bridge.models.ernie.ernie55_context_parallel#
ERNIE 5.5 training-step pieces for context parallelism: per-row LM loss and packed THD batches.
Both follow the reference implementation’s conventions and are standalone, so the ERNIE 5.5 training step can wire them in:
- func:
ernie55_per_row_lm_lossis the per-row LM loss: the row is the micro-batch (one packed THD row), its summed token loss is divided by its supervised-token count, counted over the context-parallel group, and the training loss is the mean over micro-batches. It returnsCP * S / Nwithnum_tokens = 1for Megatron-Core’s three-tuple loss contract, because the schedule then divides only by the number of micro-batches and DDP averages the gradients over DP x CP. The model config must set- attr:
~megatron.bridge.models.ernie.ernie55_config.Ernie55TransformerConfig.ernie_per_row_loss(andcalculate_per_token_loss=False).
- func:
build_ernie55_thd_cp_batchpacks samples into one THD micro-batch: every sample is padded to a multiple of2 * CProws (pad tokens with label-100and continuing positions), the documents’ boundaries become onecu_seqlenstensor shared by queries and keys, the CP partition routes are prebuilt, and the rows of this CP rank are sliced out.
The MTP depths get the same per-row normalization inside the model
(:mod:~megatron.bridge.models.ernie.modeling_ernie55.mtp_loss); the training step only selects the LM loss.
Module Contents#
Classes#
One packed THD micro-batch: this CP rank’s rows plus the metadata of the whole pack. |
Functions#
Per-row LM loss of one micro-batch, normalized like the reference implementation. |
|
Fewest rows a CP rank may hold under the contiguous partition of an ERNIE 5.5 stack. |
|
Pack samples into one THD micro-batch and slice this CP rank’s rows, as the reference does. |
Data#
Label of tokens without a loss (padding, prompts). |
API#
- bridge.models.ernie.ernie55_context_parallel.__all__#
[‘IGNORE_LABEL’, ‘Ernie55ThdBatch’, ‘build_ernie55_thd_cp_batch’, ‘ernie55_cp_min_local_rows’, ‘erni…
- bridge.models.ernie.ernie55_context_parallel.IGNORE_LABEL#
None
Label of tokens without a loss (padding, prompts).
- bridge.models.ernie.ernie55_context_parallel.ernie55_per_row_lm_loss(
- loss_mask: torch.Tensor,
- output_tensor: torch.Tensor,
- *,
- cp_group: torch.distributed.ProcessGroup | None,
- check_for_nan_in_loss: bool = True,
- check_for_spiky_loss: bool = False,
Per-row LM loss of one micro-batch, normalized like the reference implementation.
The reference’s row is the micro-batch: a packed THD micro-batch (
b = 1, the only layout at CP > 1) is one row, and the samples of an SBHD micro-batch withb > 1are pooled into one row the same way. WithSthe micro-batch’s summed token loss on this CP rank andNits supervised tokens summed over the CP group (clamped at 1), the function returnsCP * S / Nwithnum_tokens = 1: the schedule divides the loss bynum_tokensand the number of micro-batches, and DDP averages the gradients over DP x CP, so the gradient is that of the mean over micro-batches of each micro-batch’s token mean, taken over all of its CP ranks’ tokens. A CP rank whose tokens are all masked contributes 0, never NaN.The reported
[S / N, 1 / CP]sums over DP x CP and the micro-batches to the total of the micro-batches’ token means and their number, so the logged value is the mean row loss.The training step must use this loss whenever the model config sets
ernie_per_row_loss: Bridge’s defaultmasked_next_token_losswould average each rank’s own token mean instead, without an error.- Parameters:
loss_mask –
[b, s](or[s]) local loss mask of the micro-batch, 1 for supervised tokens.output_tensor – Per-token losses of the same tokens,
loss_mask.numel()elements.cp_group – Context-parallel group, or
Nonewithout context parallelism.check_for_nan_in_loss – Run the rerun state machine’s NaN/Inf check on the local loss.
check_for_spiky_loss – Run the rerun state machine’s spiky-loss check on the local loss.
- Returns:
the scalar fp32 loss, an int
1and the two-element fp32 reporting tensor.- Return type:
(loss, num_tokens, {"lm loss": reporting})
- class bridge.models.ernie.ernie55_context_parallel.Ernie55ThdBatch#
One packed THD micro-batch: this CP rank’s rows plus the metadata of the whole pack.
- Parameters:
tokens –
[1, rows]token ids.labels –
[1, rows]targets,-100where there is no loss (padding included).loss_mask –
[1, rows]fp32,labels != -100.position_ids –
[1, rows]positions inside each sample, continuing through its padding.packed_seq_params – Metadata of the whole pack: one int32
cu_seqlenstensor of the padded samples in all fourcu_seqlensfields,max_seqlen_q == max_seqlen_kv, and at CP > 1 the CP partition mode and the prebuilt partition routes.
- tokens: torch.Tensor#
None
- labels: torch.Tensor#
None
- loss_mask: torch.Tensor#
None
- position_ids: torch.Tensor#
None
- packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams#
None
- bridge.models.ernie.ernie55_context_parallel._padded_length(length: int, multiple: int) int#
- bridge.models.ernie.ernie55_context_parallel.ernie55_cp_min_local_rows(config: object) int#
Fewest rows a CP rank may hold under the contiguous partition of an ERNIE 5.5 stack.
At CP > 1 every H layer (Megatron-Core’s DSv4 hybrid attention with a nonzero compress ratio) receives the
D_window = max(csa_window_size, d_comp)hidden rows left of its block from the previous CP rank (exchange_cp_boundary_hidden;d_compis 8 for ratio 4, else the ratio), and refuses a rank with fewer thanD_windowlocal rows. A stack without such layers has no minimum.- Parameters:
config – Model (transformer) config with
csa_compress_ratiosandcsa_window_size.- Returns:
The minimum local row count,
1when there is none.
- bridge.models.ernie.ernie55_context_parallel.build_ernie55_thd_cp_batch(
- samples: collections.abc.Sequence[tuple[torch.Tensor, torch.Tensor]],
- *,
- pad_token_id: int,
- cp_group: torch.distributed.ProcessGroup | None,
- cp_partition_mode: str = 'contiguous',
- max_seqlen: int | None = None,
- min_local_rows: int = 1,
- device: torch.device | str | None = None,
Pack samples into one THD micro-batch and slice this CP rank’s rows, as the reference does.
Every sample is padded to a multiple of
2 * CProws (1without context parallelism), the zigzag partition’s requirement and the reference’s padding rule: pad tokens getpad_token_id, label-100and positions that continue the sample’s own, so each pad belongs to its sample’s document. The padded samples are concatenated; one int32cu_seqlenstensor describes their boundaries and fillscu_seqlens_q,cu_seqlens_kvand both padded fields (Megatron-Core’s fused zigzag indexer scorer needs the query and key boundaries to be the same tensor). At CP > 1 the partition routes and hostcu_seqlensare prebuilt with Megatron-Core’sprebuild_thd_cp_partition_routes, so no layer synchronizes the device to build them, and the rank keeps its rows ofcp_partition_mode:"contiguous"(the DSv4 hybrid stack): rows[r * T / CP, (r + 1) * T / CP);"zigzag"(a D-only stack): chunksrand2 * CP - 1 - rof every sample.
Under the contiguous partition a pack shorter than
CP * min_local_rowsrows (short SFT samples, for example) gets more padding on its last sample, up to the next multiple of2 * CPof at least that size, so every CP rank holds the rows its H layers’ boundary exchange needs (:func:ernie55_cp_min_local_rows). These pads follow the same rule as the others: label-100, positions continuing the last sample’s, inside its document. The LM and MTP losses of the real tokens do not change (attention is causal and pads carry no loss); the indexer loss, normalized by the pack’s rows, counts them like any other pad rows.Labels must already be aligned with the inputs (
labels[t]is the target of positiont).- Parameters:
samples –
(input_ids, labels)pairs of equal-length 1-D integer tensors.pad_token_id – Token id of the padding.
cp_group – Context-parallel group, or
Nonewithout context parallelism.cp_partition_mode – Partition of the stack’s rows at CP > 1,
"contiguous"or"zigzag".max_seqlen –
max_seqlen_q/max_seqlen_kvof the metadata, at least the longest padded sample; pinning it (e.g. to the training sequence length) keeps the fused kernels’ compile keys stable. Defaults to the longest padded sample.min_local_rows –
Fewest rows each CP rank must hold under the contiguous partition (see
- func:
ernie55_cp_min_local_rows); ignored at CP = 1 and for"zigzag".
device – Device of the returned tensors; defaults to the samples’ device.
- Returns:
This rank’s :class:
Ernie55ThdBatch.- Raises:
RuntimeError – At CP > 1 without Megatron-Core’s CP partition converter (Megatron-Core main).
ValueError – For an empty batch, malformed samples, a
max_seqlenbelow the longest padded sample, amin_local_rowsbelow 1 or an unknowncp_partition_mode.