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_loss is 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 returns CP * S / N with num_tokens = 1 for 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 (and calculate_per_token_loss=False).

  • func:

    build_ernie55_thd_cp_batch packs samples into one THD micro-batch: every sample is padded to a multiple of 2 * CP rows (pad tokens with label -100 and continuing positions), the documents’ boundaries become one cu_seqlens tensor 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#

Ernie55ThdBatch

One packed THD micro-batch: this CP rank’s rows plus the metadata of the whole pack.

Functions#

ernie55_per_row_lm_loss

Per-row LM loss of one micro-batch, normalized like the reference implementation.

_padded_length

ernie55_cp_min_local_rows

Fewest rows a CP rank may hold under the contiguous partition of an ERNIE 5.5 stack.

build_ernie55_thd_cp_batch

Pack samples into one THD micro-batch and slice this CP rank’s rows, as the reference does.

Data#

__all__

IGNORE_LABEL

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

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 with b > 1 are pooled into one row the same way. With S the micro-batch’s summed token loss on this CP rank and N its supervised tokens summed over the CP group (clamped at 1), the function returns CP * S / N with num_tokens = 1: the schedule divides the loss by num_tokens and 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 default masked_next_token_loss would 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 None without 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 1 and 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, -100 where 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_seqlens tensor of the padded samples in all four cu_seqlens fields, 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_comp is 8 for ratio 4, else the ratio), and refuses a rank with fewer than D_window local rows. A stack without such layers has no minimum.

Parameters:

config – Model (transformer) config with csa_compress_ratios and csa_window_size.

Returns:

The minimum local row count, 1 when 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,
) → bridge.models.ernie.ernie55_context_parallel.Ernie55ThdBatch#

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 * CP rows (1 without context parallelism), the zigzag partition’s requirement and the reference’s padding rule: pad tokens get pad_token_id, label -100 and positions that continue the sample’s own, so each pad belongs to its sample’s document. The padded samples are concatenated; one int32 cu_seqlens tensor describes their boundaries and fills cu_seqlens_q, cu_seqlens_kv and 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 host cu_seqlens are prebuilt with Megatron-Core’s prebuild_thd_cp_partition_routes, so no layer synchronizes the device to build them, and the rank keeps its rows of cp_partition_mode:

  • "contiguous" (the DSv4 hybrid stack): rows [r * T / CP, (r + 1) * T / CP);

  • "zigzag" (a D-only stack): chunks r and 2 * CP - 1 - r of every sample.

Under the contiguous partition a pack shorter than CP * min_local_rows rows (short SFT samples, for example) gets more padding on its last sample, up to the next multiple of 2 * CP of 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 position t).

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 None without context parallelism.

  • cp_partition_mode – Partition of the stack’s rows at CP > 1, "contiguous" or "zigzag".

  • max_seqlen – max_seqlen_q/max_seqlen_kv of 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_seqlen below the longest padded sample, a min_local_rows below 1 or an unknown cp_partition_mode.