bridge.models.ernie.ernie55_config#
ERNIE 5.5 configuration: the transformer config and the builder-backed HybridModel config.
- class:
Ernie55TransformerConfigis Bridge’s MLA config plus the ERNIE fields Megatron-Core lacks.
- class:
Ernie55ModelConfigis theHybridModelconfig whose builder (:class:~megatron.bridge.models.ernie.ernie55_builder.Ernie55ModelBuilder) constructs- class:
~megatron.bridge.models.ernie.modeling_ernie55.model.Ernie55HybridModelon every pipeline stage.
The hybrid layout helpers translate between the Hugging Face layer description (
compress_ratios,first_k_dense_replace) and the hybrid pattern: every ERNIE layer is two hybrid layers, an attention symbol (Hfor an H layer,Dfor a D layer) followed by-(dense MLP) orE(MoE), and every MTP depth repeats the layer description of itscompress_ratiosentry ("H-DEHEDE/DE"for the 4-layer proxy with one MTP depth).
Module Contents#
Classes#
Bridge |
|
An ERNIE 5.5 hybrid pattern, split into ERNIE layers. |
|
ERNIE 5.5 |
Functions#
Split a pipe-free pattern section into |
|
Parse and validate an ERNIE 5.5 hybrid pattern. |
|
Build the hybrid pattern of an ERNIE 5.5 Hugging Face layer description. |
|
Megatron-Core |
|
Split an ERNIE 5.5 hybrid pattern into |
Data#
Hugging Face |
|
Hugging Face |
|
API#
- bridge.models.ernie.ernie55_config.__all__#
[‘ERNIE55_D_COMPRESS_RATIO’, ‘ERNIE55_H_COMPRESS_RATIO’, ‘Ernie55HybridLayout’, ‘Ernie55ModelConfig’…
- bridge.models.ernie.ernie55_config.ERNIE55_H_COMPRESS_RATIO#
128
Hugging Face
compress_ratiosentry of an H layer (heavily compressed attention).
- bridge.models.ernie.ernie55_config.ERNIE55_D_COMPRESS_RATIO#
None
Hugging Face
compress_ratiosentry of a D layer (latent MQA with DSA top-k).
- bridge.models.ernie.ernie55_config._ATTENTION_SYMBOLS#
None
- bridge.models.ernie.ernie55_config._RATIO_OF_SYMBOL#
None
- bridge.models.ernie.ernie55_config._MLP_SYMBOLS#
()
- bridge.models.ernie.ernie55_config._CSA_RATIO_OF_SYMBOL#
None
- class bridge.models.ernie.ernie55_config.Ernie55TransformerConfig#
Bases:
megatron.bridge.models.transformer_config.MLATransformerConfigBridge
MLATransformerConfigplus the ERNIE 5.5 fields the D-layer, H-layer and MoE modules read.Existing Megatron-Core fields configure the rest of the D layer:
csa_window_size(sliding windowW),dsa_indexer_topk/dsa_indexer_n_heads/dsa_indexer_head_dim,dsa_indexer_loss_coeffwithdsa_indexer_use_sparse_loss, anddsa_kernel_backend("cudnn"fused,"none"PyTorch reference).H layers (Megatron-Core’s DSv4 hybrid attention at compress ratio 128) read the stack geometry (
num_attention_heads,q_lora_rank,v_head_dim,qk_pos_emb_head_dim,output_projection_groups,output_projection_lora_rank),csa_window_sizeandcsa_compress_rotary_base(Hugging Facecompress_rope_theta, their RoPE base), plus- Attr:
ernie_hca_rope_typeand the shared ERNIE fieldsernie_vha_rank,ernie_vha_bf16_mixandernie_output_gate_fp32.
The MoE layers use Megatron-Core’s MoE fields:
num_moe_experts,moe_router_topk,moe_ffn_hidden_size,moe_shared_expert_intermediate_size,moe_router_topk_scaling_factor(initial value of the learned per-expert scale),moe_router_bias_update_rate,moe_latent_sizeandmoe_use_norm_before_up_proj. SiTU-GLU (Hugging Facehidden_act="situ") is Megatron-Core’sactivation_func_tanh_clamp_scale(activation_situ_beta) andactivation_func_tanh_clamp_scale_linear(activation_situ_linear_beta); see :mod:~megatron.bridge.models.ernie.modeling_ernie55.moe.Hyper-connections use Megatron-Core’s
enable_mhc_connections,mhc_num_residual_streamsandmhc_sinkhorn_iterations; ERNIE 5.5 changes their arithmetic, not their configuration (:mod:~megatron.bridge.models.ernie.modeling_ernie55.hyper_connection). MTP uses Megatron-Core’s fields and the hybrid pattern’s/depths, plus- Attr:
ernie_mtp_shared_last_layer. The multimax output head has no configuration.- Meth:
finalizevalidates the supported envelope with- Func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_config,- Func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_mhc_configand- Func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_multimax_config; with the DSv4 hybrid attention variant that H layers need, also with- Func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_hca_config; and, when MoE is configured, with :func:~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_moe_config.
False
SD-MTP (Hugging Face
mtp_shared_last_layer): every MTP depth’s inner layers share the Parameters of the decoder’s last layers, whose layer symbols they must repeat (DEfor ERNIE 5.5). :class:~megatron.bridge.models.ernie.modeling_ernie55.model.Ernie55HybridModelapplies it after construction. It cannot be combined with Megatron-FSDP, torch FSDP2 or meta-device initialization, which re-create parameters module by module; the training setup checks this with- Func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_mtp_sharing.
- ernie_norm_topk_prob: bool#
True
Divide the top-k gate values by their sum (plus 1e-20) when
moe_router_topk > 1, before the per-expert scale (Hugging Facenorm_topk_prob).
- ernie_vha_rank: int | None#
None
Rank
Rof the VHA head post-mixI + V U^T(U,Vare[heads, R]) of both the D and the H layers. Required when either is built; ERNIE 5.5 uses 16. Hugging Facevha_rank(optional; the released configs omit it, which means 16).
- ernie_hca_rope_type: str#
‘rope’
H-layer RoPE (Hugging Face
hca_rope_type):"rope"is plain RoPE atcsa_compress_rotary_base,"yarn"Megatron-Core’s YaRN at that base fromrotary_scaling_factor,original_max_position_embeddings,beta_fastandbeta_slow, rotated without the concentration factor as in the reference implementation.
- ernie_vha_bf16_mix: bool#
True
Form
I + V U^Tand apply it with GEMMs in the activation dtype (bf16 in training), the reference implementation’s default contract, in D and H layers. False accumulates the mix in fp32 and rounds once.
- ernie_output_gate_fp32: bool#
False
Run the output gate’s sigmoid and product in fp32 and round once, in D and H layers (Hugging Face
sigmoid_gate_fusion). False runs both in the activation dtype, the reference default.
- ernie_native_sink_grad: bool#
True
Let the cuDNN sparse-attention backward differentiate the attention sink on the fused path. True (the default) runs Megatron-Core’s
csa_sparse_attn.test_sink_gradientchecks its sink gradient at the 576-wide latent queries against the analytic gradient and an autograd reference; it has been checked on GB300 (sm_103), so run that test before relying on it on other GPUs. False uses the analytic sink gradient with a sink-free cuDNN backward. Has no effect on the reference path.
- ernie_d_num_attention_heads: int | None#
None
D-layer attention heads; None inherits
num_attention_heads.
- ernie_d_q_lora_rank: int | None#
None
D-layer q latent rank; None inherits
q_lora_rank.
- ernie_d_kv_lora_rank: int | None#
None
D-layer kv latent rank; None inherits
kv_lora_rank.
- ernie_d_qk_head_dim: int | None#
None
D-layer non-RoPE query/key head dim (Hugging Face
qk_nope_head_dim); None inheritsqk_head_dim.
- ernie_d_qk_pos_emb_head_dim: int | None#
None
D-layer RoPE head dim; None inherits
qk_pos_emb_head_dim.
- ernie_d_v_head_dim: int | None#
None
D-layer value head dim; None inherits
v_head_dim.
- ernie_d_rotary_base: float | None#
None
RoPE base of the D attention and its indexer (Hugging Face
rope_theta); None inheritsrotary_base.
- ernie_mqa_latent_rope_adjacent_pairing: bool#
True
Channel layout of the D-layer latent RoPE weights in the Hugging Face checkpoint (
mqa_latent_rope_adjacent_pairing):Truefor adjacent pairs(2k, 2k + 1),Falsefor the two halves. It has no effect on the model, which always rotates adjacent pairs (Megatron-Core’s AbsorbedMLA); weight conversion permutes the RoPE rows of a half-split checkpoint on import and back on export, and the exportedconfig.jsonkeeps the source’s value. The default is the model’s own layout.
- ernie_per_row_loss: bool#
False
Train with the reference implementation’s per-row LM loss (:func:
~megatron.bridge.models.ernie.ernie55_context_parallel.ernie55_per_row_lm_loss): every micro-batch (one packed THD row) is averaged over its own supervised tokens, counted over the context-parallel group, and the training loss is the mean over micro-batches. Requirescalculate_per_token_loss=False, which also makes the D-layer indexer loss per row, and the model then normalizes every MTP depth the same way (:mod:~megatron.bridge.models.ernie.modeling_ernie55.mtp_loss). A context-parallel rank whose tokens are all masked contributes 0 instead of NaN. The training step must use that loss function (:mod:~megatron.bridge.models.ernie.ernie55_stepdoes, and rejects inconsistent loss settings). There is no Hugging Face key.
- ernie_fused_ops: bool#
True
Run the reference implementation’s Triton kernels (adapted in
- Mod:
~megatron.bridge.models.ernie.modeling_ernie55.fused_ops) wherever their inputs fit: SiTU-GLU in the dense, routed and shared MLPs, the multimax head, and the RoPE of the H layers at context_parallel_size > 1 (Megatron-Core’scp_utils.apply_thd_cp_local_rope_unfused). CPU tensors, layouts the kernels do not take, andFalserun the eager paths. Megatron-Core’s SiTU-GLU calls do not carry the config, so that kernel goes by the model’s clamp scales: among models with the same scales in one process, the one built last decides; see- Mod:
~megatron.bridge.models.ernie.modeling_ernie55.fused_dispatch. The reference has no switch and always runs them on CUDA. There is no Hugging Face key; on the command line,model.ernie_fused_ops=false.
- ernie_reference_rmsnorm: bool#
False
Build every RMSNorm of the model with the reference implementation’s eager arithmetic (:class:
~megatron.bridge.models.ernie.modeling_ernie55.norm.Ernie55RMSNorm) instead of Transformer Engine’sTENorm: each layer’s input and pre-MLP norm (the MTP depths’ layers included), the D and H q/kv latent norms, the H compressor’s norm and the decoder’s final norm, the norms the reference builds asErnieRMSNorm. The MTP block’senorm,hnormand final norm stayTENorm, as in the reference. Both computebf16(x * rsqrt(mean(x^2) + eps) * w)with fp32 statistics; they sum the squares in different orders, so about 0.05% of the token norms differ by one bf16 ulp. The reference arithmetic reproduces the reference’s norms bitwise but is slower, so the recipe leaves it off; set it for bitwise parity runs against the reference. Parameter names and checkpoints are the same either way. There is no Hugging Face key; on the command line,model.ernie_reference_rmsnorm=true.
- finalize() None#
Run the deferred Megatron-Core post-init, then validate the ERNIE 5.5 envelopes.
The D-layer, hyper-connection and multimax envelopes are always checked; the hyper-connection check passes configs without
enable_mhc_connections.The H-layer envelope is checked only with
experimental_attention_variant="dsv4_hybrid", the variant Megatron-Core’s DSv4 attention requires; D-only stacks may use"dsa". The MoE envelope is checked only whennum_moe_expertsis set.- Raises:
ValueError – If
ernie_fused_opsorernie_reference_rmsnormis not a bool, ifernie_per_row_lossis combined withcalculate_per_token_lossor (with MTP)mtp_loss_early_backwardor an MTP loss other than cross entropy, or if a layer envelope is violated.RuntimeError –
If Megatron-Core lacks a piece the configured context parallelism needs (see
- func:
~megatron.bridge.models.ernie.modeling_ernie55.validate_ernie55_context_parallel_config).
- class bridge.models.ernie.ernie55_config.Ernie55HybridLayout#
An ERNIE 5.5 hybrid pattern, split into ERNIE layers.
- Parameters:
layers –
(attention symbol, MLP symbol)of every decoder layer, in order.mtp_layers –
(attention symbol, MLP symbol)of every layer of one MTP depth.mtp_depths – Number of MTP depths (each repeats
mtp_layers).stage_boundaries – Indices into
layerswhere a new pipeline stage starts (|).
- layers: tuple[tuple[str, str], ...]#
None
- mtp_layers: tuple[tuple[str, str], ...]#
None
- mtp_depths: int#
None
- stage_boundaries: tuple[int, ...]#
None
- property num_hybrid_layers: int#
Hybrid layers of the decoder (two per ERNIE layer), MTP excluded.
- bridge.models.ernie.ernie55_config._ernie_layers(symbols: str, what: str) tuple[tuple[str, str], ...]#
Split a pipe-free pattern section into
(attention, MLP)pairs.
- bridge.models.ernie.ernie55_config.parse_ernie55_hybrid_pattern(
- pattern: str,
Parse and validate an ERNIE 5.5 hybrid pattern.
- Parameters:
pattern – Unified hybrid pattern, e.g.
"H-DEHEDE/DE"(|may separate pipeline stages, at ERNIE-layer boundaries only).- Returns:
The pattern’s ERNIE layers.
- Raises:
ValueError – If the pattern is not a sequence of ERNIE layers, or a pipeline stage boundary splits one.
- bridge.models.ernie.ernie55_config.ernie55_hybrid_layer_pattern(
- compress_ratios: collections.abc.Sequence[int],
- *,
- num_hidden_layers: int,
- first_k_dense_replace: int,
- num_mtp_layers: int,
Build the hybrid pattern of an ERNIE 5.5 Hugging Face layer description.
Layer
i(decoder layers first, then one entry per MTP depth) isHforcompress_ratios[i] == 128andDfor-2, followed by-wheni < first_k_dense_replaceandEotherwise.- Parameters:
compress_ratios –
num_hidden_layers + num_mtp_layerscompress ratios.num_hidden_layers – Decoder layers.
first_k_dense_replace – Leading dense layers.
num_mtp_layers – MTP depths.
- Returns:
The unified hybrid pattern, e.g.
"H-DEHEDE/DE".- Raises:
ValueError – On an unknown compress ratio, a
compress_ratioslength that does not cover the layers, or MTP depths that differ (Megatron-Core repeats one MTP pattern per depth).
- bridge.models.ernie.ernie55_config.ernie55_csa_compress_ratios(pattern: str) list[int]#
Megatron-Core
csa_compress_ratiosof an ERNIE 5.5 hybrid pattern.One entry per hybrid layer, the decoder’s (pipes skipped) and then every MTP depth’s:
128for anHlayer and0for every other symbol (D layers are not DSv4 layers; Megatron-Core’s DSv4 root accepts only 0, 4 and 128).- Parameters:
pattern – Unified hybrid pattern.
- Returns:
The per-hybrid-layer ratios.
- bridge.models.ernie.ernie55_config.ernie55_pipeline_layer_pattern(pattern: str, num_stages: int) str#
Split an ERNIE 5.5 hybrid pattern into
num_stagespipeline segments at ERNIE-layer boundaries.Existing
|separators are dropped, so a pattern saved under another pipeline size is re-split. Earlier stages take the remainder; the MTP depths stay after the last stage, where Megatron-Core runs them (SD-MTP needs the last decoder layer there too).- Parameters:
pattern – Unified hybrid pattern.
num_stages – Pipeline stages (
pipeline_model_parallel_size * virtual_pipeline_model_parallel_size).
- Returns:
The pattern with
num_stages - 1pipe separators.- Raises:
ValueError – If there are fewer ERNIE layers than stages.
- class bridge.models.ernie.ernie55_config.Ernie55ModelConfig#
Bases:
megatron.bridge.models.hybrid.model_config.BridgeHybridModelConfigERNIE 5.5
HybridModelconfig, built by :class:~megatron.bridge.models.ernie.ernie55_builder.Ernie55ModelBuilder.hybrid_layer_patternspells out the decoder and every MTP depth ("H-DEHEDE/DE"), sotransformer.num_layerscounts hybrid layers (two per ERNIE layer) andmtp_num_layersmust equal the pattern’s MTP depths.mtp_hybrid_override_patternis not used.- Meth:
finalizevalidates the model-level envelope before the transformer config’s own checks:
the pattern is a sequence of ERNIE layers (
H/Dthen-/E) andmtp_num_layersmatches its MTP depths;csa_compress_ratiosis the pattern’s (set from the pattern when unset);experimental_attention_variant="dsv4_hybrid",position_embedding_type="none"(every ERNIE attention owns its RoPE) and an untied output layer;with H layers, Megatron-Core’s
DSv4HybridAttention._post_o_group_projhook exists (Megatron-Core dev f78809f6d or later), and at context_parallel_size > 1 the stack is contiguous (cp_partition_mode="contiguous"), the DSv4 layout;with pipeline parallelism and no
|in the pattern, the pattern is split at ERNIE-layer boundaries (:func:ernie55_pipeline_layer_pattern); with pipeline parallelismvariable_seq_lengthsis turned on, because the ERNIE 5.5 SFT data path emits one packed THD row per micro-batch whose length is data-dependent (ernie55_steppads its documents to multiples of2 * CPat CP > 1), so the stages exchange tensor shapes before each transfer instead of posting static receive buffers sized fromseq_length; theallgatherMoE token dispatcher, which cannot take variable sequence lengths, is rejected there.
The builder always uses :func:
~megatron.bridge.models.ernie.modeling_ernie55.ernie55_hybrid_stack_specunlesshybrid_stack_specnames another ERNIE 5.5 stack spec, and never pads the vocabulary (the multimax head and the loss must see exactlyvocab_sizelogits).- builder: ClassVar[str]#
‘megatron.bridge.models.ernie.ernie55_builder.Ernie55ModelBuilder’
- transformer_config_class: ClassVar[type[megatron.bridge.models.transformer_config.TransformerConfig]]#
None
- ernie55_layout() bridge.models.ernie.ernie55_config.Ernie55HybridLayout#
The ERNIE layers of
hybrid_layer_pattern.- Raises:
ValueError – If the pattern is unset or not an ERNIE 5.5 pattern.
- dsa_indexer_metric_num_layers() int#
Divisor of the logged indexer loss: ERNIE layers plus MTP depths (the reference convention).
The D layers record their indexer losses in Megatron-Core’s DSA tracker; the logged
indexer lossis their sum divided by this number, as in the reference implementation (``(L_D + … + L_MTP) / (num_layersmtp)
, e.g./ 5`` for the 4-layer proxy with one MTP depth), not by the number of D layers.
- finalize() None#
Validate the ERNIE 5.5 model-level envelope, then finalize the hybrid and transformer configs.
- Raises:
ValueError – If the pattern, the MTP depths,
csa_compress_ratios, the attention variant, the position embedding, embedding tying or the context-parallel layout is outside the ERNIE 5.5 envelope.RuntimeError – If the pattern has H layers and Megatron-Core lacks the
_post_o_group_projhook.