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
rholds the packed rows[r * T / CP, (r + 1) * T / CP);zigzag: every document is cut into
2 * CPequal chunks and rankrholds chunksrand2 * CP - 1 - rof 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_apifinds the converter inmegatron.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: thedsa_layouthost builders and thecp_partition_modefields ofTransformerConfigandPackedSeqParams. 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_configrejects CP > 1 there, and keeps rejecting it at config time if a port brings only some of the pieces.
- func:
check_thd_cp_metadatachecks a micro-batch’s packed metadata on the host.
- func:
zigzag_cp_geometryreturns 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’sdsa_layouthelpers and cached on the micro-batch’sPackedSeqParams(one entry, for the micro-batch’s current boundaries).
- func:
gather_cp_rowsall-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 exactlycu_seqlens_padded[-1] / CProws (no rows after the last document);Megatron-Core’s
prebuild_thd_cp_partition_routes(orfinalize_packed_seq_params) ran when the batch was built: it stores the conversion route and the host copies ofcu_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_qandmax_seqlen_kvare at least the longest padded document.
- func:
~megatron.bridge.models.ernie.ernie55_context_parallel.build_ernie55_thd_cp_batchbuilds such micro-batches.
Module Contents#
Classes#
Megatron-Core’s module-local CP partition-mode API (dev #6387). |
|
Where this rank’s zigzag rows sit in the packed micro-batch. |
Functions#
Return the module-local CP partition converter of this Megatron-Core build, or |
|
Megatron-Core pieces ERNIE 5.5 context parallelism calls that this build lacks (empty on dev). |
|
Return Megatron-Core’s module-local CP partition converter, or |
|
Return the CP partition converter, or raise for Megatron-Core builds that cannot run ERNIE 5.5 CP. |
|
Raise |
|
Check a packed micro-batch for context parallelism on the host; return its document boundaries. |
|
Return the zigzag geometry of this rank’s rows, built on the host and cached on the micro-batch. |
|
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_seqlenson itsPackedSeqParams.
- 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,
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
Nonewhen 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_layouthost builders of the zigzag positions and the key permutation, and thecp_partition_modefields ofTransformerConfigandPackedSeqParams. 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,
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,
Raise
ValueErrorifconfigis 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_lossneeds Megatron-Core dev’s grouped MTP roll (:data:~megatron.bridge.models.ernie.modeling_ernie55.mtp_loss.PER_ROW_MTP_LOSS_SUPPORTED);cp_partition_modemust be"contiguous"(thedsv4_hybridstack, converted to zigzag inside each D layer) or"zigzag"(a D-only"dsa"stack).
Multi-token prediction is supported: with
ernie_per_row_lossthe 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,
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, orNoneto 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,
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_modemust be"zigzag". Positions and the key permutation come from Megatron-Core’sbuild_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 onpacked_seq_params, so every D layer of the micro-batch (and its recomputation) reuses it. The cache holds one entry: aPackedSeqParamsreused 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,
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.