bridge.training.gpt_step#

Module Contents#

Classes#

_StageBatchFields

Which batch fields one PP/VPP stage reads from the data iterator.

_ResolvedPackedBatch

One THD representation for the forward step, whichever packing mode produced the batch.

Functions#

_trim_padded_cu_seqlens_for_cp

Trim padded THD cu_seqlens without introducing a CUDA sync.

_has_packed_sequence_metadata

Return whether a dataloader batch contains packed-sequence metadata.

_packed_metadata_for_forward

Extract sequence metadata, including padding masks for unpacked batches.

_patch_mcore_schedule_plan_padding_mask

Forward the schedule-plan chunk mask into the pinned MCore MoE router.

_validate_packed_moe_cuda_graph

Reject router-scoped TE graphs that cannot consume token padding masks.

_prepare_packed_padding_mask

Prepare an alignment-padding mask for the current model stage.

_cu_seqlens_for_cp_partition

Return the cu-seqlens tensor TE should use to partition packed THD tokens.

_uses_packed_sequence_metadata

Return whether the dataset is expected to provide packed sequence metadata.

_middle_pp_stage_needs_batch

Return whether middle PP stages need batch metadata for attention.

_uses_inter_document_masking

Return whether the batch carries Core GPTDataset document boundaries to adapt for attention.

_validate_inter_document_masking

Reject settings the GPT and DSv4 steps do not support with document masking.

_layout_stage_has_mtp

Return whether a parsed or raw pipeline layout stage owns MTP layers.

_current_stage_has_mtp_from_layout

Return whether the current PP/VPP stage owns the configured MTP block, derived from layout.

_current_stage_needs_mtp_inputs_from_layout

Return whether this stage needs token ids for MTP embedding lookup, derived from layout.

_stage_batch_fields

Return the batch fields get_batch reads on this PP/VPP stage.

_rank_reads_batch

Return whether any model chunk on this rank reads the data iterator in a training iteration.

_reads_batch_on_skip

Return whether the GPT step reads the data iterator on this rank.

_partition_packed_batch_for_cp

Partition THD/packed batches across context-parallel ranks.

_adapt_document_boundaries

Convert the document boundaries of one Core GPTDataset row to THD Q/KV fields.

get_batch_from_iterator

Get a batch of data from the iterator.

_keep_full_position_ids_for_cp

Whether the model’s rotary embedding CP-shards the position ids itself.

get_batch

Generate a batch.

_resolve_packed_batch

Normalize packed-sequence metadata from any packing mode into PackedSeqParams.

_forward_step_common

Forward training step.

forward_step

Forward training step.

_create_loss_function

Create a partial loss function with the specified configuration.

forward_step_modelopt

Forward training step with ModelOpt required modifications.

_create_loss_function_modelopt

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,
) → torch.Tensor#

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],
) → dict[str, bridge.training.gpt_step._PackedMetadataValue] | None#

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,
) → torch.Tensor | None#

Prepare an alignment-padding mask for the current model stage.

bridge.training.gpt_step._cu_seqlens_for_cp_partition(
batch: dict[str, torch.Tensor],
) → 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,
) → bool#

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,
) → bool#

Return whether middle PP stages need batch metadata for attention.

bridge.training.gpt_step._uses_inter_document_masking(
cfg: megatron.bridge.training.config.ConfigContainer,
) → bool#

Return whether the batch carries Core GPTDataset document boundaries to adapt for attention.

Only GPTDatasetConfig builds Core GPTDataset rows, whose padded cu_seqlens layout get_batch_from_iterator adapts. Other datasets that expose an inter_document_masking attribute are left unchanged.

bridge.training.gpt_step._validate_inter_document_masking(
cfg: megatron.bridge.training.config.ConfigContainer,
) → None#

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,
) → bool#

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,
) → bool#

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,
) → bool#

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,
) → bridge.training.gpt_step._StageBatchFields#

Return the batch fields get_batch reads 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],
) → bool#

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,
) → bool#

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,
) → dict[str, torch.Tensor]#

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],
) → dict[str, torch.Tensor]#

Convert the document boundaries of one Core GPTDataset row to THD Q/KV fields.

Core pads cu_seqlens to 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_seqlens and max_seqlen.

Returns:

A new batch with cu_seqlens_q, cu_seqlens_kv, max_seqlen_q and max_seqlen_kv in place of cu_seqlens and max_seqlen.

Raises:

ValueError – If cu_seqlens is 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 if max_seqlen is 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,
) → dict[str, torch.Tensor]#

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,
) → tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, dict[str, bridge.training.gpt_step._PackedMetadataValue] | 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,
) → bridge.training.gpt_step._ResolvedPackedBatch#

Normalize packed-sequence metadata from any packing mode into PackedSeqParams.

Dataset-level packing (offline, in-batch, Energon) yields cu_seqlens dicts that :func:get_packed_seq_params converts; global-batch packing yields a finished PackedSeqParams (with its per-microbatch CP group) under the packed_seq_params key.

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,
) → tuple[torch.Tensor, torch.Tensor]#

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,
) → tuple[torch.Tensor, functools.partial]#

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,
) → functools.partial#

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,
) → tuple[torch.Tensor, functools.partial]#

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,
) → functools.partial#

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