bridge.models.ernie.modeling_ernie55.hyper_connection#
ERNIE 5.5 manifold-constrained hyper-connections (mHC): the eager fp32 mapping and mixing contract.
Megatron-Core’s HyperConnectionHybridLayer wraps every hybrid layer in a
HyperConnectionModule. ERNIE 5.5 keeps that structure and Megatron-Core’s parameters,
initialization and autograd plumbing, and changes only the arithmetic of four operations. For the
streams X = [x_1 .. x_n] of one token (stored as [s, b, n*C], K = n*C):
proj = fp32(X) W^TwithW = mapping_proj.weight([n^2 + 2n, K], fp32), andr = 1 / (||fp32(X)||_2 / sqrt(K) + 1e-6)(the epsilon outside the square root);h = r * proj * [a_pre]*n ++ [a_post]*n ++ [a_res]*n^2 + bias;h_pre = sigmoid(h[:n]) + 1e-6,h_post = 2 sigmoid(h[n:2n]),H_res = Sinkhorn(h[2n:].view(n, n))withM = softmax(L, -1) + 1e-6, a column normalizationM / (colsum + 1e-6), theniterations - 1rounds of a row and a column normalization, plain autograd throughout;the layer input
a = sum_j h_pre_j x_j, in fp32 (the downcasting pre-norm rounds it once);the residual update
x_i <- sum_j H_res[j, i] x_j + h_post_i * yfor the layer outputy, in fp32 and rounded once to the stream dtype.
All four keep h_pre, h_post and H_res in fp32 and run eagerly, as the reference
implementation does. Megatron-Core by default casts the mappings to the stream dtype, and it compiles
its mixing operations with torch.compile. Two consequences make that unsuitable for ERNIE 5.5:
Precision. The decoder’s streams are fp32 (see
- class:
~megatron.bridge.models.ernie.modeling_ernie55.hybrid_stack.Ernie55HybridStack), so the cast is a no-op there, but the MTP layer’s streams are bf16: Megatron-Core rounds its mappings to bf16 and mixes in bf16, where ERNIE 5.5 mixes in fp32 and rounds once. Megatron-Core’smhc_keep_mappings_in_fp32(off by default) keeps the mappings in fp32, but its mixing operations stay compiled (see the next point).
Recompute consistency. Under full activation recompute the first forward runs under
torch.no_grad()and the backward replays it with gradients enabled. Compiled code may specialize the two differently and change reduction order (Megatron-Core’s own projection is eager for this reason; its other mHC operations are still compiled). A replay that differs from the forward changes the backward point, and through the MoE router top-k after the mHC aggregate, possibly the routing and the expert-token counts of the replay. Eager operations compute the same bits in both passes; the GPU testtest_ernie55_stack_gpu.pychecks this.
The fp32 GEMMs (the projection and the H_res mix) follow PyTorch’s TF32 setting, as the
reference implementation’s do, so parity runs must pin it.
Only the arithmetic changes, so parameter names, shapes, dtypes and initialization stay
Megatron-Core’s. :func:use_ernie55_hyper_connections switches existing Megatron-Core modules to
- class:
Ernie55HyperConnectionModulein place; the ERNIE decoder stack and model call it.
Module Contents#
Classes#
Megatron-Core’s |
Functions#
Sinkhorn-Knopp projection of |
|
|
|
|
|
Convert every Megatron-Core |
|
Raise |
Data#
API#
- bridge.models.ernie.modeling_ernie55.hyper_connection.__all__#
[‘Ernie55HyperConnectionModule’, ‘ernie55_h_aggregate’, ‘ernie55_h_post_bda’, ‘ernie55_sinkhorn’, ‘u…
- bridge.models.ernie.modeling_ernie55.hyper_connection.ernie55_sinkhorn(
- logits: torch.Tensor,
- iterations: int,
- eps: float,
Sinkhorn-Knopp projection of
[..., n, n]logits onto doubly stochastic matrices.M = softmax(logits, -1) + eps, then a column normalization, theniterations - 1rounds of a row and a column normalization, each dividing bysum + eps. Plain autograd.- Parameters:
logits – Residual-mixing logits,
[..., n, n].iterations – Total number of column normalizations (
mhc_sinkhorn_iterations).eps – Epsilon added after the softmax and to every normalizer.
- Returns:
The projected matrices, same shape and dtype as
logits.
- bridge.models.ernie.modeling_ernie55.hyper_connection.ernie55_h_aggregate(
- streams: torch.Tensor,
- h_pre: torch.Tensor,
sum_j h_pre_j x_jover the stream axis, in the promoted dtype (fp32 for fp32h_pre).- Parameters:
streams –
[s, b, n, C].h_pre –
[s, b, n].
- Returns:
[s, b, C].
- bridge.models.ernie.modeling_ernie55.hyper_connection.ernie55_h_post_bda(
- h_res: torch.Tensor,
- original_residual: torch.Tensor,
- h_post: torch.Tensor,
- x: torch.Tensor,
- bias: torch.Tensor | None,
H_res^T @ residual + h_post * (x [+ bias])in fp32, rounded once to the residual dtype.- Parameters:
h_res –
[s, b, n, n]fp32 residual mixing matrices.original_residual –
[s, b, n, C]streams before the update.h_post –
[s, b, n]fp32 expansion weights.x –
[s, b, C]layer output.bias – Optional
[C]layer output bias.
- Returns:
[s, b, n, C]inoriginal_residual.dtype.
- class bridge.models.ernie.modeling_ernie55.hyper_connection.Ernie55HyperConnectionModule(
- config: megatron.core.transformer.transformer_config.TransformerConfig,
- layer_number: int,
Bases:
megatron.core.transformer.hyper_connection.HyperConnectionModuleMegatron-Core’s
HyperConnectionModulewith the ERNIE 5.5 eager fp32 mapping and mixing.The ERNIE stack converts the modules Megatron-Core built with
- Func:
use_ernie55_hyper_connections, so their parameters, initialization and checkpoint keys are unchanged; constructing one directly gives the same module.compute_mappingsreturns fp32h_pre,h_postandH_res;aggregatereturns the fp32 layer input; the residual update (_h_post_bda_op, which Megatron-Core’s forward calls) mixes in fp32 and rounds once to the stream dtype. Both ways of getting an instance point Megatron-Core’s operation slots at the ERNIE operations; without that, Megatron-Core’s compiled residual update would run. The fused-kernel path and the dropout path (apply_h_res) are not used:- Func:
validate_ernie55_mhc_configrequiresuse_fused_mhc=Falseandhidden_dropout=0.
Initialization
- _use_ernie55_operations() None#
Point the operation slots Megatron-Core’s forward calls at the ERNIE 5.5 operations.
- compute_mappings(
- x: torch.Tensor,
Compute
h_preandh_post([s, b, n]) andH_res([s, b, n, n]), all fp32.- Parameters:
x –
[s, b, n*C]streams (fp32 in the decoder, bf16 in the MTP layer).- Returns:
(h_pre, h_post, h_res)in fp32.
- aggregate(
- x: torch.Tensor,
- h_pre: torch.Tensor,
- out: torch.Tensor | None = None,
Aggregate the streams into the fp32 layer input
sum_j h_pre_j x_j.- Parameters:
x –
[s, b, n*C]streams.h_pre –
[s, b, n]fp32 aggregation weights.out – Megatron-Core dev’s CUDA-graph arena slot; not supported.
- Returns:
[s, b, C]in fp32.- Raises:
NotImplementedError – If
outis given.
- bridge.models.ernie.modeling_ernie55.hyper_connection.use_ernie55_hyper_connections(root: torch.nn.Module) int#
Convert every Megatron-Core
HyperConnectionModuleunderrootto the ERNIE 5.5 one (in place).Idempotent: modules that are already :class:
Ernie55HyperConnectionModuleare left alone.- Parameters:
root – Any module, e.g. a decoder stack or a whole model.
- Returns:
The number of hyper-connection modules under
rootafter the conversion.- Raises:
TypeError – If a hyper-connection module is a subclass this function does not know.
- bridge.models.ernie.modeling_ernie55.hyper_connection.validate_ernie55_mhc_config(config: object) None#
Raise
ValueErrorifconfigenables hyper-connections outside the ERNIE 5.5 envelope.Configs without hyper-connections pass. With them:
use_fused_mhc=False: the ERNIE operations replace the unfused ones only.hidden_dropout=0: with dropout Megatron-Core mixes the residual throughapply_h_res, outside the ERNIE fp32 update.fp32_residual_connection=False: the decoder carries fp32 streams by its own entry cast.mhc_norm_eps_inside_sqrt=False(ERNIE adds the epsilon outside the square root) andmhc_learned_output_contract=True(ERNIE contracts the streams with the learnedhc_head).With pipeline parallelism,
pipeline_dtype=torch.float32: stages exchange the fp32 streams, and a narrower pipeline dtype would round them at every stage boundary.
- Parameters:
config – Transformer config.
- Raises:
ValueError – On the first violated requirement.