Skip to content

Commit 4d3e729

Browse files
authored
Update TE-FL arguments (flagos-ai#972)
### PR Category Train ### PR Types Bug Fixes ### PR Description Redesign the parameters in TE-FL as follows: - **use_transformer_engine_fl = True** - Enables TE-FL and, by default, also enables flag_gems.enable. All Torch Ops in the framework-side Megatron-LM are replaced with Gems Ops, while the TransformerEngine side enters the new-implementation branch and likewise replaces every Torch Op with a Gems Op. - **use_transformer_engine_fl = True && disable_flag_gems_replace_torch = True** - Enables TE-FL but does NOT enable flag_gems.enable. All Torch Ops in the framework-side Megatron-LM keep their original implementations, and the TransformerEngine side still enters the new-implementation branch yet retains every original Torch Op implementation. - This mode is useful for debugging the training process to determine whether an issue lies in the operator implementation or in the TE-FL plugin-style implementation. - **use_flag_gems_replace_torch = True** - Does NOT enable TE-FL, but does enable flag_gems.enable. All Torch Ops in the framework-side Megatron-LM are replaced with Gems Ops, while the TransformerEngine side continues to use the original FusedOp implementation and does NOT enter the new branch.
1 parent 652ae9f commit 4d3e729

3 files changed

Lines changed: 31 additions & 30 deletions

File tree

flagscale/backends/Megatron-LM/megatron/core/tensor_parallel/layers.py.patch

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
diff --git a/megatron/core/tensor_parallel/layers.py b/megatron/core/tensor_parallel/layers.py
2-
index 5c6f34b70..5c943759a 100644
2+
index 5c6f34b70..c4f77ea61 100644
33
--- a/megatron/core/tensor_parallel/layers.py
44
+++ b/megatron/core/tensor_parallel/layers.py
55
@@ -448,6 +448,7 @@ class LinearWithGradAccumulationAndAsyncCommunication(torch.autograd.Function):
@@ -56,13 +56,13 @@ index 5c6f34b70..5c943759a 100644
5656
# Need to return None's as gradient has to flow for all the input arguments
5757
# provided during forward
5858
- return (sub_grad_input, grad_weight, grad_bias, None, None, None, None, None, None)
59-
+ return (sub_grad_input, grad_weight, grad_bias, None, None, None, None, None, None, None, None)
59+
+ return (sub_grad_input, grad_weight, grad_bias, None, None, None, None, None, None, None)
6060

6161
if ctx.allreduce_dgrad:
6262
handle.wait()
6363

6464
- return grad_input, grad_weight, grad_bias, None, None, None, None, None, None
65-
+ return grad_input, grad_weight, grad_bias, None, None, None, None, None, None, None, None
65+
+ return grad_input, grad_weight, grad_bias, None, None, None, None, None, None, None
6666

6767

6868
def linear_with_grad_accumulation_and_async_allreduce(

flagscale/backends/Megatron-LM/megatron/training/arguments.py.patch

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
diff --git a/megatron/training/arguments.py b/megatron/training/arguments.py
2-
index 1120c7529..761a796db 100644
2+
index 1120c7529..3facfbf30 100644
33
--- a/megatron/training/arguments.py
44
+++ b/megatron/training/arguments.py
55
@@ -67,6 +67,7 @@ def add_megatron_arguments(parser: argparse.ArgumentParser):
@@ -202,7 +202,7 @@ index 1120c7529..761a796db 100644
202202
else:
203203
args.ffn_hidden_size = 4 * args.hidden_size
204204

205-
@@ -1175,6 +1198,148 @@ def validate_args(args, defaults={}):
205+
@@ -1175,6 +1198,147 @@ def validate_args(args, defaults={}):
206206
args.recompute_granularity != 'full'
207207
), 'recompute_granularity must not be full when CUDA Graphs are enabled.'
208208

@@ -342,16 +342,15 @@ index 1120c7529..761a796db 100644
342342
+ assert args.ckpt_format == 'torch', "PEFT is only tested with torch format checkpoint"
343343
+
344344
+ if args.use_transformer_engine_fl:
345-
+ assert not args.add_bias_linear, "Do not support linear with bias in TransformerEngine-TL Now"
346-
+ assert args.context_parallel_size == 1, "DotProductAttention in TransformerEngine-FL, do not support context parallel now"
347345
+ assert not args.tp_comm_overlap, "Do not support gemm/sp comm in TransformerEngine-FL now"
348346
+ args.distributed_backend = 'flagcx'
349-
+ args.use_flag_gems = True
347+
+ if not args.disable_flag_gems_replace_torch:
348+
+ args.use_flag_gems_replace_torch = True
350349
+
351350
# Print arguments.
352351
_print_args("arguments", args)
353352

354-
@@ -1585,6 +1750,8 @@ def _add_network_size_args(parser):
353+
@@ -1585,6 +1749,8 @@ def _add_network_size_args(parser):
355354
help='Which normalization technique to use.')
356355
group.add_argument('--norm-epsilon', type=float, default=1e-5,
357356
help='Epsilon for layer norm and RMS norm.')
@@ -360,7 +359,7 @@ index 1120c7529..761a796db 100644
360359
group.add_argument('--apply-layernorm-1p', action='store_true',
361360
help='Adjust LayerNorm weights such that they are centered '
362361
'around zero. This improves numerical stability.')
363-
@@ -1608,6 +1775,10 @@ def _add_network_size_args(parser):
362+
@@ -1608,6 +1774,10 @@ def _add_network_size_args(parser):
364363
group.add_argument('--glu-linear-offset', type=float, default=0.0,
365364
help='Offset term in the GLU activation function: activation_func(x[0]) * (x[1] + offset). '
366365
'Only used when gated_linear_unit is True')
@@ -371,7 +370,7 @@ index 1120c7529..761a796db 100644
371370
group.add_argument('--onnx-safe', type=bool, required=False,
372371
help='Use workarounds for known problems with '
373372
'Torch ONNX exporter')
374-
@@ -1820,6 +1991,14 @@ def _add_logging_args(parser):
373+
@@ -1820,6 +1990,14 @@ def _add_logging_args(parser):
375374
help='The wandb experiment name.')
376375
group.add_argument('--wandb-save-dir', type=str, default='',
377376
help='Path to save the wandb results locally.')
@@ -386,7 +385,7 @@ index 1120c7529..761a796db 100644
386385
group.add_argument('--logging-level', type=int, default=None,
387386
help='Set default logging level')
388387
return parser
389-
@@ -2001,6 +2180,25 @@ def _add_training_args(parser):
388+
@@ -2001,6 +2179,25 @@ def _add_training_args(parser):
390389
'"shared_experts": recompute the shared experts in the MoE layer.'
391390
'"moe_act", "layernorm", and "mla_up_proj" use output-discarding checkpointing, '
392391
'"core_attn", "mlp", "moe", and "shared_experts" use normal checkpointing.')
@@ -412,7 +411,7 @@ index 1120c7529..761a796db 100644
412411
group.add_argument('--no-clone-scatter-output-in-embedding', action='store_false',
413412
help='If not set, clone the output of the scatter in embedding layer to GC original tensor.',
414413
dest='clone_scatter_output_in_embedding')
415-
@@ -2087,6 +2285,10 @@ def _add_training_args(parser):
414+
@@ -2087,6 +2284,10 @@ def _add_training_args(parser):
416415
help='Total number of samples to train over all '
417416
'training runs. Note that either train-iters or '
418417
'train-samples should be provided.')
@@ -423,7 +422,7 @@ index 1120c7529..761a796db 100644
423422
group.add_argument('--log-interval', type=int, default=100,
424423
help='Report loss and timing interval.')
425424
group.add_argument('--exit-interval', type=int, default=None,
426-
@@ -2210,6 +2412,10 @@ def _add_training_args(parser):
425+
@@ -2210,6 +2411,10 @@ def _add_training_args(parser):
427426
help='The communicator group names to use high priority streams.')
428427
group.add_argument('--use-te-activation-func', action='store_true',
429428
help='Use activation function kernel from Transformer Engine in MLP module.')
@@ -434,7 +433,7 @@ index 1120c7529..761a796db 100644
434433

