bridge.models.ernie.modeling_ernie55.context_parallel#

Context parallelism (CP) for ERNIE 5.5: zigzag D layers inside a contiguous stack.

Two CP partitions of a packed THD micro-batch of T rows exist in Megatron-Core:

  • contiguous: rank r holds the packed rows [r * T / CP, (r + 1) * T / CP);

  • zigzag: every document is cut into 2 * CP equal chunks and rank r holds chunks r and 2 * CP - 1 - r of every document, in document order.

The H layers (Megatron-Core’s DSv4 hybrid attention) accept only the contiguous partition, and Megatron-Core forces it on the whole dsv4_hybrid stack. Everything Megatron-Core provides for the D layer accepts only zigzag: AbsorbedMLA’s packed RoPE, the DSA indexer’s RoPE and the fused CP>1 indexer scorer. A D layer therefore converts its input to zigzag with Megatron-Core dev’s module-local converter (#6387) and converts its output back (:class:~megatron.bridge.models.ernie.modeling_ernie55.latent_mqa_attention.Ernie55LatentMQASelfAttention), and its core attends from its local zigzag rows to the gathered keys of the whole pack (:class:~megatron.bridge.models.ernie.modeling_ernie55.latent_mqa_core.Ernie55LatentMQACoreAttention).

This module holds what both need:

  • func:

    load_cp_layout_api finds the converter in megatron.core.context_parallel_layout (Megatron-Core dev) or, in a build that moves it there, megatron.core.context_parallel.layout. It also requires the other dev pieces the zigzag D layer calls: the dsa_layout host builders and the cp_partition_mode fields of TransformerConfig and PackedSeqParams. Megatron-Core main has none of them, and its AbsorbedMLA would apply zigzag RoPE positions to contiguous rows without an error, so :func:validate_ernie55_context_parallel_config rejects CP > 1 there, and keeps rejecting it at config time if a port brings only some of the pieces.

  • func:

    check_thd_cp_metadata checks a micro-batch’s packed metadata on the host.

  • func:

    zigzag_cp_geometry returns the global packed position of every local zigzag row and the permutation that puts the rank-ordered gathered keys into global order, built from host lists by Megatron-Core’s dsa_layout helpers and cached on the micro-batch’s PackedSeqParams (one entry, for the micro-batch’s current boundaries).

  • func:

    gather_cp_rows all-gathers a per-row tensor over the CP group and reorders it.

A micro-batch at CP > 1 must satisfy (checked on the host, without a device-to-host synchronization):

  • packed THD input (qkv_format="thd", batch 1); SBHD input is not supported;

  • every padded document length is a multiple of 2 * CP, and the rank holds exactly cu_seqlens_padded[-1] / CP rows (no rows after the last document);

  • Megatron-Core’s prebuild_thd_cp_partition_routes (or finalize_packed_seq_params) ran when the batch was built: it stores the conversion route and the host copies of cu_seqlens (thd_cp_host_cu_seqlens_q/_kv) the layout is built from;

  • the query and key document boundaries are identical (self attention);

  • max_seqlen_q and max_seqlen_kv are at least the longest padded document.

func:

~megatron.bridge.models.ernie.ernie55_context_parallel.build_ernie55_thd_cp_batch builds such micro-batches.

Module Contents#

Classes#

CpLayoutApi

Megatron-Core’s module-local CP partition-mode API (dev #6387).

ZigzagCpGeometry

Where this rank’s zigzag rows sit in the packed micro-batch.

Functions#

_find_cp_layout_converter

Return the module-local CP partition converter of this Megatron-Core build, or None.

_missing_cp_layout_support

Megatron-Core pieces ERNIE 5.5 context parallelism calls that this build lacks (empty on dev).

load_cp_layout_api

Return Megatron-Core’s module-local CP partition converter, or None when this build cannot run ERNIE 5.5 CP.

require_cp_layout_api

Return the CP partition converter, or raise for Megatron-Core builds that cannot run ERNIE 5.5 CP.

validate_ernie55_context_parallel_config

Raise ValueError if config is outside the ERNIE 5.5 context-parallel envelope.

check_thd_cp_metadata

Check a packed micro-batch for context parallelism on the host; return its document boundaries.

zigzag_cp_geometry

Return the zigzag geometry of this rank’s rows, built on the host and cached on the micro-batch.

gather_cp_rows

All-gather a per-row tensor over the CP group and put its rows into global packed order.

Data#

API#

bridge.models.ernie.modeling_ernie55.context_parallel.__all__#

[‘CpLayoutApi’, ‘ZigzagCpGeometry’, ‘check_thd_cp_metadata’, ‘gather_cp_rows’, ‘load_cp_layout_api’,…

bridge.models.ernie.modeling_ernie55.context_parallel._CP_LAYOUT_MODULES#

(‘megatron.core.context_parallel.layout’, ‘megatron.core.context_parallel_layout’)

bridge.models.ernie.modeling_ernie55.context_parallel._DSA_LAYOUT_HOST_BUILDERS#

(‘build_packed_allgather_cp_query_positions_and_key_reorder_from_host’, ‘build_packed_allgather_cp_l…

bridge.models.ernie.modeling_ernie55.context_parallel._CP_PARTITION_MODE_HOLDERS#

()

bridge.models.ernie.modeling_ernie55.context_parallel._GEOMETRY_CACHE_ATTR#

‘_ernie55_zigzag_cp_geometry’

class bridge.models.ernie.modeling_ernie55.context_parallel.CpLayoutApi#

Megatron-Core’s module-local CP partition-mode API (dev #6387).

Parameters:
  • module – Name of the module the functions come from.

  • convert_module_input_tensors_cp_partition_mode – Converts a module’s input to a target partition and returns the converter for the way back.

  • prebuild_thd_cp_partition_routes – Stores a packed micro-batch’s conversion route and host cu_seqlens on its PackedSeqParams.

module: str#

None

convert_module_input_tensors_cp_partition_mode: collections.abc.Callable[..., Any]#

None

prebuild_thd_cp_partition_routes: collections.abc.Callable[..., Any]#

None

bridge.models.ernie.modeling_ernie55.context_parallel._find_cp_layout_converter() → bridge.models.ernie.modeling_ernie55.context_parallel.CpLayoutApi | None#

Return the module-local CP partition converter of this Megatron-Core build, or None.

bridge.models.ernie.modeling_ernie55.context_parallel._missing_cp_layout_support(
converter: bridge.models.ernie.modeling_ernie55.context_parallel.CpLayoutApi | None,
) → list[str]#

Megatron-Core pieces ERNIE 5.5 context parallelism calls that this build lacks (empty on dev).

bridge.models.ernie.modeling_ernie55.context_parallel.load_cp_layout_api() → bridge.models.ernie.modeling_ernie55.context_parallel.CpLayoutApi | None#

Return Megatron-Core’s module-local CP partition converter, or None when this build cannot run ERNIE 5.5 CP.

Besides the converter (dev #6387), the build must have every other Megatron-Core dev piece the zigzag D layer calls: the dsa_layout host builders of the zigzag positions and the key permutation, and the cp_partition_mode fields of TransformerConfig and PackedSeqParams. A build with only some of them (e.g. a main port that brings the converter alone) is rejected here, at config time, instead of failing in the first forward.

bridge.models.ernie.modeling_ernie55.context_parallel.require_cp_layout_api(
what: str,
) → bridge.models.ernie.modeling_ernie55.context_parallel.CpLayoutApi#

Return the CP partition converter, or raise for Megatron-Core builds that cannot run ERNIE 5.5 CP.

Parameters:

what – Subject of the error message, e.g. "ERNIE 5.5 D layers".

Raises:

RuntimeError – If Megatron-Core lacks the module-local CP partition converter or another piece of the zigzag CP path (see :func:load_cp_layout_api).

bridge.models.ernie.modeling_ernie55.context_parallel.validate_ernie55_context_parallel_config(
config: Any,
*,
layer: str,
) → None#

Raise ValueError if config is outside the ERNIE 5.5 context-parallel envelope.

Called by the D- and H-layer validators. Nothing is checked at context_parallel_size == 1. At CP > 1:

  • dynamic (hybrid) context parallelism is not supported;

  • Megatron-Core dev must have the module-local CP partition converter (#6387) and the other pieces of the zigzag CP path (:func:load_cp_layout_api);

  • multi-token prediction with ernie_per_row_loss needs Megatron-Core dev’s grouped MTP roll (:data:~megatron.bridge.models.ernie.modeling_ernie55.mtp_loss.PER_ROW_MTP_LOSS_SUPPORTED);

  • cp_partition_mode must be "contiguous" (the dsv4_hybrid stack, converted to zigzag inside each D layer) or "zigzag" (a D-only "dsa" stack).

Multi-token prediction is supported: with ernie_per_row_loss the model normalizes every MTP depth by the row’s supervised tokens counted over the CP group (:mod:~megatron.bridge.models.ernie.modeling_ernie55.mtp_loss), as the LM loss does. A build without the grouped MTP roll (Megatron-Core main, also once #7128 brings the converter) would keep Megatron-Core’s MTP loss, which divides each depth by this rank’s own supervised tokens, so that combination is rejected instead of training with the wrong normalization.

Parameters:
  • config – Stack-level or per-layer transformer config.

  • layer – Layer name for the error messages, "D" or "H".

Raises:
  • RuntimeError – If Megatron-Core lacks the CP partition converter or another piece of the zigzag CP path, or, for per-row MTP, the grouped MTP roll.

  • ValueError – On the first other violated requirement.

bridge.models.ernie.modeling_ernie55.context_parallel.check_thd_cp_metadata(
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None,
*,
cp_size: int,
local_rows: int,
expected_mode: str | None,
need_route: bool,
what: str,
) → list[int]#

Check a packed micro-batch for context parallelism on the host; return its document boundaries.

Parameters:
  • packed_seq_params – The micro-batch’s packed metadata.

  • cp_size – Context-parallel size (> 1).

  • local_rows – Number of packed rows this rank holds.

  • expected_mode – Required packed_seq_params.cp_partition_mode, or None to accept either.

  • need_route – Require the prebuilt conversion route (cp_partition_route).

  • what – Subject of the error messages.

Returns:

The compacted host cu_seqlens (thd_cp_host_cu_seqlens_q) of the padded documents.

Raises:
  • NotImplementedError – For SBHD input.

  • ValueError – If the metadata violates a requirement in the module docstring.

class bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry#

Where this rank’s zigzag rows sit in the packed micro-batch.

Parameters:
  • query_positions – int64 [local_rows] global packed position of every local row.

  • key_reorder – int64 [CP * local_rows] permutation that puts keys gathered in rank order (rank 0’s local rows, then rank 1’s, …) into global packed order.

  • cp_size – Context-parallel size.

  • cp_rank – This rank’s index in the CP group.

  • num_rows – Rows of the whole packed micro-batch, CP * local_rows.

query_positions: torch.Tensor#

None

key_reorder: torch.Tensor#

None

cp_size: int#

None

cp_rank: int#

None

num_rows: int#

None

bridge.models.ernie.modeling_ernie55.context_parallel.zigzag_cp_geometry(
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
*,
cp_group: torch.distributed.ProcessGroup,
local_rows: int,
device: torch.device,
what: str,
) → bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry#

Return the zigzag geometry of this rank’s rows, built on the host and cached on the micro-batch.

The micro-batch’s cp_partition_mode must be "zigzag". Positions and the key permutation come from Megatron-Core’s build_packed_allgather_cp_query_positions_and_key_reorder_from_host (the layout Megatron-Core’s DSA uses), so no device kernel or device-to-host copy runs; the result is cached on packed_seq_params, so every D layer of the micro-batch (and its recomputation) reuses it. The cache holds one entry: a PackedSeqParams reused for a micro-batch with other boundaries replaces it instead of accumulating device tensors.

Parameters:
  • packed_seq_params – The micro-batch’s packed metadata.

  • cp_group – Context-parallel group (size > 1).

  • local_rows – Number of packed rows this rank holds.

  • device – Device of the returned tensors.

  • what – Subject of the error messages.

Returns:

The geometry of this rank’s rows.

bridge.models.ernie.modeling_ernie55.context_parallel.gather_cp_rows(
local: torch.Tensor,
*,
geometry: bridge.models.ernie.modeling_ernie55.context_parallel.ZigzagCpGeometry,
cp_group: torch.distributed.ProcessGroup,
) → torch.Tensor#

All-gather a per-row tensor over the CP group and put its rows into global packed order.

The backward reduce-scatters the gradient: every rank’s contribution to a row reaches the rank that owns it, summed.

Parameters:
  • local – [local_rows, ...] tensor of this rank’s zigzag rows.

  • geometry – This rank’s zigzag geometry.

  • cp_group – Context-parallel group.

Returns:

[num_rows, ...] tensor of every packed row in global order.