-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathtrain_ft.py
More file actions
1494 lines (1287 loc) · 60.4 KB
/
Copy pathtrain_ft.py
File metadata and controls
1494 lines (1287 loc) · 60.4 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. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import inspect
import logging
import pathlib
import time
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Dict, Optional
import torch
import torch.nn as nn
import wandb
from huggingface_hub import constants as hf_constants
from megatron_fsdp import MegatronFSDP
from megatron_fsdp.fully_shard import fully_shard_optimizer
from torch.utils.data import DataLoader, IterableDataset
from torchao.float8 import precompute_float8_dynamic_scale_for_fsdp
from torchdata.stateful_dataloader.sampler import StatefulDistributedSampler
from transformers import AutoConfig
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from wandb import Settings
from nemo_automodel._transformers import NeMoAutoModelForCausalLM, NeMoAutoModelForSequenceClassification
from nemo_automodel._transformers.auto_tokenizer import NeMoAutoTokenizer
from nemo_automodel._transformers.infrastructure import (
MeshContext,
apply_model_infrastructure,
instantiate_infrastructure,
)
from nemo_automodel._transformers.utils import apply_cache_compatibility_patches
from nemo_automodel.components.checkpoint.checkpointing import (
Checkpointer,
CheckpointingConfig,
)
from nemo_automodel.components.config._arg_parser import parse_args_and_load_config
from nemo_automodel.components.datasets.llm.megatron.sampler import create_megatron_sampler
from nemo_automodel.components.datasets.llm.megatron_dataset import MegatronPretraining
from nemo_automodel.components.datasets.llm.packed_sequence import pack_dataset
from nemo_automodel.components.distributed.config import MegatronFSDPConfig
from nemo_automodel.components.distributed.cp_utils import make_cp_batch_and_ctx
from nemo_automodel.components.distributed.device_mesh import create_device_mesh
from nemo_automodel.components.distributed.init_utils import (
initialize_distributed,
)
from nemo_automodel.components.distributed.pipelining import AutoPipeline
from nemo_automodel.components.distributed.utils import FirstRankPerNode, get_sync_ctx
from nemo_automodel.components.loggers.log_utils import setup_logging
from nemo_automodel.components.loggers.metric_logger import MetricsSample, build_metric_logger
from nemo_automodel.components.loggers.mlflow_utils import build_mlflow
from nemo_automodel.components.loggers.wandb_utils import suppress_wandb_log_messages
from nemo_automodel.components.loss.linear_ce import FusedLinearCrossEntropy
from nemo_automodel.components.loss.masked_ce import MaskedCrossEntropy
from nemo_automodel.components.optim.scheduler import OptimizerParamScheduler
from nemo_automodel.components.optim.utils import build_dion_optimizer, is_dion_optimizer
from nemo_automodel.components.quantization.fp8 import build_fp8_config
from nemo_automodel.components.training.model_output_utils import get_final_hidden_states
from nemo_automodel.components.training.rng import ScopedRNG, StatefulRNG
from nemo_automodel.components.training.step_scheduler import StepScheduler
from nemo_automodel.components.training.utils import (
count_tail_padding,
prepare_for_final_backward,
prepare_for_grad_accumulation,
scale_grads_and_clip_grad_norm,
)
from nemo_automodel.components.utils.compile_utils import (
build_compile_config,
)
from nemo_automodel.components.utils.model_utils import (
_supports_logits_to_keep,
_supports_seq_lens,
resolve_trust_remote_code,
)
from nemo_automodel.recipes.base_recipe import BaseRecipe
if TYPE_CHECKING:
from torch.optim import Optimizer
from nemo_automodel.components.distributed.init_utils import DistInfo
logger = logging.getLogger(__name__)
# ---------------------------
# Stateless helper functions
# ---------------------------
def _get_model_name(cfg_model):
if cfg_model.get("pretrained_model_name_or_path", None) is not None:
return cfg_model.pretrained_model_name_or_path
elif cfg_model.get("config", None) is not None:
if isinstance(cfg_model.config, str):
return cfg_model.config
return cfg_model.config.get("pretrained_model_name_or_path", None)
else:
return None
def _uses_te_dot_product_attention(cfg_model):
return (
True
if hasattr(cfg_model, "backend") and hasattr(cfg_model.backend, "attn") and cfg_model.backend.attn == "te"
else False
)
def _uses_thd_collater(cfg_dataloader):
from nemo_automodel.components.datasets.utils import packed_sequence_thd_collater
return (
True
if hasattr(cfg_dataloader, "collate_fn") and cfg_dataloader.collate_fn == packed_sequence_thd_collater
else False
)
def _get_num_thd_chunks(pp_enabled, cfg):
if pp_enabled:
return cfg.step_scheduler.local_batch_size // cfg.autopipeline.pp_microbatch_size
return 1
def build_model(
cfg_model,
cfg_peft,
seed,
has_packed_sequence=False,
cfg_fp8=None,
cfg_compile=None,
cfg_quantization=None,
device_mesh=None,
moe_mesh=None,
distributed_config=None,
pipeline_config=None,
cfg_qat=None,
cfg_moe=None,
unfreeze_modules: list[str] | None = None,
) -> tuple[nn.Module | AutoPipeline, list["Optimizer"]]: # noqa: F821
"""
Build and initialize a model and optimizer.
Args:
cfg_model: Configuration for model instantiation.
cfg_peft: Configuration for PEFT.
seed: Random seed.
has_packed_sequence: Whether using packed sequences.
cfg_fp8: Configuration for FP8.
cfg_compile: Configuration for torch.compile.
cfg_quantization: Configuration for BitsAndBytes quantization.
device_mesh: Device mesh for distributed training. Parallelism sizes are inferred from this.
moe_mesh: MOE mesh for expert parallelism.
distributed_config: Strategy-specific distributed config (FSDP2Config, etc.).
pipeline_config: Pipeline parallelism config.
cfg_qat: Configuration for QAT (will be instantiated to QATConfig).
cfg_moe: Configuration for MOE (will be instantiated to MoEParallelizerConfig).
unfreeze_modules: List of module names/substrings to unfreeze.
Returns:
Tuple of (model, optimizer_list).
"""
with ScopedRNG(seed=seed, ranked=True):
kwargs = {
"has_packed_sequence": has_packed_sequence,
"peft_config": cfg_peft,
"device_mesh": device_mesh,
"moe_mesh": moe_mesh,
"distributed_config": distributed_config,
"pipeline_config": pipeline_config,
}
# Instantiate QATConfig from cfg_qat if provided
if cfg_qat is not None and cfg_qat.get("enabled", False):
if cfg_peft is not None:
raise ValueError("QAT with PEFT is not currently supported")
kwargs["qat_config"] = cfg_qat.qat_config.instantiate()
# Instantiate MoEParallelizerConfig from cfg_moe if provided
if cfg_moe is not None:
kwargs["moe_config"] = cfg_moe.instantiate()
if cfg_fp8 is not None:
fp8_config = build_fp8_config(cfg_fp8)
kwargs["fp8_config"] = fp8_config
if cfg_compile is not None:
kwargs["compile_config"] = build_compile_config(cfg_compile)
if cfg_quantization is not None:
logger.info("Model weight quantization enabled with BitsAndBytes")
from nemo_automodel.components.quantization.qlora import create_bnb_config
kwargs["quantization_config"] = create_bnb_config(cfg_quantization)
is_nemo_auto_model = cfg_model.get("_target_", None) in (
NeMoAutoModelForCausalLM.from_config,
NeMoAutoModelForCausalLM.from_pretrained,
NeMoAutoModelForSequenceClassification.from_config,
NeMoAutoModelForSequenceClassification.from_pretrained,
)
if is_nemo_auto_model:
# NeMoAutoModel handles infrastructure internally
model = cfg_model.instantiate(**kwargs)
else:
# For non-NemoAutoModel entry points (e.g., build_gpt2_model),
# instantiate the model first, then apply infrastructure separately.
# We must convert config objects into runtime objects (model_wrapper,
# autopipeline, parallelize_fn, etc.) via instantiate_infrastructure,
# exactly as from_pretrained/from_config do internally.
model = cfg_model.instantiate()
mesh = MeshContext.from_meshes(device_mesh, moe_mesh)
model_wrapper, autopipeline, parallelize_fn, qat_quantizer = instantiate_infrastructure(
distributed_config=distributed_config,
pipeline_config=pipeline_config,
qat_config=kwargs.get("qat_config"),
moe_config=kwargs.get("moe_config"),
device=torch.device("cuda", torch.cuda.current_device()),
mesh=mesh,
)
loss_fn = pipeline_config.loss_fn if pipeline_config is not None else None
model = apply_model_infrastructure(
model,
is_meta_device=False,
device=torch.cuda.current_device(),
mesh=mesh,
model_wrapper=model_wrapper,
autopipeline=autopipeline,
parallelize_fn=parallelize_fn,
qat_quantizer=qat_quantizer,
loss_fn=loss_fn,
peft_config=kwargs.get("peft_config"),
fp8_config=kwargs.get("fp8_config"),
compile_config=kwargs.get("compile_config"),
quantization_config=kwargs.get("quantization_config"),
pretrained_model_name_or_path=None,
load_base_model=False,
cache_dir=hf_constants.HF_HUB_CACHE,
)
# Explicitly unfreeze specified modules (e.g. task heads) that need full fine-tuning
if unfreeze_modules:
for name, param in model.named_parameters():
if any(module_name in name for module_name in unfreeze_modules):
param.requires_grad_(True)
logging.info(f"Unfroze parameters matching: {unfreeze_modules}")
return model
def build_optimizer(model, cfg_opt, distributed_config, device_mesh):
"""Build an optimizer for the model.
Args:
model: The model to build an optimizer for.
cfg_opt: The configuration for the optimizer.
distributed_config: The distributed configuration.
device_mesh: The device mesh.
"""
if device_mesh is not None and "tp" in device_mesh.mesh_dim_names and device_mesh["tp"].size() > 1:
# TP does not support foreach
cfg_opt.foreach = False
optimizer = []
has_dion_optimizer = is_dion_optimizer(cfg_opt)
for part in getattr(model, "parts", [model]):
trainable_params = list(filter(lambda x: x.requires_grad, part.parameters()))
assert len(trainable_params) > 0, "trainable_params cannot be empty"
# TODO(@akoumparouli): no branching for building the optimizer, refactor.
if has_dion_optimizer:
tmp_optimizer = build_dion_optimizer(
cfg_opt=cfg_opt,
model=part,
distributed_mesh=device_mesh,
)
else:
tmp_optimizer = cfg_opt.instantiate(params=trainable_params)
if isinstance(distributed_config, MegatronFSDPConfig) and torch.distributed.get_world_size() > 1:
assert not has_dion_optimizer, "Dion optimizer does not support fully_shard_optimizer"
# Only call fully_shard_optimizer when the model was actually wrapped
# with MegatronFSDP. When dp_mesh.size()==1 the parallelizer skips
# MegatronFSDP wrapping and the parameters won't carry the required
# _megatron_fsdp_model attribute.
if isinstance(part, MegatronFSDP):
fully_shard_optimizer(tmp_optimizer)
optimizer.append(tmp_optimizer)
return optimizer
def build_checkpoint_config(cfg_ckpt, cache_dir, model_repo_id, is_peft) -> CheckpointingConfig:
"""Build a checkpoint configuration.
Args:
cfg_ckpt: Configuration for checkpointing.
cache_dir: Cache directory for the model.
model_repo_id: Model repository ID.
is_peft: Whether the model is PEFT.
state_dict_keys: Copy of the model state dict keys before any parallelization.
Returns:
The instantiated checkpoint configuration.
"""
ckpt_kwargs = dict(
enabled=True,
checkpoint_dir="checkpoints/",
model_save_format="safetensors",
model_repo_id=model_repo_id,
model_cache_dir=cache_dir if cache_dir is not None else hf_constants.HF_HUB_CACHE,
save_consolidated=True,
is_peft=is_peft,
)
if cfg_ckpt is not None:
cfg_ckpt = cfg_ckpt.to_dict()
cfg_ckpt.pop("restore_from", None)
ckpt_kwargs |= cfg_ckpt
if ckpt_kwargs.get("is_peft", False) and ckpt_kwargs.get("model_save_format") == "torch_save":
raise ValueError(
"PEFT checkpointing is not supported for torch_save format. Save using `safetensors` format instead."
)
checkpoint_config = CheckpointingConfig(**ckpt_kwargs)
return checkpoint_config
def build_loss_fn(cfg_loss):
"""Build a loss function.
Args:
cfg_loss (ConfigNode): Loss function configuration.
Returns:
The instantiated loss function on the specified device.
"""
return cfg_loss.instantiate()
def compute_trust_remote_code_from_model(cfg_model):
"""Compute the value of trust_remote_code based on the model configuration.
Args:
cfg_model (ConfigNode): Model configuration.
Returns:
bool: Whether to trust remote code.
"""
if hasattr(cfg_model, "trust_remote_code"):
return getattr(cfg_model, "trust_remote_code")
elif hasattr(cfg_model, "config") and hasattr(cfg_model.config, "trust_remote_code"):
return getattr(cfg_model.config, "trust_remote_code")
return resolve_trust_remote_code(_get_model_name(cfg_model))
def _build_tokenizer(cfg_model, cfg_ds):
trust_remote_code = compute_trust_remote_code_from_model(cfg_model)
# if tokenizer is not provided, use the model config to instantiate it
if "tokenizer" not in cfg_ds and _get_model_name(cfg_model) is not None:
logging.info("Using model config to instantiate tokenizer")
tokenizer = NeMoAutoTokenizer.from_pretrained(_get_model_name(cfg_model), trust_remote_code=trust_remote_code)
elif cfg_ds.get("tokenizer", None) is None:
tokenizer = None
elif "_target_" not in cfg_ds.tokenizer:
tokenizer_dict = cfg_ds.tokenizer.to_dict()
trust_remote_code = tokenizer_dict.pop("trust_remote_code", trust_remote_code)
tokenizer = NeMoAutoTokenizer.from_pretrained(**tokenizer_dict, trust_remote_code=trust_remote_code)
else:
trust_remote_code = cfg_ds.tokenizer.to_dict().pop("trust_remote_code", trust_remote_code)
tokenizer = cfg_ds.tokenizer.instantiate(trust_remote_code=trust_remote_code)
# Finally, check if the dataset target accepts a tokenizer parameter
kwargs = {}
if tokenizer is not None and callable(cfg_ds._target_):
try:
sig = inspect.signature(cfg_ds._target_)
if "tokenizer" in sig.parameters:
kwargs["tokenizer"] = tokenizer
except (ValueError, TypeError):
# If we can't get the signature, skip adding tokenizer
pass
return kwargs, tokenizer
def build_dataloader(
cfg_ds,
cfg_dl,
cfg_model,
cfg_ps,
seed,
local_batch_size,
global_batch_size,
max_steps,
val_check_interval,
dp_rank,
dp_world_size,
pp_enabled,
cp_size=1,
model: Optional[nn.Module] = None,
) -> tuple[DataLoader, PreTrainedTokenizerBase]:
"""Build a DataLoader for the dataset.
Args:
cfg_ds: Dataset configuration.
cfg_dl: DataLoader configuration.
cfg_model: Model configuration.
cfg_ps: Packed sequence configuration.
seed: Random seed.
local_batch_size: Local batch size.
global_batch_size: Global batch size.
max_steps: Maximum number of steps.
val_check_interval: Validation check interval.
dp_rank: Data parallel rank.
dp_world_size: Data parallel world size.
pp_enabled: Whether pipeline parallelism is enabled.
cp_size: Context parallel size.
model: Optional model instance. If provided and packed sequences are enabled,
seq_lens will only be included if the model's forward() accepts it.
Returns:
The instantiated DataLoader and tokenizer.
"""
with ScopedRNG(seed=seed, ranked=True):
kwargs, tokenizer = _build_tokenizer(cfg_model, cfg_ds)
# Megatron specific kwargs
if cfg_ds._target_ == MegatronPretraining:
kwargs["global_batch_size"] = global_batch_size
kwargs["trainer_max_steps"] = max_steps if max_steps is not None else None
kwargs["trainer_val_check_interval"] = val_check_interval
ds = cfg_ds.instantiate(**kwargs)
ds.build()
else:
with FirstRankPerNode():
ds = cfg_ds.instantiate(**kwargs)
# If using an IterableDataset, per-rank sharding for unique samples
if isinstance(ds, IterableDataset):
if callable(getattr(ds, "shard", None)):
ds = ds.shard(dp_world_size, dp_rank)
logging.info(f"Sharded IterableDataset via dataset.shard: world_size={dp_world_size}, rank={dp_rank}")
elif hasattr(ds, "dataset"):
# HuggingFace streaming datasets: split by file shards when possible.
from datasets.distributed import split_dataset_by_node
assert hasattr(ds, "dataset"), "dataset must have a dataset attribute"
ds.dataset = split_dataset_by_node(ds.dataset, world_size=dp_world_size, rank=dp_rank)
logging.info(f"Sharded dataset via split_dataset_by_node: world_size={dp_world_size}")
else:
logging.warning("IterableDataset does not support sharding; Data may be duplicated across ranks.")
packed_sequence_size = getattr(cfg_ps, "packed_sequence_size", 0)
# check if packed sequence is supported
supports_seq_lens = _supports_seq_lens(model)
if packed_sequence_size > 0 and not supports_seq_lens:
logging.warning("Packed sequence is not supported without seq_lens; disabling packed sequence")
packed_sequence_size = 0
# Apply packing if configured
# Apply packing if configured
if packed_sequence_size > 0:
logger.info(f"Packing dataset with size: {packed_sequence_size}")
if hasattr(ds, "shuffle"):
ds = ds.shuffle(seed)
# Determine whether to include seq_lens/seq_lens_padded in packed samples.
# Priority: explicit config > model.forward signature detection > default False
ds = pack_dataset(
ds,
split=cfg_ds.split, # Assumes split is defined in dataset config
packed_sequence_size=packed_sequence_size,
max_packs=getattr(cfg_ps, "max_packs", None),
padding_idx=getattr(tokenizer, "pad_token_id", 0),
cp_size=cp_size,
)
if isinstance(ds, MegatronPretraining):
ds = ds.get_dataset(split=cfg_ds.splits_to_build)
dataloader_type = cfg_dl.get("dataloader_type", "single")
if "dataloader_type" in cfg_dl:
del cfg_dl.dataloader_type
batch_sampler = create_megatron_sampler(
dataset_len=len(ds),
micro_batch_size=local_batch_size,
global_batch_size=global_batch_size,
dataloader_type=dataloader_type,
rank=dp_rank,
world_size=dp_world_size,
)
dl_kwargs = {"batch_sampler": batch_sampler}
elif not isinstance(ds, IterableDataset):
shuffle = cfg_dl.get("shuffle", True)
if "shuffle" in cfg_dl:
del cfg_dl.shuffle
dist_sampler_kwargs = {
"num_replicas": dp_world_size,
"rank": dp_rank,
"shuffle": shuffle,
}
sampler = StatefulDistributedSampler(
ds,
seed=seed,
drop_last=True,
**dist_sampler_kwargs,
)
dl_kwargs = {"sampler": sampler, "batch_size": local_batch_size}
if pp_enabled:
dl_kwargs["drop_last"] = True
else:
logging.info("Using IterableDataset; skipping sampler.")
# Optional shuffle for streaming IterableDataset (uses HF dataset shuffle if available)
shuffle = cfg_dl.get("shuffle", False)
shuffle_buffer_size = cfg_dl.get("shuffle_buffer_size", 10000)
# Do not pass shuffle-related kwargs to the DataLoader when using IterableDataset
# But leave them in dl config to be consistent
if hasattr(cfg_dl, "shuffle"):
del cfg_dl.shuffle
if hasattr(cfg_dl, "shuffle_buffer_size"):
del cfg_dl.shuffle_buffer_size
if shuffle and hasattr(ds, "shuffle"):
try:
ds = ds.shuffle(buffer_size=shuffle_buffer_size, seed=seed)
logging.info(f"Shuffling IterableDataset with buffer_size={shuffle_buffer_size}, seed={seed}")
except Exception as e:
logging.warning(f"IterableDataset shuffle skipped due to error: {e}")
dl_kwargs = {}
# Handle collate_fn with optional mask precomputation for pipeline parallelism
dl_kwargs = dl_kwargs | {"dataset": ds}
# Handle collate_fn instantiation if it's a ConfigNode
if hasattr(cfg_dl, "collate_fn"):
if hasattr(cfg_dl.collate_fn, "_target_"):
collate_cfg = cfg_dl.collate_fn
dl_kwargs["collate_fn"] = lambda batch: collate_cfg.instantiate(batch=batch)
else:
dl_kwargs["collate_fn"] = cfg_dl.collate_fn
assert callable(dl_kwargs["collate_fn"]), "collate_fn must be callable"
# Chain with mask precomputation if PP is enabled
if pp_enabled:
from nemo_automodel.components.datasets.utils import add_causal_masks_to_batch
hf_model_config = AutoConfig.from_pretrained(
_get_model_name(cfg_model), trust_remote_code=compute_trust_remote_code_from_model(cfg_model)
)
if "collate_fn" in dl_kwargs:
# Case 1: PP enabled + collate_fn exists -> chain them
# base_collate_fn -> add_causal_masks_to_batch
base_collate_fn = dl_kwargs["collate_fn"]
def chained_collate_fn(batch, base_fn=base_collate_fn, config=hf_model_config):
batch = base_fn(batch) # Apply base collate (padding, batching, etc.)
batch = add_causal_masks_to_batch(batch, model_config=config) # Add masks
return batch
dl_kwargs["collate_fn"] = chained_collate_fn
else:
# Case 2: PP enabled + no collate_fn -> only add masks
dl_kwargs["collate_fn"] = lambda batch, config=hf_model_config: add_causal_masks_to_batch(
batch, model_config=config
)
try:
import torch.multiprocessing as mp
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method("spawn", force=True)
except RuntimeError:
pass
return cfg_dl.instantiate(**dl_kwargs), tokenizer
def build_distributed(cfg_dist: Dict[str, Any]) -> "DistInfo": # noqa: F821
"""Build and initialize distributed training resources.
Args:
cfg_dist: Configuration for distributed training.
Returns:
Distributed training information from initialize_distributed.
"""
backend = cfg_dist.get("backend", "nccl")
timeout = cfg_dist.get("timeout_minutes", 1)
return initialize_distributed(backend=backend, timeout_minutes=timeout)
def build_step_scheduler(cfg, dataloader, dp_group_size, local_batch_size):
"""Build the step scheduler.
Args:
cfg: configuration for the StepScheduler class.
dataloader: the training dataloader, used for extracting the epoch_len (in batches).
dp_group_size: the size of the data parallel group.
micro_batch_size: the size of the micro batch.
Returns:
StepScheduler: the configured StepScheduler.
"""
assert "_target_" not in cfg, "_target_ not permitted in step scheduler"
default_kwargs = dict(
num_epochs=10,
global_batch_size=32,
local_batch_size=local_batch_size,
dp_size=dp_group_size,
ckpt_every_steps=100,
dataloader=dataloader,
)
if cfg is not None:
default_kwargs |= cfg.to_dict()
return StepScheduler(**default_kwargs)
def build_lr_scheduler(cfg, optimizer, step_scheduler) -> list[OptimizerParamScheduler] | None: # noqa: F821
"""Build the learning rate scheduler.
Args:
cfg: Configuration for the OptimizerParamScheduler.
optimizer: The optimizer to be scheduled.
step_scheduler: The step scheduler to extract training parameters.
Returns:
OptimizerParamScheduler: The configured learning rate scheduler, or None if not configured.
"""
if cfg is None:
return None
# Calculate total steps for the training run
total_epochs = step_scheduler.num_epochs
epoch_len = len(step_scheduler.dataloader)
grad_acc_steps = step_scheduler.grad_acc_steps
# Total optimizer steps (accounting for gradient accumulation)
total_steps = (total_epochs * epoch_len) // grad_acc_steps
if step_scheduler.max_steps is not None:
total_steps = min(total_steps, step_scheduler.max_steps)
# Set defaults for scheduler parameters
optimizer_param_schedulers = []
user_kwargs = cfg.to_dict()
default_kwargs = dict(
lr_warmup_steps=min(1000, total_steps // 10), # 10% warmup or max 1000 steps
lr_decay_steps=total_steps,
lr_decay_style="cosine",
wd_incr_steps=total_steps,
wd_incr_style="constant",
)
if not isinstance(optimizer, list):
optimizer = [optimizer]
for opt in optimizer:
base_lr = opt.param_groups[0]["lr"]
default_kwargs.update(
dict(
optimizer=opt,
init_lr=base_lr * 0.1, # Start warmup at 10% of base LR
max_lr=base_lr,
min_lr=base_lr * 0.01, # End at 1% of base LR
start_wd=opt.param_groups[0].get("weight_decay", 0.0),
end_wd=opt.param_groups[0].get("weight_decay", 0.0),
)
)
default_kwargs.update(user_kwargs)
optimizer_param_schedulers.append(OptimizerParamScheduler(**default_kwargs))
logger.info(
f"Building LR scheduler with total_steps={total_steps}, "
f"warmup_steps={default_kwargs['lr_warmup_steps']}, "
f"decay_style={default_kwargs['lr_decay_style']}"
)
return optimizer_param_schedulers
def build_wandb(cfg) -> wandb.Run:
"""Instantiates wandb and returns the instance. If no name is given, it will use the model name.
Args:
cfg: Configuration for wandb.
Returns:
The wandb instance.
"""
assert cfg.get("wandb", None) is not None
kwargs = cfg.wandb.to_dict()
if kwargs.get("name", "") == "":
kwargs["name"] = "_".join(_get_model_name(cfg.model).split("/")[-2:])
run = wandb.init(
**kwargs,
config=cfg.to_dict(),
settings=Settings(silent=True),
)
return run
def calculate_loss(loss_fn, **kwargs) -> torch.Tensor:
"""Calculate the loss.
Args:
loss_fn: Loss function.
**kwargs: Keyword arguments for the loss function.
Returns:
The loss.
"""
loss_fn_kwargs = {"num_label_tokens": kwargs.pop("num_label_tokens", None)}
if isinstance(loss_fn, FusedLinearCrossEntropy):
model = kwargs.pop("model")
labels = kwargs.pop("labels")
# find the lm_head in the model
lm_head = None
if hasattr(model, "get_output_embeddings"):
lm_head = model.get_output_embeddings().weight
else:
for n, p in model.named_parameters(remove_duplicate=False):
if "lm_head" in n and n.endswith(".weight"):
lm_head = p
break
if lm_head is None:
raise ValueError("lm_head.weight not found in model")
# unshard the possibly sharded lm_head
lm_head = lm_head.full_tensor() if hasattr(lm_head, "full_tensor") else lm_head
loss_fn_kwargs.update(
{
"hidden_states": kwargs.pop("hidden_states"),
"labels": labels,
"lm_weight": lm_head,
}
)
else:
loss_fn_kwargs.update(
{
"logits": kwargs.pop("logits"),
"labels": kwargs.pop("labels"),
}
)
return loss_fn(**loss_fn_kwargs)
def build_validation_dataloader(cfg, dp_world_size, dp_rank, pp_enabled, model: Optional[nn.Module] = None):
def _prepare_val_ds_name(val_ds_name):
val_ds_name = val_ds_name.replace("validation_dataset", "")
if len(val_ds_name) > 1 and val_ds_name[0] in ("_", "-", "."):
val_ds_name = val_ds_name[1:]
if val_ds_name == "":
val_ds_name = "default"
return val_ds_name
# Build validation dataloader if the config provides it
val_dataloaders = {}
for val_ds_name in filter(lambda x: x.startswith("validation_dataset"), cfg.to_dict().keys()):
val_ds_cfg = cfg.get(val_ds_name, None)
val_ds_name = _prepare_val_ds_name(val_ds_name)
val_dataloaders[val_ds_name] = build_dataloader(
val_ds_cfg,
cfg.validation_dataloader,
cfg.model,
cfg_ps=cfg.get("packed_sequence", None)
if _uses_te_dot_product_attention(cfg.model) and _uses_thd_collater(cfg.dataloader)
else None,
seed=cfg.get("seed", 42),
local_batch_size=cfg.get("step_scheduler.local_batch_size", 1),
global_batch_size=cfg.get("step_scheduler.global_batch_size", 1),
max_steps=cfg.get("step_scheduler.max_steps", None),
val_check_interval=cfg.get("step_scheduler.val_every_steps", None),
dp_rank=dp_rank,
dp_world_size=dp_world_size,
pp_enabled=False,
cp_size=cfg.get("distributed.cp_size", 1),
model=model,
)[0]
return val_dataloaders
# ---------------------------------------------------------------------------
# Trainer class – orchestration only
# ---------------------------------------------------------------------------
class TrainFinetuneRecipeForNextTokenPrediction(BaseRecipe):
"""Recipe for fine-tuning a model for next-token prediction.
This class orchestrates training, from setup to main training loop.
"""
def __init__(self, cfg):
"""Initialize the recipe with configuration.
Args:
cfg: Configuration dictionary/object for training.
"""
self.cfg = cfg
# ------------------ build phase ------------------
def setup(self):
"""Builds all components needed for training/validation/logging/checkpointing/etc.
This is the last place where self.cfg should be referenced.
Raises:
NotImplemented: Raises if it tries to restore a checkpoint; will be removed.
"""
torch.cuda.reset_peak_memory_stats()
self.dist_env = build_distributed(self.cfg.get("dist_env", {}))
# setups logging and adds the rankfilter to logging
setup_logging()
apply_cache_compatibility_patches()
# Set up the stateful random number generator
self.rng = StatefulRNG(seed=self.cfg.get("seed", 42), ranked=True)
# Enable NVTX patching only when explicitly requested in config
self.enable_nvtx = bool(self.cfg.get("nvtx", False))
self.device_mesh = None
self.moe_mesh = None
self.distributed_config = None
if "distributed_config" in self.cfg:
# Strategy-specific config from distributed_config section
self.distributed_config = self.cfg.distributed_config.instantiate()
# Parallelism sizes from distributed section, create device mesh
self.device_mesh, self.moe_mesh = create_device_mesh(
self.distributed_config,
dp_size=self.cfg.get("distributed.dp_size", None),
dp_replicate_size=self.cfg.get("distributed.dp_replicate_size", None),
tp_size=self.cfg.get("distributed.tp_size", 1),
pp_size=self.cfg.get("distributed.pp_size", 1),
cp_size=self.cfg.get("distributed.cp_size", 1),
ep_size=self.cfg.get("distributed.ep_size", 1),
world_size=self.dist_env.world_size,
)
if self.dist_env.is_main and hasattr(self.cfg, "wandb"):
suppress_wandb_log_messages()
run = build_wandb(self.cfg)
logging.info("🚀 View run at {}".format(run.url))
self.mlflow_logger = None
if self.dist_env.is_main and hasattr(self.cfg, "mlflow"):
self.mlflow_logger = build_mlflow(self.cfg)
self.mlflow_logger.log_params(self.cfg.to_dict())
logging.info("MLflow experiment tracking enabled")
# Log experiment details on main rank
self._log_experiment_details()
self._log_library_versions()
self.pp_enabled: bool = self.cfg.get("distributed.pp_size", 1) > 1
# Build pipeline config if PP enabled
self.pipeline_config = None
if self.pp_enabled:
pp_size = self.cfg.get("distributed.pp_size", 1)
pp_batch_size = self.cfg.step_scheduler.local_batch_size
pp_microbatch_size = self.cfg.autopipeline.pp_microbatch_size
assert pp_batch_size // pp_microbatch_size >= pp_size, (
f"pp_batch_size {pp_batch_size} // pp_microbatch_size {pp_microbatch_size} must be >= pp_size {pp_size}"
)
# THD override logic
if (
self.cfg.distributed.get("cp_size", 1) > 1
and _uses_te_dot_product_attention(self.cfg.model)
and _uses_thd_collater(self.cfg.dataloader)
):
pp_microbatch_size = 1
pp_batch_size = pp_batch_size // self.cfg.autopipeline.pp_microbatch_size
logging.info(
f"Overriding pp_batch_size: {pp_batch_size}, pp_microbatch_size: {pp_microbatch_size} for THD"
)
assert self.cfg.get("autopipeline", None) is not None, (
"AutoPipeline configuration is required when pipeline parallelism is enabled"
)
assert not isinstance(self.distributed_config, MegatronFSDPConfig), (
"MegatronFSDPConfig is not supported when pipeline parallelism is enabled"
)
# Build loss_fn first (needed for pipeline_config)
self.loss_fn = build_loss_fn(self.cfg.loss_fn)
# Instantiate PipelineConfig from YAML, override runtime-computed args
self.pipeline_config = self.cfg.autopipeline.instantiate(
pp_microbatch_size=pp_microbatch_size,
pp_batch_size=pp_batch_size,
patch_stage_backward_maybe_with_nosync=self.cfg.get("model.backend.enable_fsdp_optimizations", False),
loss_fn=self.loss_fn,
)
else:
self.loss_fn = build_loss_fn(self.cfg.loss_fn)
# Build components
self.peft_config = None
if self.cfg.get("peft", None) is not None:
self.peft_config = self.cfg.peft.instantiate()
# Build checkpoint config
checkpoint_config = build_checkpoint_config(
self.cfg.get("checkpoint", None),
self.cfg.get("model.cache_dir", None),
_get_model_name(self.cfg.model),
True if self.cfg.get("peft", None) else False,
)
if self.cfg.get("clip_grad_norm.max_norm", None) is not None:
self.max_grad_norm = float(self.cfg.clip_grad_norm.max_norm)
else:
logging.info("No clip_grad_norm.max_norm specified in config, using default value of 1.0")
self.max_grad_norm = 1.0
# Create Checkpointer instance
self.checkpointer = Checkpointer(
config=checkpoint_config,
dp_rank=self._get_dp_rank(include_cp=True),
tp_rank=self._get_tp_rank(),
pp_rank=self._get_pp_rank(),
moe_mesh=self.moe_mesh,
)
model = build_model(
self.cfg.model,
self.peft_config,
has_packed_sequence=self.cfg.get("packed_sequence.packed_sequence_size", 0) > 0,
seed=self.cfg.get("seed", 42),
cfg_fp8=self.cfg.get("fp8", None),
cfg_compile=self.cfg.get("compile", None),
cfg_quantization=self.cfg.get("quantization", None),
device_mesh=self.device_mesh,
moe_mesh=self.moe_mesh,
distributed_config=self.distributed_config,
pipeline_config=self.pipeline_config,
cfg_qat=self.cfg.get("qat", None),
cfg_moe=self.cfg.get("moe_config", None),
)
self.optimizer = build_optimizer(model, self.cfg.optimizer, self.distributed_config, self.device_mesh)
if not _supports_logits_to_keep(model) and not isinstance(self.loss_fn, MaskedCrossEntropy):
logger.warning("logits_to_keep not found in model.forward. Using MaskedCrossEntropy instead.")
self.loss_fn = MaskedCrossEntropy()
if isinstance(model, AutoPipeline):
self.model_parts = model.parts
self.pp = model
if self.enable_nvtx:
import nemo_automodel.autonvtx as autonvtx
# Patch each pipeline stage with NVTX profiling
for i, part in enumerate(self.model_parts):
autonvtx.patch(part, name=f"PipelineStage_{i}")
else:
if self.enable_nvtx:
import nemo_automodel.autonvtx as autonvtx
# Patch model with NVTX profiling
autonvtx.patch(model, name=model.__class__.__name__)
self.model_parts = [model]
self.pp = None
self.dataloader, self.tokenizer = build_dataloader(
self.cfg.dataset,
self.cfg.dataloader,
self.cfg.model,
self.cfg.get("packed_sequence", None),
seed=self.cfg.get("seed", 42),
local_batch_size=self.cfg.get("step_scheduler.local_batch_size", 1),
global_batch_size=self.cfg.get("step_scheduler.global_batch_size", 1),
max_steps=self.cfg.get("step_scheduler.max_steps", None),
val_check_interval=self.cfg.get("step_scheduler.val_every_steps", None),
dp_rank=self._get_dp_rank(),
dp_world_size=self._get_dp_group_size(),
pp_enabled=self.pp_enabled,
cp_size=self.cfg.get("distributed.cp_size", 1),
model=self.model_parts[0],
)
self.val_dataloaders = build_validation_dataloader(
self.cfg,
self._get_dp_group_size(),
self._get_dp_rank(),
self.pp_enabled,
model=self.model_parts[0],
)
self.best_metric_key = self.cfg.get("checkpoint.best_metric_key", "default")
# Scheduler