435434
return parser
436435

437-
@@ -2268,11 +2474,26 @@ def _add_learning_rate_args(parser):
436+
@@ -2268,11 +2473,26 @@ def _add_learning_rate_args(parser):
438437
'and initial warmup, the learning rate at each '
439438
'iteration would be different.')
440439
group.add_argument('--lr-decay-style', type=str, default='linear',
@@ -462,7 +461,7 @@ index 1120c7529..761a796db 100644
462461
group.add_argument('--lr-decay-iters', type=int, default=None,
463462
help='number of iterations to decay learning rate over,'
464463
' If None defaults to `--train-iters`')
465-
@@ -2331,6 +2552,8 @@ def _add_checkpointing_args(parser):
464+
@@ -2331,6 +2551,8 @@ def _add_checkpointing_args(parser):
466465
group.add_argument('--save-retain-interval', type=int, default=None,
467466
help='Number of iterations between retained checkpoints (other'
468467
'checkpoints _except the last checkpoint_ are automatically deleted).')
@@ -471,7 +470,7 @@ index 1120c7529..761a796db 100644
471470
group.add_argument('--no-save-optim', action='store_true', default=None,
472471
help='Do not save current optimizer.')
473472
group.add_argument('--no-save-rng', action='store_true', default=None,
474-
@@ -2380,6 +2603,8 @@ def _add_checkpointing_args(parser):
473+
@@ -2380,6 +2602,8 @@ def _add_checkpointing_args(parser):
475474
group.add_argument('--no-use-tokenizer-model-from-checkpoint-args', action='store_false',
476475
dest='use_tokenizer_model_from_checkpoint_args',
477476
help='If set, do not use tokenizer model path from checkpoint')
@@ -480,7 +479,7 @@ index 1120c7529..761a796db 100644
480479
group.add_argument('--exit-on-missing-checkpoint', action='store_true',
481480
help="If '--load' is set, but checkpoint is not found "
482481
"(e.g., path typo), then exit instead of random "
483-
@@ -2541,7 +2766,7 @@ def _add_distributed_args(parser):
482+
@@ -2541,7 +2765,7 @@ def _add_distributed_args(parser):
484483
default=False, help='if set, overlap pipeline parallel communication in warmup and flush',
485484
dest='overlap_p2p_comm_warmup_flush')
486485
group.add_argument('--distributed-backend', default='nccl',
@@ -489,7 +488,7 @@ index 1120c7529..761a796db 100644
489488
help='Which backend to use for distributed training.')
490489
group.add_argument('--distributed-timeout-minutes', type=int, default=10,
491490
help='Timeout minutes for torch.distributed.')
492-
@@ -2592,6 +2817,11 @@ def _add_distributed_args(parser):
491+
@@ -2592,6 +2816,11 @@ def _add_distributed_args(parser):
493492
'complete it instead. Also turns on '
494493
'--use-cpu-initialization flag. This is for '
495494
'external DDP manager.' )
@@ -501,7 +500,7 @@ index 1120c7529..761a796db 100644
501500
group.add_argument('--account-for-embedding-in-pipeline-split', action='store_true',
502501
default=False, help='If set, *input* embedding layer will be treated as a standard transformer'
503502
'layer in the context of partition and placement for pipeline parallelism.')
504-
@@ -2636,6 +2866,10 @@ def _add_distributed_args(parser):
503+
@@ -2636,6 +2865,10 @@ def _add_distributed_args(parser):
505504
help='If set, keep the fp8 transpose cache when using Megatron FSDP.')
506505
group.add_argument('--enable-full-sharding-in-hsdp', action='store_true',
507506
help='If set, enable full sharding in megatron-fsdp Hybrid Sharded Data Parallel (HSDP) mode.')
@@ -512,7 +511,7 @@ index 1120c7529..761a796db 100644
512511
group.add_argument('--num-distributed-optimizer-instances', type=int, default=1,
513512
help='Number of Distributed Optimizer copies across Data Parallel domain.')
514513
group.add_argument('--use-torch-fsdp2', action='store_true',
515-
@@ -2690,6 +2924,9 @@ def _add_validation_args(parser):
514+
@@ -2690,6 +2923,9 @@ def _add_validation_args(parser):
516515
group.add_argument('--eval-interval', type=int, default=1000,
517516
help='Interval between running evaluation on '
518517
'validation set.')
@@ -522,7 +521,7 @@ index 1120c7529..761a796db 100644
522521
group.add_argument("--test-mode", action="store_true", help='Run all real-time test alongside the experiment.')
523522
group.add_argument('--skip-train', action='store_true',
524523
default=False, help='If set, bypass the training loop, '
525-
@@ -2708,6 +2945,8 @@ def _add_tokenizer_args(parser):
524+
@@ -2708,6 +2944,8 @@ def _add_tokenizer_args(parser):
526525
'automatically calculated from vocab-size.')
527526
group.add_argument('--vocab-file', type=str, default=None,
528527
help='Path to the vocab file.')
@@ -531,7 +530,7 @@ index 1120c7529..761a796db 100644
531530
group.add_argument('--merge-file', type=str, default=None,
532531
help='Path to the BPE merge file.')
533532
group.add_argument('--vocab-extra-ids', type=int, default=0,
534-
@@ -2726,8 +2965,17 @@ def _add_tokenizer_args(parser):
533+
@@ -2726,8 +2964,17 @@ def _add_tokenizer_args(parser):
535534
'MultimodalTokenizer',
536535
'NullTokenizer',
537536
'NullMultimodalTokenizer',
@@ -550,7 +549,7 @@ index 1120c7529..761a796db 100644
550549
group.add_argument('--tokenizer-model', type=str, default=None,
551550
help='Sentencepiece tokenizer model.')
552551
group.add_argument('--tokenizer-metadata', type=str, default=None,
553-
@@ -2768,6 +3016,11 @@ def _add_data_args(parser):
552+
@@ -2768,6 +3015,11 @@ def _add_data_args(parser):
554553
group.add_argument('--valid-data-path', nargs='*', default=None,
555554
help='The weight and prefix list for an independent validation dataset. '
556555
'Follows the same pattern rules as --data-path.')
@@ -562,7 +561,7 @@ index 1120c7529..761a796db 100644
562561
group.add_argument('--test-data-path', nargs='*', default=None,
563562
help='The weight and prefix list for an independent test dataset. '
564563
'Follows the same pattern rules as --data-path.')
565-
@@ -2816,11 +3069,18 @@ def _add_data_args(parser):
564+
@@ -2816,11 +3068,18 @@ def _add_data_args(parser):
566565
'end-of-document token.')
567566
group.add_argument('--eod-mask-loss', action='store_true',
568567
help='Mask loss for the end of document tokens.')
@@ -581,7 +580,7 @@ index 1120c7529..761a796db 100644
581580
group.add_argument('--object-storage-cache-path', type=str, default=None,
582581
help='Path to cache index files when using s3 or msc dataloader')
583582
group.add_argument('--mid-level-dataset-surplus', type=float, default=0.005,
584-
@@ -2897,6 +3157,19 @@ def _add_biencoder_args(parser):
583+
@@ -2897,6 +3156,19 @@ def _add_biencoder_args(parser):
585584
return parser
586585

587586

@@ -601,7 +600,7 @@ index 1120c7529..761a796db 100644
601600
def _add_vision_args(parser):
602601
group = parser.add_argument_group(title="vision")
603602

604-
@@ -2967,6 +3240,8 @@ def _add_vision_args(parser):
603+
@@ -2967,6 +3239,8 @@ def _add_vision_args(parser):
605604
help='Whether to layer normalize the q and k attention embeddings.')
606605
group.add_argument('--qk-l2-norm', action='store_true',
607606
help='Use llama 4 qk l2 norm')
@@ -610,7 +609,7 @@ index 1120c7529..761a796db 100644
610609

611610
return parser
612611

613-
@@ -3275,3 +3550,92 @@ def _add_sft_args(parser):
612+
@@ -3275,3 +3549,94 @@ def _add_sft_args(parser):
614613
group.add_argument('--sft-tokenizer-prompt-format', type=str, default="nemotron-h-aligned",
615614
help='SFT prompt format.')
616615
return parser
@@ -690,7 +689,9 @@ index 1120c7529..761a796db 100644
690689
+ group = parser.add_argument_group(title="flag engine")
691690
+ group.add_argument('--use-transformer-engine-fl', action='store_true',
692691
+ help='Enable transformer engine fl for training')
693-
+ group.add_argument('--use-flag-gems', action='store_true',
692+
+ group.add_argument('--disable-flag-gems-replace-torch', action='store_true',
693+
+ help='Disable flag gems for training when using te-fl')
694+
+ group.add_argument('--use-flag-gems-replace-torch', action='store_true',
694695
+ help='Enable flag gems for training')
695696
+ group.add_argument('--flag-gems-log-path', type=str, default=None,
696697
+ help='Path of flag gems logging')

flagscale/train/train.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2560,7 +2560,7 @@ def get_e2e_base_metrics():
25602560
cuda_graph_helper.create_cudagraphs()
25612561

25622562
# enable flag_gems for transformer_engine_fl
2563-
if args.use_flag_gems:
2563+
if args.use_flag_gems_replace_torch:
25642564
if not HAVE_GEMS:
25652565
raise ValueError(f"Can not import flag gems")
25662566
else:

0 commit comments

Comments
 (0)