bridge.training.gpt_step#
Module Contents#
Classes#
Which batch fields one PP/VPP stage reads from the data iterator. |
|
One THD representation for the forward step, whichever packing mode produced the batch. |
Functions#
Trim padded THD cu_seqlens without introducing a CUDA sync. |
|
Return whether a dataloader batch contains packed-sequence metadata. |
|
Extract sequence metadata, including padding masks for unpacked batches. |
|
Forward the schedule-plan chunk mask into the pinned MCore MoE router. |
|
Reject router-scoped TE graphs that cannot consume token padding masks. |
|
Prepare an alignment-padding mask for the current model stage. |
|
Return the cu-seqlens tensor TE should use to partition packed THD tokens. |
|
Return whether the dataset is expected to provide packed sequence metadata. |
|
Return whether middle PP stages need batch metadata for attention. |
|
Return whether the batch carries Core GPTDataset document boundaries to adapt for attention. |
|
Reject settings the GPT and DSv4 steps do not support with document masking. |
|
Return whether a parsed or raw pipeline layout stage owns MTP layers. |
|
Return whether the current PP/VPP stage owns the configured MTP block, derived from layout. |
|
Return whether this stage needs token ids for MTP embedding lookup, derived from layout. |
|
Return the batch fields |
|
Return whether any model chunk on this rank reads the data iterator in a training iteration. |
|
Return whether the GPT step reads the data iterator on this rank. |
|
Partition THD/packed batches across context-parallel ranks. |
|
Convert the document boundaries of one Core |
|
Get a batch of data from the iterator. |
|
Whether the modelβs rotary embedding CP-shards the position ids itself. |
|
Generate a batch. |
|
Normalize packed-sequence metadata from any packing mode into PackedSeqParams. |
|
Forward training step. |
|
Forward training step. |
|
Create a partial loss function with the specified configuration. |
|
Forward training step with ModelOpt required modifications. |
|
Create a partial loss function with the specified configuration. |
Data#
API#
- bridge.training.gpt_step.logger#
βgetLogger(β¦)β
- bridge.training.gpt_step._CURRENT_PACKED_SEQ_DEVICE_KEYS#
(βcu_seqlens_qβ, βcu_seqlens_kvβ, βcu_seqlens_q_paddedβ, βcu_seqlens_kv_paddedβ)
- bridge.training.gpt_step._CURRENT_PACKED_SEQ_HOST_KEYS#
(βmax_seqlen_qβ, βmax_seqlen_kvβ, βpad_between_seqsβ)
- bridge.training.gpt_step._CURRENT_PACKED_SEQ_PARAM_KEYS#
()
- bridge.training.gpt_step._LEGACY_PACKED_SEQ_DEVICE_KEYS#
(βcu_seqlensβ, βcu_seqlens_unpaddedβ)
- bridge.training.gpt_step._LEGACY_PACKED_SEQ_HOST_KEYS#
(βcu_seqlens_argminβ, βmax_seqlenβ, βcu_seqlens_unpadded_argminβ)
- bridge.training.gpt_step._LEGACY_PACKED_SEQ_PARAM_KEYS#
()
- bridge.training.gpt_step._PackedMetadataValue#
None
- bridge.training.gpt_step._MCORE_SCHEDULE_PADDING_MASK_PATCHED#
β_mbridge_schedule_padding_mask_compatibleβ
- bridge.training.gpt_step._trim_padded_cu_seqlens_for_cp(
- cu_seqlens: torch.Tensor,
- cu_seqlens_argmin: torch.Tensor | None,
Trim padded THD cu_seqlens without introducing a CUDA sync.
- bridge.training.gpt_step._has_packed_sequence_metadata(batch: dict[str, torch.Tensor]) bool#
Return whether a dataloader batch contains packed-sequence metadata.
- bridge.training.gpt_step._packed_metadata_for_forward(
- batch: dict[str, torch.Tensor],
Extract sequence metadata, including padding masks for unpacked batches.
- bridge.training.gpt_step._patch_mcore_schedule_plan_padding_mask() None#
Forward the schedule-plan chunk mask into the pinned MCore MoE router.
TODO: Remove this compatibility patch after MCore devβs schedule-plan padding-mask forwarding reaches the pinned main commit.
- bridge.training.gpt_step._validate_packed_moe_cuda_graph(config) None#
Reject router-scoped TE graphs that cannot consume token padding masks.
- bridge.training.gpt_step._prepare_packed_padding_mask(
- padding_mask: torch.Tensor | None,
- *,
- config,
- model: megatron.core.models.gpt.GPTModel,
- pg_collection,
Prepare an alignment-padding mask for the current model stage.
- bridge.training.gpt_step._cu_seqlens_for_cp_partition(
- batch: dict[str, torch.Tensor],
Return the cu-seqlens tensor TE should use to partition packed THD tokens.
- bridge.training.gpt_step._uses_packed_sequence_metadata(
- cfg: megatron.bridge.training.config.ConfigContainer,
Return whether the dataset is expected to provide packed sequence metadata.
- bridge.training.gpt_step._middle_pp_stage_needs_batch(
- cfg: megatron.bridge.training.config.ConfigContainer,
Return whether middle PP stages need batch metadata for attention.
- bridge.training.gpt_step._uses_inter_document_masking(
- cfg: megatron.bridge.training.config.ConfigContainer,
Return whether the batch carries Core GPTDataset document boundaries to adapt for attention.
Only
GPTDatasetConfigbuilds CoreGPTDatasetrows, whose paddedcu_seqlenslayoutget_batch_from_iteratoradapts. Other datasets that expose aninter_document_maskingattribute are left unchanged.
- bridge.training.gpt_step._validate_inter_document_masking(
- cfg: megatron.bridge.training.config.ConfigContainer,
Reject settings the GPT and DSv4 steps do not support with document masking.
The steps convert one row per micro-batch and do not split documents across context-parallel ranks, for training and evaluation alike. A CUDA graph that captures attention would need boundary tensors of one shape, while the number of documents changes from row to row. A custom forward step that flattens micro-batches or partitions documents itself is not affected.
- Raises:
ValueError β If a micro-batch size or context-parallel size is not 1, or if the CUDA graph captures attention.
- bridge.training.gpt_step._layout_stage_has_mtp(
- layout,
- *,
- pp_rank: int,
- pp_size: int,
- vp_stage: int,
Return whether a parsed or raw pipeline layout stage owns MTP layers.
- bridge.training.gpt_step._current_stage_has_mtp_from_layout(
- cfg: megatron.bridge.training.config.ConfigContainer,
- *,
- pg_collection,
- vp_stage: int | None = None,
Return whether the current PP/VPP stage owns the configured MTP block, derived from layout.
- bridge.training.gpt_step._current_stage_needs_mtp_inputs_from_layout(
- cfg: megatron.bridge.training.config.ConfigContainer,
- *,
- pg_collection,
- is_last: bool,
- vp_stage: int | None = None,
Return whether this stage needs token ids for MTP embedding lookup, derived from layout.
- class bridge.training.gpt_step._StageBatchFields#
Which batch fields one PP/VPP stage reads from the data iterator.
- is_first: bool#
None
- is_last: bool#
None
- include_full_batch_fields: bool#
None
- include_mtp_inputs: bool#
None
- property reads_batch: bool#
Whether the stage calls
next()on the data iterator once per micro-batch.
- bridge.training.gpt_step._stage_batch_fields(
- cfg: megatron.bridge.training.config.ConfigContainer,
- *,
- pg_collection,
- use_mtp: bool,
- vp_stage: int | None,
Return the batch fields
get_batchreads on this PP/VPP stage.
- bridge.training.gpt_step._rank_reads_batch(
- cfg: megatron.bridge.training.config.ConfigContainer,
- *,
- pg_collection,
- stage_batch_fields: Callable[..., bridge.training.gpt_step._StageBatchFields],
Return whether any model chunk on this rank reads the data iterator in a training iteration.
With virtual pipeline parallelism the chunks read through cache views over one outer iterator (
make_data_iterator_list), so the rank advances that iterator when any chunk reads.- Parameters:
cfg β Configuration container.
pg_collection β Process groups of this rank.
stage_batch_fields β The stepβs per-stage read logic, with the signature of
_stage_batch_fields.
- bridge.training.gpt_step._reads_batch_on_skip(
- cfg: megatron.bridge.training.config.ConfigContainer,
- pg_collection,
Return whether the GPT step reads the data iterator on this rank.
train()uses it on skipped iterations (train.iterations_to_skip) to advance the same ranks that read batches in a real iteration.
- bridge.training.gpt_step._partition_packed_batch_for_cp(
- batch: dict[str, torch.Tensor],
- cp_group: torch.distributed.ProcessGroup,
Partition THD/packed batches across context-parallel ranks.
Uses MCoreβs packed-sequence partitioning to slice sequence dimensions aligned with packed cu_seqlens.
- bridge.training.gpt_step._adapt_document_boundaries(
- batch: dict[str, torch.Tensor],
Convert the document boundaries of one Core
GPTDatasetrow to THD Q/KV fields.Core pads
cu_seqlensto a fixed length by repeating the rowβs token width. Like Coreβs merge helper, this keeps the offsets through the first occurrence of that width, so equal interior offsets (empty documents) stay. It runs on the host, before the device copy.- Parameters:
batch β A micro-batch from the data iterator, with
tokens,cu_seqlensandmax_seqlen.- Returns:
A new batch with
cu_seqlens_q,cu_seqlens_kv,max_seqlen_qandmax_seqlen_kvin place ofcu_seqlensandmax_seqlen.- Raises:
ValueError β If
cu_seqlensis not an int32[1, n]tensor of non-decreasing offsets that starts at 0 and ends in a run of the rowβs token width, or ifmax_seqlenis not the longest document.
- bridge.training.gpt_step.get_batch_from_iterator(
- data_iterator: Iterable,
- include_mtp_inputs: bool = False,
- skip_getting_attention_mask_from_dataset: bool = True,
- *,
- is_first_pp_stage: bool,
- is_last_pp_stage: bool,
- include_full_batch_fields: bool = False,
- inter_document_masking: bool = False,
Get a batch of data from the iterator.
- Parameters:
data_iterator β The data iterator to get the batch from.
include_mtp_inputs β Whether this PP stage needs Multi-Token Prediction input tensors.
skip_getting_attention_mask_from_dataset β If set, the dataset will pass a None attention mask.
include_full_batch_fields β Whether to include all standard training tensors regardless of PP stage.
inter_document_masking β Whether the batch is a Core GPTDataset row whose document boundaries become THD Q/KV fields (see
_adapt_document_boundaries).
- Returns:
A dictionary containing the batch data.
- Return type:
dict[str, torch.Tensor]
- bridge.training.gpt_step._keep_full_position_ids_for_cp(model_cfg, cp_size: int) bool#
Whether the modelβs rotary embedding CP-shards the position ids itself.
mrope builds its embedding from whatever ids it is given and then shards that, so sharding them here as well leaves the embedding at seq/cp**2 against hidden states at seq/cp.
- bridge.training.gpt_step.get_batch(
- data_iterator: Iterable,
- cfg: megatron.bridge.training.config.ConfigContainer,
- use_mtp: bool = False,
- *,
- pg_collection,
- vp_stage: int | None = None,
Generate a batch.
- Parameters:
data_iterator β Input data iterator
cfg β Configuration container
use_mtp β Whether Multi-Token Prediction layers are enabled
vp_stage β Virtual pipeline stage for the current model chunk.
- Returns:
tuple of tensors containing tokens, labels, loss_mask, attention_mask, position_ids, and optional packed-sequence metadata.
- class bridge.training.gpt_step._ResolvedPackedBatch#
One THD representation for the forward step, whichever packing mode produced the batch.
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None#
None
- padding_mask: torch.Tensor | None#
None
- flops_from_scheduler: bool#
False
- flops_cu_seqlens: torch.Tensor | None#
None
- flops_cu_seqlens_argmin: torch.Tensor | None#
None
- flops_cu_seqlens_unpadded: torch.Tensor | None#
None
- flops_cu_seqlens_unpadded_argmin: torch.Tensor | None#
None
- bridge.training.gpt_step._resolve_packed_batch(
- packed_seq_metadata: dict[str, bridge.training.gpt_step._PackedMetadataValue] | None,
- *,
- config,
- tokens: torch.Tensor | None,
- labels: torch.Tensor | None,
- _get_packed_seq_params_fn=None,
Normalize packed-sequence metadata from any packing mode into PackedSeqParams.
Dataset-level packing (offline, in-batch, Energon) yields
cu_seqlensdicts that :func:get_packed_seq_paramsconverts; global-batch packing yields a finishedPackedSeqParams(with its per-microbatch CP group) under thepacked_seq_paramskey.
- bridge.training.gpt_step._forward_step_common(
- state: megatron.bridge.training.state.GlobalState,
- data_iterator: Iterable,
- model: megatron.core.models.gpt.GPTModel,
- return_schedule_plan: bool = False,
- *,
- _get_batch_fn=None,
- _get_packed_seq_params_fn=None,
Forward training step.
- Parameters:
state β Global state for the run
data_iterator β Input data iterator
model β The GPT Model
return_schedule_plan (bool) β Whether to return the schedule plan instead of the output tensor
- Returns:
tuple containing the output tensor and loss mask
- bridge.training.gpt_step.forward_step(
- state: megatron.bridge.training.state.GlobalState,
- data_iterator: Iterable,
- model: megatron.core.models.gpt.GPTModel,
- return_schedule_plan: bool = False,
Forward training step.
- Parameters:
state β Global state for the run
data_iterator β Input data iterator
model β The GPT Model
return_schedule_plan (bool) β Whether to return the schedule plan instead of the output tensor
- Returns:
tuple containing the output tensor and the loss function
- bridge.training.gpt_step._create_loss_function(
- loss_mask: torch.Tensor,
- check_for_nan_in_loss: bool,
- check_for_spiky_loss: bool,
Create a partial loss function with the specified configuration.
- Parameters:
loss_mask β Used to mask out some portions of the loss
check_for_nan_in_loss β Whether to check for NaN values in the loss
check_for_spiky_loss β Whether to check for spiky loss values
- Returns:
A partial function that can be called with output_tensor to compute the loss
- bridge.training.gpt_step.forward_step_modelopt(
- state: megatron.bridge.training.state.GlobalState,
- data_iterator: Iterable,
- model: megatron.core.models.gpt.GPTModel,
- return_schedule_plan: bool = False,
Forward training step with ModelOpt required modifications.
- Parameters:
state β Global state for the run
data_iterator β Input data iterator
model β The GPT Model
return_schedule_plan (bool) β Whether to return the schedule plan instead of the output tensor
- Returns:
tuple containing the output tensor and the loss function
- bridge.training.gpt_step._create_loss_function_modelopt(
- loss_mask: torch.Tensor,
- model: megatron.core.models.gpt.GPTModel,
- check_for_nan_in_loss: bool,
- check_for_spiky_loss: bool,
Create a partial loss function with the specified configuration.
Kept here for backward compatibility with tests and callers that patch
megatron.bridge.training.gpt_step.masked_next_token_loss.- Parameters:
loss_mask β Used to mask out some portions of the loss
model β The GPT Model
check_for_nan_in_loss β Whether to check for NaN values in the loss
check_for_spiky_loss β Whether to check for spiky loss values
- Returns:
A partial function that can be called with output_tensor to compute the loss