Repository navigation
Expand file tree
/
Copy pathpretrain_gpt.py
More file actions
403 lines (355 loc) · 15.3 KB
/
Copy pathpretrain_gpt.py
File metadata and controls
403 lines (355 loc) · 15.3 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
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
"""Pretrain and SFT GPT."""
# Capture the true program start time BEFORE any heavy imports.
import time
_PROGRAM_START_TIME = time.time()
from megatron.rank_log_setup import suppress_duplicate_logs_off_rank0
# Quiet the duplicate warnings before the heavy imports below: torch raises its
# own deprecations while it is being imported, so a filter installed any later
# cannot reach them.
suppress_duplicate_logs_off_rank0()
from functools import partial
from typing import List, Optional
from gpt_builders import gpt_builder
from megatron.core import mpu
from megatron.core.datasets.data_schedule import get_batch_on_this_rank_for_sequence_packing
from megatron.core.enums import ModelType
from megatron.core.models.gpt import GPTModel
from megatron.core.package_info import __version__ as mcore_version
from megatron.core.packed_seq_params import PackedSeqParams
from megatron.core.parallel_state import get_context_parallel_group
from megatron.core.process_groups_config import ProcessGroupCollection
from megatron.core.transformer.multi_token_prediction import get_mtp_ranks
from megatron.core.transformer.multi_token_prediction import (
mtp_on_this_rank as mtp_on_this_rank_func,
)
from megatron.core.utils import (
StragglerDetector,
flatten_batch_for_packed_sequences,
get_attr_wrapped_model,
get_batch_on_this_cp_rank,
get_batch_on_this_tp_rank,
get_te_version,
get_torch_version,
)
from megatron.training import (
get_args,
get_timers,
inprocess_restart,
pretrain,
print_rank_0,
set_startup_timestamps,
)
from megatron.training.argument_utils import (
gpt_config_from_args,
gpt_data_config_from_args,
pretrain_cfg_container_from_args,
)
from megatron.training.arguments import parse_and_validate_args
from megatron.training.datasets.providers import build_gpt_datasets, is_dataset_built_on_rank
from megatron.training.datasets.utils import get_dataset_input_length
from megatron.training.global_vars import get_run_config, set_run_config
from megatron.training.losses import build_loss_func, language_model_loss
from megatron.training.training import update_seqlen_stats_from_cu_seqlens
from megatron.training.utils import is_first_or_last_pipeline_stage
try:
from megatron.post_training.arguments import add_modelopt_args
from megatron.post_training.model_config import (
apply_modelopt_model_config,
distillation_config_from_args,
)
from megatron.post_training.utils import should_use_modelopt_config
has_nvidia_modelopt = True
except ImportError:
has_nvidia_modelopt = False
stimer = StragglerDetector()
# Canonical, ordered schema of the fields ``get_batch`` returns. Kept alphabetical
# to match the historical ``sorted(batch.keys())`` order that callers unpack into.
BATCH_KEYS = [
"attention_mask",
"cu_seqlens",
"cu_seqlens_padded",
"dynamic_cp_group",
"labels",
"local_cp_size",
"loss_mask",
"max_seqlen",
"position_ids",
"tokens",
]
def get_batch(
data_iterator,
vp_stage: Optional[int] = None,
pg_collection: Optional[ProcessGroupCollection] = None,
):
"""Generate a batch."""
cfg = get_run_config()
if cfg.model.transformer.sequence_packing_scheduler is not None:
if pg_collection is None:
# Compatibility for direct entrypoint callers; Core receives explicit groups.
pg_collection = ProcessGroupCollection.use_mpu_process_groups(
required_pgs=["tp", "pp", "cp", "tp_cp", "dynamic_cp", "dynamic_tp_cp"]
)
return get_batch_on_this_rank_for_sequence_packing(
data_iterator,
vpp_size=cfg.model.transformer.virtual_pipeline_model_parallel_size,
mtp_on_this_rank=mtp_on_this_rank_func(
layout=cfg.model.transformer.pipeline_model_parallel_layout,
mtp_num_layers=cfg.model.transformer.mtp_num_layers,
ignore_virtual=False,
vp_stage=vp_stage,
pp_group=pg_collection.pp,
vp_size=cfg.model.transformer.virtual_pipeline_model_parallel_size or 1,
),
vp_stage=vp_stage,
dynamic_cp=cfg.model.transformer.dynamic_context_parallel,
pg_collection=pg_collection,
config=cfg.model.transformer,
)
# The data section's predicates and the dataset's fields; the packing path above needs
# neither them nor the length.
cp_size = cfg.model.transformer.context_parallel_size
tp_rank = mpu.get_tensor_model_parallel_rank()
has_cu_seqlens = cfg.data.has_cu_seqlens()
# Use the caller's pipeline group when it is given, so a model on its own grid places MTP by
# the same group the model uses (GPTModel/HybridModel read pg_collection.pp).
pp_group = pg_collection.pp if pg_collection is not None else None
if pp_group is None:
pp_group = mpu.get_pipeline_model_parallel_group()
mtp_on_this_rank = mtp_on_this_rank_func(
layout=cfg.model.transformer.pipeline_model_parallel_layout,
mtp_num_layers=cfg.model.transformer.mtp_num_layers,
ignore_virtual=False,
vp_stage=vp_stage,
pp_group=pp_group,
)
# Dynamic CP always uses the sequence-packing path above.
assert not cfg.model.transformer.dynamic_context_parallel
if (
not is_first_or_last_pipeline_stage(vp_stage)
and not mtp_on_this_rank
and not has_cu_seqlens
):
return [None for _ in BATCH_KEYS]
# The dataset's row width (the derived pack width for SFT).
seq_length = get_dataset_input_length(cfg.data.dataset)
batch = {}
if tp_rank == 0:
batch = next(data_iterator)
for key in BATCH_KEYS:
batch[key] = (
batch[key].cuda(non_blocking=True)
if key in batch and batch[key] is not None
else None
)
# Read after the early return above: an intermediate stage without cu_seqlens never looks at
# the dataset (a loader-only section has none).
create_attention_mask_in_dataloader = cfg.data.creates_attention_mask()
batch = get_batch_on_this_tp_rank(
batch,
broadcast_src_rank=mpu.get_tensor_model_parallel_src_rank(),
broadcast_group=mpu.get_tensor_model_parallel_group(),
has_cu_seqlens=has_cu_seqlens,
dynamic_cp=False,
create_attention_mask_in_dataloader=create_attention_mask_in_dataloader,
cp_size=cp_size,
tp_rank=tp_rank,
micro_batch_size=cfg.train.micro_batch_size,
seq_length=seq_length,
mtp_on_this_rank=mtp_on_this_rank,
pipeline_model_parallel_size=cfg.model.transformer.pipeline_model_parallel_size,
is_pipeline_first_stage=mpu.is_pipeline_first_stage(),
is_pipeline_last_stage=mpu.is_pipeline_last_stage(),
)
batch = flatten_batch_for_packed_sequences(batch)
if not is_first_or_last_pipeline_stage(vp_stage) and not mtp_on_this_rank:
assert has_cu_seqlens
return (
None,
batch['cu_seqlens'],
batch['cu_seqlens_padded'],
None,
None,
None,
None,
batch['max_seqlen'],
None,
None,
)
batch = get_batch_on_this_cp_rank(
batch,
dynamic_cp=False,
cp_group=get_context_parallel_group(),
use_per_sequence_balancing=cfg.data.use_per_sequence_balancing(),
)
# Return values in BATCH_KEYS order so callers can unpack into the fixed
# names regardless of any provenance fields wrappers like BlendedDataset
# add (e.g. "dataset_id"). The for-loop above already populates every
# BATCH_KEYS entry on tp_rank 0; other tp_ranks receive a fresh dict from
# get_batch_on_this_tp_rank. BATCH_KEYS is already alphabetical, matching
# the historical sorted(batch.keys()) order.
return [batch[key] for key in BATCH_KEYS]
def forward_step(
data_iterator, model: GPTModel, return_schedule_plan: bool = False, *, loss_func=language_model_loss
):
"""Forward training step.
Args:
data_iterator : Input data iterator
model (GPTModel): The GPT Model
return_schedule_plan (bool): Whether to return the schedule plan instead of the output tensor
"""
cfg = get_run_config()
timers = get_timers()
# Get the batch.
timers('batch-generator', log_level=2).start()
with stimer(bdata=True):
vp_stage = get_attr_wrapped_model(model, "vp_stage")
batch = get_batch(
data_iterator, vp_stage, pg_collection=get_attr_wrapped_model(model, "pg_collection")
)
# Only populated by the has_cu_seqlens (--sft) 10-tuple branch below;
# stays None for the 6-/7-tuple (unpacked) batch shapes.
cu_seqlens = None
cu_seqlens_padded = None
if len(batch) == 7:
(
tokens,
labels,
loss_mask,
attention_mask,
position_ids,
packed_seq_params,
padding_mask,
) = batch
elif len(batch) == 6:
tokens, labels, loss_mask, attention_mask, position_ids, packed_seq_params = batch
padding_mask = None
else:
(
attention_mask,
cu_seqlens,
cu_seqlens_padded,
dynamic_cp_group,
labels,
local_cp_size,
loss_mask,
max_seqlen,
position_ids,
tokens,
) = batch
padding_mask = None
packed_seq_params = None
if cu_seqlens is not None:
# Squeeze the batch dim: the batch dict keeps cu_seqlens as (1, N)
# for consistency, but PackedSeqParams and TE expect 1-D.
cu_seqlens = cu_seqlens.squeeze(0)
if cu_seqlens_padded is not None:
cu_seqlens_padded = cu_seqlens_padded.squeeze(0)
# Use real (unpadded) cu_seqlens to feed the FLOPs accounting: varlen
# attention only computes work for real tokens within each chunk.
update_seqlen_stats_from_cu_seqlens(cu_seqlens)
cu_seqlens_for_params = (
cu_seqlens_padded if cu_seqlens_padded is not None else cu_seqlens
) # TODO(asolergi-nv): Currently there is a bug forcing cu_seqlens to be cu_seqlens_padded
packed_seq_params = PackedSeqParams(
qkv_format="thd",
cu_seqlens_q=cu_seqlens_for_params,
cu_seqlens_kv=cu_seqlens_for_params,
cu_seqlens_q_padded=cu_seqlens_padded,
cu_seqlens_kv_padded=cu_seqlens_padded,
max_seqlen_q=int(max_seqlen.item()),
max_seqlen_kv=int(max_seqlen.item()),
local_cp_size=int(local_cp_size.item()) if local_cp_size is not None else None,
cp_group=dynamic_cp_group,
tokens_per_sample=get_dataset_input_length(cfg.data.dataset),
)
# Offline logits KD: record this microbatch's global (un-CP-sharded)
# document boundaries so the saver can persist them alongside the
# logits _forward_hook is about to capture -- required for
# document-aware CP reassembly of packed (--sft) sequences.
from megatron.training.distillation.logits_saver import get_logits_saver
saver = get_logits_saver()
if saver is not None:
saver.set_current_cu_seqlens(
cu_seqlens_padded if cu_seqlens_padded is not None else cu_seqlens
)
timers('batch-generator').stop()
with stimer:
if return_schedule_plan:
assert (
cfg.model.transformer.overlap_moe_expert_parallel_comm
), "overlap_moe_expert_parallel_comm must be enabled to return the schedule plan"
schedule_plan = model.build_schedule_plan(
tokens,
position_ids,
attention_mask,
labels=labels,
loss_mask=loss_mask,
packed_seq_params=packed_seq_params,
padding_mask=padding_mask,
)
return schedule_plan, partial(loss_func, loss_mask, model=model)
else:
output_tensor = model(
tokens,
position_ids,
attention_mask,
labels=labels,
loss_mask=loss_mask,
packed_seq_params=packed_seq_params,
padding_mask=padding_mask,
)
return output_tensor, partial(loss_func, loss_mask, model=model)
def train_valid_test_datasets_provider(train_val_test_num_samples, vp_stage=None):
"""Build the train, validation and test datasets from the run config's ``cfg.data``.
The provider body is ``megatron.training.datasets.providers.build_gpt_datasets``, shared with
``pretrain_hybrid.py`` and ``pretrain_hybrid_flex.py``, called with the shared rank
predicate.
"""
return build_gpt_datasets(
train_val_test_num_samples, vp_stage, built_on_rank=is_dataset_built_on_rank
)
def get_embedding_ranks(pp_ranks: List[int]):
"""Get the embedding ranks."""
embedding_ranks = [pp_ranks[0]]
if len(pp_ranks) > 1:
cfg = get_run_config()
if cfg.model.share_embeddings_and_output_weights:
embedding_ranks.append(pp_ranks[-1])
mtp_ranks = get_mtp_ranks(pp_ranks, cfg.model.transformer)
embedding_ranks.extend(mtp_ranks)
embedding_ranks = list(set(embedding_ranks))
embedding_ranks = sorted(embedding_ranks)
return embedding_ranks
if __name__ == "__main__":
# Timestamp right after entering __main__ block (after all imports/library setup)
_MAIN_ENTRY_TIME = time.time()
print_rank_0(f'> PyTorch version ................ {get_torch_version()}')
print_rank_0(f'> Megatron-Core version .......... {mcore_version}')
print_rank_0(f'> Transformer Engine version ... {get_te_version()}')
# Register startup timestamps for timing report in pretrain()
set_startup_timestamps(program_start=_PROGRAM_START_TIME, main_entry=_MAIN_ENTRY_TIME)
# Temporary for transition to core datasets
setattr(train_valid_test_datasets_provider, "is_distributed", True)
# Optionally enable inprocess restart on pretrain
pretrain, store = inprocess_restart.maybe_wrap_for_inprocess_restart(pretrain)
args = parse_and_validate_args(
extra_args_provider=add_modelopt_args if has_nvidia_modelopt else None,
args_defaults={'tokenizer_type': 'GPT2BPETokenizer'},
)
model_cfg = gpt_config_from_args(args, vocab_size_from_tokenizer=True)
full_config = pretrain_cfg_container_from_args(
args, model_cfg, data_cfg=gpt_data_config_from_args(args)
)
if has_nvidia_modelopt and should_use_modelopt_config(args):
apply_modelopt_model_config(full_config.model, args)
full_config.distillation = distillation_config_from_args(args, full_config.model)
set_run_config(full_config)
pretrain(
full_config,
train_valid_test_datasets_provider,
ModelType.encoder_or_decoder,
partial(forward_step, loss_func=build_loss_func(full_config)),
store=store,
get_embedding_ranks=get_embedding_ranks,
)