forked from flagos-ai/FlagScale
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraining.py
More file actions
4232 lines (3799 loc) · 183 KB
/
Copy pathtraining.py
File metadata and controls
4232 lines (3799 loc) · 183 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
"""Pretrain utilities."""
import time
# The earliest we can measure the start time.
_TRAIN_START_TIME = time.time()
# Startup timestamps for tracking program initialization phases
_STARTUP_TIMESTAMPS = {
'program_start': None, # Set by entry script before imports
'main_entry': None, # Set by entry script at start of __main__
'pretrain_entry': None, # Set at top of pretrain()
}
def set_startup_timestamps(program_start=None, main_entry=None):
"""Set startup timestamps from the entry script.
Call this after imports but before calling pretrain() to register
the program start time and main entry time.
Args:
program_start: Timestamp captured at very start of program, before any imports.
main_entry: Timestamp captured right after entering __main__ block.
"""
global _TRAIN_START_TIME, _STARTUP_TIMESTAMPS
if program_start is not None:
_TRAIN_START_TIME = program_start
_STARTUP_TIMESTAMPS['program_start'] = program_start
if main_entry is not None:
_STARTUP_TIMESTAMPS['main_entry'] = main_entry
from collections import defaultdict
import copy
import dataclasses
from datetime import datetime, timedelta
import functools
import gc
import inspect
import json
import logging
import math
import os
import socket
import sys
from contextlib import nullcontext
from pathlib import Path
from typing import Any, Optional, Dict
import torch.distributed
from megatron.core.optimizer.distrib_optimizer import DistributedOptimizer
from megatron.core.optimizer_param_scheduler import get_canonical_lr_for_logging
from .log_handler import CustomHandler
# Make default logging level INFO, but filter out all log messages not from MCore.
logging.basicConfig(handlers=[CustomHandler()], level=logging.INFO)
from .theoretical_memory_usage import report_theoretical_memory
_LEGACY_TRAIN_START_TIME = time.time() # NOTE(asolergi-nv): Legacy timestamp
import torch
try:
from megatron.rl import rl_utils
has_rl_utils = True
except ImportError:
has_rl_utils = False
# Canonical list of RL timer names to include in timers_to_log.
# When the profiling branch is merged, this will be imported from rl_profiling
# as RL_LOGGABLE_TIMER_NAMES instead of being defined here.
RL_LOGGABLE_TIMER_NAMES = [
# Top-level RL phases
'rl/rollout-collection',
'rl/prepare-data-for-update',
# Rollout collection breakdown
'rl/inference-setup',
'rl/collect-rollouts',
'rl/sync-rollouts',
'rl/suspend-engine',
# Optimizer offload/restore
'rl/offload-optimizer-before-inference',
'rl/restore-optimizer-after-inference',
'rl/offload-kv-cache-after-inference',
'rl/restore-kv-cache-before-inference',
# Fine-grained offload/restore breakdown
'rl/restore/grad-buffers',
'rl/restore/optimizer-state',
'rl/restore/wait-for-transfers',
'rl/offload/grad-buffers',
'rl/offload/optimizer-state',
# Weight prefetching
'rl/prefetch-weights-to-gpu',
'rl/prefetch-weights-to-cpu',
# Data preparation
'rl/compute-group-stats',
'rl/prepare-advantages',
'rl/prepare-trajectories',
'rl/get-ltor-masks',
'rl/create-dataloader',
'rl/sequence-packing',
'rl/align-inference-logprobs',
'rl/log-wandb-tb',
'rl/pack-sequences',
'rl/regather-trajectories',
# Logprobs computation
'rl/compute-logprobs',
'rl/compute-old-logprobs',
'rl/compute-ref-logprobs',
'rl/get-logprobs',
'rl/forward-pass',
'rl/log-softmax',
# Inference / cuda graphs
'rl/build-cuda-graphs',
'rl/wait-for-decode-only',
]
try:
from modelopt.torch.distill.plugins.megatron import (
get_tensor_shapes_adjust_fn_for_distillation,
)
has_nvidia_modelopt = True
except ImportError:
has_nvidia_modelopt = False
try:
from nvidia_resiliency_ext.inprocess import CallWrapper
except ImportError:
CallWrapper = type(None)
from megatron.core import mpu, tensor_parallel
from megatron.core.models.gpt.experimental_attention_variant_module_specs import (
is_linear_attention_variant,
)
from megatron.core.utils import (
check_param_hashes_across_dp_replicas,
get_attr_wrapped_model,
get_model_config,
get_pg_size,
get_pg_rank,
StragglerDetector,
)
from megatron.core.fp8_utils import correct_amax_history_if_needed
from megatron.core.process_groups_config import ProcessGroupCollection
from megatron.core.pipeline_parallel.utils import (
is_pp_first_stage,
is_pp_last_stage,
is_vp_first_stage,
is_vp_last_stage,
is_dualpipev_first_stage,
is_dualpipev_last_stage,
)
from megatron.core.optimizer import get_mup_config_overrides, get_standard_config_overrides
from megatron.training.checkpointing import load_checkpoint
from megatron.training.checkpointing import save_checkpoint, save_grads
from megatron.training.checkpointing import checkpoint_exists
from megatron.training.checkpointing import get_loaded_iteration
from megatron.core.full_cuda_graph import FullCudaGraphWrapper
from megatron.core.optimizer.optimizer_cuda_graph import OptimizerCudaGraphWrapper
from megatron.core.transformer.cuda_graphs import TECudaGraphHelper
from megatron.core.transformer.enums import CudaGraphScope
from megatron.core.transformer.module import Float16Module
from megatron.core.distributed import DistributedDataParallelConfig, TorchFullyShardedDataParallelConfig
from megatron.core.distributed import DistributedDataParallel as DDP
from megatron.core.distributed.fsdp.mcore_fsdp_adapter import FullyShardedDataParallel as megatron_FSDP
from megatron.core.optimizer.optimizer import param_group_identifier_keys
from megatron.core.optimizer.qk_clip import clip_qk
try:
from megatron.core.distributed import TorchFullyShardedDataParallel as torch_FSDP
HAVE_FSDP2 = True
except ImportError:
HAVE_FSDP2 = False
from megatron.core.distributed import finalize_model_grads
from megatron.core.enums import ModelType
from megatron.core.optimizer import get_megatron_optimizer, AdamOptimizerConfig, SGDOptimizerConfig, OptimizerConfig, ParamKey
from megatron.core.optimizer.muon import get_megatron_muon_optimizer
from megatron.core.rerun_state_machine import (
get_rerun_state_machine,
destroy_rerun_state_machine,
RerunDataIterator,
RerunMode,
)
from megatron.training.initialize import initialize_megatron
from megatron.training.initialize import write_args_to_tensorboard
from megatron.training.initialize import set_jit_fusion_options
from megatron.training.utils import get_batch_on_this_cp_rank, get_batch_on_this_tp_rank, is_hybrid_model
from megatron.training.datasets.data_samplers import build_pretraining_data_loader
from megatron.core.datasets.data_schedule import HybridCPDataLoaderWrapper
from megatron.core.optimizer_param_scheduler import OptimizerParamScheduler
from megatron.core.transformer.moe import upcycling_utils
from megatron.core.transformer.moe.moe_utils import track_moe_metrics, clear_aux_losses_tracker
from megatron.core.transformer.experimental_attention_variant.dsa import DSAIndexerLossLoggingHelper
from megatron.core.transformer.multi_token_prediction import MTPLossLoggingHelper
from megatron.core.parallel_state import (
destroy_global_memory_buffer,
destroy_model_parallel,
update_pg_timeout
)
from megatron.core.inference.symmetric_memory import SymmetricMemoryManager
from megatron.core.inference.unified_memory import create_unified_mempool
from megatron.core.resharding.refit import swap_model_weights
try:
from torch_memory_saver import torch_memory_saver
torch_memory_saver.hook_mode = "torch"
HAVE_TORCH_MEMORY_SAVER = True
except ImportError:
HAVE_TORCH_MEMORY_SAVER = False
from megatron.core.pipeline_parallel import get_forward_backward_func
from megatron.core.num_microbatches_calculator import (
destroy_num_microbatches_calculator,
get_current_global_batch_size,
get_current_running_global_batch_size,
get_num_microbatches,
update_num_microbatches
)
from megatron.training.async_utils import maybe_finalize_async_save
from megatron.training.utils import (
append_to_progress_log,
calc_params_l2_norm,
check_adlr_autoresume_termination,
logical_and_across_model_parallel_group,
reduce_max_stat_across_model_parallel_group,
is_last_rank,
print_rank_0,
print_rank_last,
report_memory,
unwrap_model,
update_use_dist_ckpt,
to_empty_if_meta_device,
)
from megatron.training.global_vars import (
destroy_global_vars,
get_args,
get_signal_handler,
get_timers,
get_tensorboard_writer,
get_wandb_writer,
get_one_logger,
get_tokenizer,
get_energy_monitor,
)
from . import one_logger_utils
from .dgrad_logging import enable_dgrad_logging, disable_dgrad_logging, save_dgrads
from megatron.training import ft_integration
########## FlagScale Begin ##########
from megatron.training.global_vars import get_spiky_loss_detector
from megatron.training.peft import PEFT # Import PEFT from peft module
from megatron.plugin.hetero.parallel_context import get_parallel_context
from flagscale.runner.straggler import (
OptionalSectionContext,
StragglerConfig as FSStragglerConfig,
StragglerDetector as FSStragglerDetector,
)
from flagscale.train.perf_monitor.hooks import (
initialize_perf_monitor,
perf_monitor_end_iteration,
perf_monitor_end_training,
perf_monitor_start_iteration,
)
from megatron.plugin.platform import get_platform
cur_platform = get_platform()
import megatron.plugin_flagscale
########## FlagScale End ##########
stimer = StragglerDetector()
_fs_straggler_detector = None
def get_fs_straggler_detector():
"""Get the global FlagScale straggler detector."""
return _fs_straggler_detector
def init_fs_straggler_detector(args):
"""Initialize the FlagScale straggler detector from parsed args."""
global _fs_straggler_detector
if not getattr(args, "enable_straggler_detection", False):
_fs_straggler_detector = None
return None
config = FSStragglerConfig(
enabled=True,
profiling_interval=getattr(args, "straggler_profiling_interval", 10),
report_interval_steps=getattr(args, "straggler_report_interval", 100),
straggler_threshold=getattr(args, "straggler_threshold", 1.5),
warmup_steps=getattr(args, "straggler_warmup_steps", 10),
gather_on_rank0=True,
enable_comm_logging=getattr(args, "straggler_enable_comm_logging", True),
enable_gpu_profile=getattr(args, "straggler_enable_gpu_profile", True),
)
rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
local_rank = int(os.environ.get("LOCAL_RANK", 0))
hostname = os.environ.get("HOSTNAME") or socket.gethostname()
_fs_straggler_detector = FSStragglerDetector(
config=config,
rank=rank,
world_size=world_size,
node_name=f"{hostname}:gpu{local_rank}",
)
return _fs_straggler_detector
def _save_straggler_report(report, log_dir: Optional[str], iteration: int):
"""Persist a straggler report and print a text summary."""
if log_dir is None:
return
os.makedirs(log_dir, exist_ok=True)
hostname = os.environ.get("HOSTNAME") or socket.gethostname()
report_path = os.path.join(log_dir, f"straggler_report_{hostname}_step_{iteration}.json")
try:
with open(report_path, "w") as file_obj:
json.dump(report.to_dict(), file_obj, indent=2)
except Exception as exc:
print(f"[{hostname}] Warning: Could not save straggler report: {exc}")
print(f"\n{report.to_text()}")
def _is_global_rank_zero() -> bool:
"""Return True only on global rank 0, or in non-distributed execution."""
if torch.distributed.is_available() and torch.distributed.is_initialized():
return torch.distributed.get_rank() == 0
return True
from megatron.core.msc_utils import MultiStorageClientFeature, open_file
def destroy_global_state():
destroy_global_vars()
destroy_num_microbatches_calculator()
destroy_global_memory_buffer()
SymmetricMemoryManager.destroy()
destroy_model_parallel()
destroy_rerun_state_machine()
def print_datetime(string, override_timestamp=None):
"""Note that this call will sync across all ranks. Use override_timestamp if provided;
otherwise use current timestamp."""
torch.distributed.barrier()
if override_timestamp is None:
time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
else:
time_str = datetime.fromtimestamp(override_timestamp).strftime('%Y-%m-%d %H:%M:%S.%f')
print_rank_0(f'[{string}] datetime: {time_str} ')
def num_floating_point_operations(args, batch_size):
def mlp_layer_flops(batch_size, seq_len, hidden_size, expansion=4.0, swiglu=False):
"""Calculate FLOPs for an MLP layer."""
scale_factor = 3.0 / 2.0 if swiglu else 1.0
return 4 * expansion * scale_factor * batch_size * seq_len * hidden_size**2
def moe_layer_flops(batch_size, seq_len, hidden_size, moe_ffn_hidden_size,
shared_expert_ffn_hidden_size, num_experts_routed_to,
moe_latent_size=None, swiglu=False):
"""Calculate FLOPs for an MoE layer."""
scale_factor = 3.0 / 2.0 if swiglu else 1.0
if moe_latent_size is None:
routed_flops = (4 * batch_size * seq_len * hidden_size *
moe_ffn_hidden_size * num_experts_routed_to * scale_factor)
else:
# Routed experts run on moe_latent_size.
routed_flops = (4 * batch_size * seq_len * moe_latent_size *
moe_ffn_hidden_size * num_experts_routed_to * scale_factor)
# Up proj and down proj.
routed_flops += (4 * batch_size * seq_len * hidden_size * moe_latent_size)
shared_flops = 4 * batch_size * seq_len * hidden_size * shared_expert_ffn_hidden_size * scale_factor
return routed_flops + shared_flops
def attn_layer_flops(
batch_size, seq_len, hidden_size, num_heads, gqa=True, gqa_groups=8, kv_channels=None
):
"""Calculate FLOPs for an attention layer."""
p = (kv_channels * num_heads / hidden_size) if kv_channels else 1
g = gqa_groups if gqa else num_heads
return (
4
* batch_size
* seq_len
* hidden_size
* p
* (hidden_size + (hidden_size * (g / num_heads)) + (seq_len / 2))
)
def mamba_layer_flops(batch_size, seq_len, hidden_size, state_dim=16,
head_dim=64, num_groups=1, num_heads=128):
"""Calculate FLOPs for a Mamba layer."""
# Note (rwaleffe): flops estimate for scan should be updated based on new SSD kernels,
# but small percent of overall layer flops
d_in = 2 * hidden_size
if num_heads:
nheads = num_heads
else:
nheads = d_in // head_dim
return (
(
2
* batch_size
* seq_len
* hidden_size
* (2 * d_in + 2 * num_groups * state_dim + nheads)
) # in_proj
+ (7 * batch_size * seq_len * d_in * state_dim) # scan
+ (2 * batch_size * seq_len * d_in * hidden_size) # out_proj
)
def gdn_layer_flops(batch_size, seq_len, hidden_size,
qk_head_dim=128, v_head_dim=128,
num_qk_heads=16, num_v_heads=32,
conv_kernel_dim=4):
"""Calculate FLOPs for a Gated Delta Net (GDN) layer."""
qk_dim = qk_head_dim * num_qk_heads
v_dim = v_head_dim * num_v_heads
return (
2 * batch_size * seq_len * (
# in_proj: hidden_size -> (2*qk_dim + 2*v_dim + 2*num_v_heads)
hidden_size * (2 * qk_dim + 2 * v_dim + 2 * num_v_heads)
# conv1d
+ conv_kernel_dim * (2 * qk_dim + v_dim)
# gated delta rule: KK^T, VK^T, S(a(I-bKK^T)), and SQ
+ num_v_heads * (v_head_dim ** 2) * 4
# out_proj: v_dim -> hidden_size
+ hidden_size * v_dim
)
)
def hybrid_flops(batch_size, seq_len, hidden_size,
num_attn_layers, num_mamba_layers, num_mlp_layers, num_moe_layers,
num_gdn_layers=0,
mamba_state_dim=128, mamba_head_dim=64,
mamba_num_groups=8, mamba_num_heads=128,
num_attn_heads=32, gqa=True,
gqa_groups=8, kv_channels=None,
mlp_expansion=4.0, swiglu=False,
moe_latent_size=None,
moe_ffn_hidden_size=2048, shared_expert_ffn_hidden_size=2048, num_experts_routed_to=1,
gdn_qk_head_dim=128, gdn_v_head_dim=128,
gdn_num_qk_heads=16, gdn_num_v_heads=32,
gdn_conv_kernel_dim=4,
vocab_size=256000, mtp_num_layers=0):
"""Calculate total FLOPs for the hybrid model."""
flops_fwd = (
num_attn_layers * attn_layer_flops(batch_size, seq_len, hidden_size,
num_attn_heads, gqa, gqa_groups, kv_channels) +
num_mlp_layers * mlp_layer_flops(batch_size, seq_len, hidden_size,
mlp_expansion, swiglu) +
num_mamba_layers * mamba_layer_flops(batch_size, seq_len, hidden_size,
mamba_state_dim, mamba_head_dim,
mamba_num_groups, mamba_num_heads) +
num_moe_layers * moe_layer_flops(batch_size, seq_len, hidden_size, moe_ffn_hidden_size,
shared_expert_ffn_hidden_size, num_experts_routed_to,
moe_latent_size, swiglu) +
num_gdn_layers * gdn_layer_flops(batch_size, seq_len, hidden_size,
gdn_qk_head_dim, gdn_v_head_dim,
gdn_num_qk_heads, gdn_num_v_heads,
gdn_conv_kernel_dim) +
(2 * batch_size * seq_len * hidden_size * vocab_size * (1 + mtp_num_layers)) # logits computation
)
return flops_fwd * 3
def transformer_flops():
"""Calculate FLOPs for a standard Transformer model."""
# TODO(helenn/dnarayanan): Refactor this to reuse the helper methods.
# Group Query Attention.
if not args.group_query_attention:
args.num_query_groups = args.num_attention_heads
# MoE.
if args.num_experts is None:
# Every Transformer MLP is dense.
num_dense_layers = args.num_layers
num_moe_layers = 0
num_experts_routed_to = 0
last_layer_is_moe = 0
else:
# Calculate number of dense and MoE Transformer MLPs.
if isinstance(args.moe_layer_freq, int):
moe_layer_pattern = [
1 if (i % args.moe_layer_freq == 0) else 0 for i in range(args.num_layers)
]
elif isinstance(args.moe_layer_freq, list):
moe_layer_pattern = args.moe_layer_freq
else:
raise RuntimeError("Illegal --moe-layer-freq argument provided!")
assert len(moe_layer_pattern) == args.num_layers, (
f"Invalid length of moe_layer_pattern: {len(moe_layer_pattern)}, "
f"expected {args.num_layers}, "
f"current moe layer pattern: {args.moe_layer_freq}"
)
num_moe_layers = sum(moe_layer_pattern) # Number of 1s in `moe_layer_pattern`.
num_dense_layers = args.num_layers - num_moe_layers
num_experts_routed_to = args.moe_router_topk
last_layer_is_moe = moe_layer_pattern[-1]
if args.mtp_num_layers is not None:
mtp_num_layers = args.mtp_num_layers
num_moe_layers += last_layer_is_moe * mtp_num_layers
num_dense_layers += (1 - last_layer_is_moe) * mtp_num_layers
num_layers = args.num_layers + mtp_num_layers
else:
mtp_num_layers = 0
num_layers = args.num_layers
moe_ffn_hidden_size = (
args.moe_ffn_hidden_size
if args.moe_ffn_hidden_size is not None
else args.ffn_hidden_size
)
moe_latent_size = args.moe_latent_size
shared_expert_ffn_hidden_size = (
0
if args.moe_shared_expert_intermediate_size is None
else args.moe_shared_expert_intermediate_size
)
# - 3x: Each GEMM in the model needs to be performed 3 times (forward pass,
# backward wgrad [weight gradient], backward dgrad [data gradient]).
forward_backward_expansion_factor = 3
# - 2x: A GEMM of a m*n tensor with a n*k tensor requires 2mnk floating-point operations.
fma_expansion_factor = 2
# - 3x (SwiGLU enabled): h->2*ffn_h GEMM and ffn_h->h GEMM are stacked.
# - 2x (SwiGLU disabled): h->ffn_h GEMM and ffn_h->h GEMM are stacked.
ffn_expansion_factor = 3 if args.swiglu else 2
if args.multi_latent_attention:
assert not args.group_query_attention
'''
Basic arithmetic
let B is batch size, s is seq_len, h is embedding dim,
for one self_attnetion block (prenorm is not included)
qkv projection: 6Bsh^2
attn: 2Bs^2h
attn over value: 2Bs^2h
oproj: 2Bsh^2
references
https://arxiv.org/abs/2305.10403
https://arxiv.org/abs/2205.05198
'''
if args.experimental_attention_variant == "dsv4_hybrid":
## DSv4 hybrid MLA projections (per layer, per token).
## In dsv4_hybrid mode, qk_head_dim + qk_pos_emb_head_dim == v_head_dim
## (qk_head_dim is derived as v_head_dim - qk_pos_emb_head_dim), and the
## joint KV is produced by a single hidden -> v_head_dim projection.
## Full core attention is replaced by sparse attention and is accounted
## for in the dsv4_hybrid branch below.
q_term = args.q_lora_rank * (
args.hidden_size
+ args.num_attention_heads * args.v_head_dim
+ 1 # q norm
)
kv_term = args.hidden_size * args.v_head_dim + args.v_head_dim # kv proj + kv norm
## Grouped low-rank output projection:
## wo_a: (n_head * v_head_dim) -> (o_groups * o_lora_rank)
## linear_proj: (o_groups * o_lora_rank) -> hidden
o_term = (
args.num_attention_heads * args.v_head_dim * args.o_lora_rank
+ args.o_groups * args.o_lora_rank * args.hidden_size
)
standard_self_attn_term = (
forward_backward_expansion_factor
* fma_expansion_factor
* (q_term + kv_term + o_term)
)
else:
## MLA
if args.q_lora_rank is None:
q_term = (
args.hidden_size
* args.num_attention_heads
* (args.qk_head_dim + args.qk_pos_emb_head_dim)
)
else:
q_term = args.q_lora_rank * (
args.hidden_size
+ args.num_attention_heads * (args.qk_head_dim + args.qk_pos_emb_head_dim)
+ 1
)
standard_self_attn_term = (
forward_backward_expansion_factor
* fma_expansion_factor
* (
## q lora + rope + q norm
q_term
## kv lora + rope + kv norm
+ args.kv_lora_rank
* (
args.hidden_size
+ args.num_attention_heads * (args.qk_head_dim + args.v_head_dim)
+ 1
)
+ args.hidden_size * args.qk_pos_emb_head_dim
## o proj
+ (args.num_attention_heads * args.v_head_dim) * args.hidden_size
## core attn
+ args.seq_length
* (args.num_attention_heads * (args.qk_head_dim + args.qk_pos_emb_head_dim))
/ 2 # causal mask (only half of the mask is non-zero)
+ args.seq_length * args.num_attention_heads * args.v_head_dim / 2
)
)
else:
## MHA or GQA
query_projection_size = args.kv_channels * args.num_attention_heads
key_projection_size = args.kv_channels * args.num_query_groups
value_projection_size = args.kv_channels * args.num_query_groups
gate_projection_size = query_projection_size if args.attention_output_gate else 0
standard_self_attn_term = (
forward_backward_expansion_factor
* fma_expansion_factor
* (
## qkv proj
args.hidden_size
* (
query_projection_size
+ key_projection_size
+ value_projection_size
+ gate_projection_size
)
## core attention
+ query_projection_size
* args.seq_length
/ 2 # causal mask (only half of the mask is non-zero)
* 2 # QK^T and (QK^T)V
## out proj
+ query_projection_size
* args.hidden_size
)
)
if is_linear_attention_variant(args.experimental_attention_variant):
# Calculate number of dense and MoE Transformer MLPs.
if isinstance(args.linear_attention_freq, int):
linear_attention_pattern = [
# [1,1,...,1,0,1,1,...,1,0,...]
0 if ((i + 1) % args.linear_attention_freq == 0)
else 1 for i in range(num_layers)
]
elif isinstance(args.linear_attention_freq, list):
linear_attention_pattern = args.linear_attention_freq
assert len(linear_attention_pattern) == num_layers, (
f"Invalid length of linear_attention_pattern: {len(linear_attention_pattern)}, "
f"expected {num_layers}, "
f"current linear attention pattern: {args.linear_attention_freq}"
)
elif args.linear_attention_freq is None:
# This should be caught by config validation, but raise here as a safety check
raise ValueError(
f"Linear attention type {args.experimental_attention_variant} is specified "
"but linear_attention_freq is None. "
"Please set linear_attention_freq to specify the LA/SDPA layer pattern."
)
else:
raise ValueError(
f"Invalid linear_attention_freq: {type(args.linear_attention_freq)},"
f" {args.linear_attention_freq}"
)
num_linear_attention_layers = sum(linear_attention_pattern)
num_standard_attention_layers = num_layers - num_linear_attention_layers
if args.experimental_attention_variant == "gated_delta_net":
# Calculate the FLOPs for the gated delta net attention.
qk_head_dim = args.linear_key_head_dim
v_head_dim = args.linear_value_head_dim
num_qk_heads = args.linear_num_key_heads
num_v_heads = args.linear_num_value_heads
qk_dim = qk_head_dim * num_qk_heads
v_dim = v_head_dim * num_v_heads
linear_self_attn_term = (
forward_backward_expansion_factor
* fma_expansion_factor
* (
## in proj
args.hidden_size
* (2 * qk_dim + 2 * v_dim + 2 * num_v_heads)
## conv1d
+ args.linear_conv_kernel_dim
* (2 * qk_dim + v_dim)
## gated delta rule
+ num_v_heads
* (v_head_dim ** 2)
* 4 # KK^T, VK^T, S(a(I-bKK^T)), and SQ
## out proj
+ args.hidden_size
* v_dim
)
)
else:
raise ValueError(
"Invalid experimental_attention_variant: "
f"{args.experimental_attention_variant}"
)
else:
num_linear_attention_layers = 0
linear_self_attn_term = 0
num_standard_attention_layers = num_layers
self_attn_term = (
linear_self_attn_term * num_linear_attention_layers
+ standard_self_attn_term * num_standard_attention_layers
)
total_floating_point_operations = (
batch_size
* args.seq_length
* (
# MLP
forward_backward_expansion_factor
* fma_expansion_factor
* args.hidden_size
* (
# dense layer (deepseek v2, v3 style)
(args.ffn_hidden_size * ffn_expansion_factor)
* num_dense_layers
# routed experts
+ (
(moe_ffn_hidden_size * num_experts_routed_to * ffn_expansion_factor)
if moe_latent_size is None
else (
(
moe_ffn_hidden_size
* num_experts_routed_to
* ffn_expansion_factor
* moe_latent_size
/ args.hidden_size
) # Routed experts run on moe_latent_size.
+ 2 * moe_latent_size # Up proj and down proj.
)
)
* num_moe_layers
# Shared Experts.
+ (shared_expert_ffn_hidden_size * ffn_expansion_factor)
* num_moe_layers
)
# Self Attention
+ self_attn_term
# MTP norms and proj
+ forward_backward_expansion_factor
* fma_expansion_factor
* mtp_num_layers
* (
# MTP eh norm + final nrom
3 * args.hidden_size
# MTH eh proj
+ 2 * args.hidden_size * args.hidden_size
)
# Logit.
+ forward_backward_expansion_factor
* fma_expansion_factor
* args.hidden_size
* args.padded_vocab_size
* (mtp_num_layers + 1) # MTP + final logit
)
)
return total_floating_point_operations
# Main entrypoint for FLOPs calculation.
if is_hybrid_model(args):
# Calculate the number of each type of layer.
from operator import itemgetter
from megatron.core.ssm.mamba_hybrid_layer_allocation import Symbols, get_hybrid_layer_counts
num_mamba_layers, num_gdn_layers, num_attn_layers, num_mlp_layers, num_moe_layers = (
itemgetter(Symbols.MAMBA, Symbols.GDN, Symbols.ATTENTION, Symbols.MLP, Symbols.MOE)(
get_hybrid_layer_counts(args.hybrid_layer_pattern)
)
)
mtp_num_layers = args.mtp_num_layers
if mtp_num_layers is None:
mtp_num_layers = 0
# Compute hybrid model FLOPs.
return hybrid_flops(
batch_size=batch_size,
seq_len=args.seq_length,
hidden_size=args.hidden_size,
num_attn_layers=num_attn_layers,
num_mamba_layers=num_mamba_layers,
num_mlp_layers=num_mlp_layers,
num_moe_layers=num_moe_layers,
num_gdn_layers=num_gdn_layers,
mamba_state_dim=args.mamba_state_dim,
mamba_head_dim=args.mamba_head_dim,
mamba_num_groups=args.mamba_num_groups,
mamba_num_heads=args.mamba_num_heads,
num_attn_heads=args.num_attention_heads,
gqa=args.group_query_attention,
gqa_groups=args.num_query_groups,
kv_channels=args.kv_channels,
mlp_expansion=args.ffn_hidden_size / args.hidden_size,
swiglu=args.swiglu,
moe_latent_size=args.moe_latent_size,
moe_ffn_hidden_size=(args.moe_ffn_hidden_size if args.moe_ffn_hidden_size is not None
else args.ffn_hidden_size),
shared_expert_ffn_hidden_size=(0 if args.moe_shared_expert_intermediate_size is None
else args.moe_shared_expert_intermediate_size),
num_experts_routed_to=args.moe_router_topk,
gdn_qk_head_dim=args.linear_key_head_dim or 128,
gdn_v_head_dim=args.linear_value_head_dim or 128,
gdn_num_qk_heads=args.linear_num_key_heads or 16,
gdn_num_v_heads=args.linear_num_value_heads or 32,
gdn_conv_kernel_dim=args.linear_conv_kernel_dim or 4,
vocab_size=args.padded_vocab_size,
mtp_num_layers=mtp_num_layers,
)
else:
# Compute standard Transformer model FLOPs.
return transformer_flops()
def get_start_time_from_progress_log():
"""
Gets start time of earliest job with same world size. Also returns the number
of floating-point operations completed in last saved checkpoint.
"""
args = get_args()
assert args.save is not None
progress_log_filename = os.path.join(args.save, "progress.txt")
# start_time is time when job with same world size started.
# start_num_floating_point_operations is the number of floating-point operations
# completed when this job started.
# latest_num_floating_point_operations is the number of floating-point operations
# completed in most recent saved checkpoint.
start_time = None
start_num_floating_point_operations = None
latest_num_floating_point_operations = 0
latest_num_floating_point_operations_uncommitted = None
def _get_field(string, type):
return type(string.split(': ')[1])
with open_file(progress_log_filename, 'r') as f:
for line in f:
line = line.strip()
line_tokens = line.split('\t')
world_size_in_line = _get_field(line_tokens[2], int)
if line_tokens[3] == "Saved checkpoint":
latest_num_floating_point_operations = _get_field(line_tokens[7], float)
elif line_tokens[3] == "Saving async checkpoint":
# Checkpoint hasn't committed yet, so store for now in a different variable.
latest_num_floating_point_operations_uncommitted = _get_field(line_tokens[7], float)
elif line_tokens[3] == "Saved async checkpoint":
# Checkpoint has committed, so can update latest_num_floating_point_operations to
# value from latest 'Saving async checkpoint' message.
# Note: latest_num_floating_point_operations_uncommitted can be None if
# save_checkpoint was called directly (without save_checkpoint_and_time),
# which writes "Saved async checkpoint" but not "Saving async checkpoint".
if latest_num_floating_point_operations_uncommitted is not None:
latest_num_floating_point_operations = latest_num_floating_point_operations_uncommitted
latest_num_floating_point_operations_uncommitted = None
if world_size_in_line != args.world_size:
# Re-start search if we see a different world size.
start_time = None
start_num_floating_point_operations = None
continue
if line_tokens[3] == "Starting job":
if start_time is None:
start_time = line_tokens[0]
start_num_floating_point_operations = latest_num_floating_point_operations
assert (
start_time is not None and start_num_floating_point_operations is not None
), "Should have seen at least one 'Starting job' entry with same world_size"
print_rank_0(f"megatron.training.get_start_time_from_progress_log: "
f"{start_time=}, {start_num_floating_point_operations=}")
return datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S'), start_num_floating_point_operations
def preprocess_common_state_dict(common_state_dict):
import copy
# Convert args key of type namespace to dictionary
preprocessed_common_state_dict = copy.deepcopy(common_state_dict)
preprocessed_common_state_dict['args'] = vars(preprocessed_common_state_dict['args'])
# Remove rank and local rank from state dict if it exists, since they are expected to be different
preprocessed_common_state_dict['args'].pop('local_rank', None)
preprocessed_common_state_dict['args'].pop('rank', None)
if (
preprocessed_common_state_dict['args']['use_distributed_optimizer']
and "optimizer" in preprocessed_common_state_dict
):
def reorder_inner_param_groups(optimizer_state_dict):
# When distributed optimizer loading, source param groups will be reordered,
# so we reorder the param groups here to prevent warning.
# Pop empty param_state.
if "param_state" in optimizer_state_dict and not optimizer_state_dict["param_state"]:
optimizer_state_dict.pop("param_state")
# Reorder param groups.
if "optimizer" not in optimizer_state_dict:
return
inner_optimizer = optimizer_state_dict["optimizer"]
if "param_groups" not in inner_optimizer:
return
param_groups = inner_optimizer["param_groups"]
key_fn = lambda pg: [pg[key] for key in param_group_identifier_keys]
param_groups.sort(key=key_fn)
inner_optimizer["param_groups"] = param_groups
optimizer_state_dict = preprocessed_common_state_dict['optimizer']
if "optimizer" in optimizer_state_dict:
# Only 1 optimizer in chained optimizer.
reorder_inner_param_groups(optimizer_state_dict)
else:
# Multiple optimizers in chained optimizer.
for i in range(len(optimizer_state_dict)):
if i in optimizer_state_dict.keys():
reorder_inner_param_groups(optimizer_state_dict[i])
return preprocessed_common_state_dict
def pretrain(
train_valid_test_dataset_provider,
model_provider,
model_type,
forward_step_func,
process_non_loss_data_func=None,
extra_args_provider=None,
args_defaults={},
get_embedding_ranks=None,
get_position_embedding_ranks=None,
non_loss_data_func=None,
store=None,
inprocess_call_wrapper: Optional[CallWrapper] = None,
extra_valid_dataset_provider=None, ###### FlagScale Add ##########
):
"""Main training program.
This function will run the followings in the order provided:
1) initialize Megatron.
2) setup model, optimizer and lr schedule using the model_provider.
3) call train_val_test_data_provider to get train/val/test datasets.
4) train the model using the forward_step_func.
Args:
train_valid_test_dataset_provider: a function that takes the size of
train/valid/test dataset and returns `train, valid, test` datasets.
model_provider: a function that returns a vanilla version of the
model. By vanilla we mean a simple model on cpu with no fp16 or ddp.
model_type: an enum that specifies the type of model being trained.
forward_step_func: a function that takes a `data iterator` and `model`,
and returns a `loss` scalar with a dictionary with key:values being
the info we would like to monitor during training, for example
`lm-loss: value`. We also require that this function add
`batch generator` to the timers class.
process_non_loss_data_func: a function to post process outputs of the
network. It can be used for dumping output tensors (e.g images) to
tensorboard. It takes `collected data`(list of tensors),
`current iteration index` and `tensorboard writer` as arguments.
extra_args_provider: a function that takes a parser and adds arguments
to it. It is used for programs to add their own arguments.
args_defaults: a dictionary from argument-name to argument-value. It
to set already parse arguments.
get_embedding_ranks: a function that takes a list of ranks for a pipeline
group and returns those ranks that should have word embeddings.
For most models, these are the first and last pipeline stages.
If None, defaults to returning the first and last pipeline stages.
get_position_embedding_ranks: a function that takes a list of ranks for
a pipeline group and returns those ranks that should have position
embeddings. For most models, this is only the first pipeline stage.
If None, defaults to returning only the first pipeline stage.
non_loss_data_func (callable): A custom function to call during evaluation.
It can run e.g. benchmarks.
store: an optional instance of torch.distributed.Store, to be used by
torch.distributed.init_process_group
inprocess_call_wrapper: an optional instance of inprocess.CallWrapper,
it is automatically injected when in-process restart is in use
"""
# Capture timestamp right at top of pretrain, before initialize_megatron
global _STARTUP_TIMESTAMPS
_STARTUP_TIMESTAMPS['pretrain_entry'] = time.time()
if inprocess_call_wrapper is not None:
iteration = inprocess_call_wrapper.iteration
store = torch.distributed.PrefixStore(str(iteration), store)