bridge.models.ernie.ernie55_mappings#

Hugging Face <-> Megatron weight mappings for ERNIE 5.5 (Ernie5_5_MoeForCausalLM).

func:

ernie55_mapping_registry returns the :class:MegatronMappingRegistry a bridge’s mapping_registry() returns; it covers every parameter and persistent buffer of

class:

~megatron.bridge.models.ernie.modeling_ernie55.model.Ernie55HybridModel and every tensor of a Hugging Face ERNIE 5.5 checkpoint. Export writes every tensor in its ERNIE 5.5 dtype, so a checkpoint that stores the keep-in-fp32 tensors in F32 round-trips bitwise; one that stores them in bf16, as the released checkpoints do, comes back with those tensors in F32 (values unchanged).

class:

Ernie55WeightConversionMixin gives a

class:

~megatron.bridge.models.conversion.model_bridge.MegatronModelBridge subclass this registry and a strict import: the checkpoint must hold exactly the tensors the registry reads (:func:check_ernie55_checkpoint_keys), where Bridge alone would ignore a tensor no mapping reads.

Layout. Hugging Face layer i (model.layers.{i}) is two hybrid layers:

  • decoder.layers.{2i}, its attention: H when compress_ratios[i] == 128 (Megatron-Core’s DSv4 attention at compress ratio 128) or D when compress_ratios[i] == -2 (the latent-MQA layer);

  • decoder.layers.{2i+1}, its MLP: a dense MLP for i < first_k_dense_replace, MoE otherwise.

MTP depth k is Hugging Face layer num_hidden_layers + k. ERNIE 5.5’s MTP shares its body with the decoder’s last two hybrid layers (mtp_shared_last_layer; SD-MTP): the body’s Parameters are the decoder’s, so named_parameters() and this registry see them once, under their decoder names. The released checkpoints also store the body under every MTP layer (:func:ernie55_mtp_body_copy_names): the import skips those copies, and the export writes the ones its source checkpoint holds, because inference engines read their MTP draft layer for speculative decoding from them. The MTP router’s expert_bias is a buffer, owned by the MTP layer (Hugging Face block_sparse_moe.e_score_correction_bias). A non-shared MTP has no checkpoint to validate its key layout against and is rejected.

Every hybrid layer is wrapped in a hyper-connection module, so its weights live under .inner_layer. and its mHC weights under .hyper_connection. (Hugging Face self_attention_hyper_connection / mlp_hyper_connection).

Tensors that are not plain renames:

  • mapping_proj.weight of every hyper-connection module and every hc_head_fn are stored transposed by Hugging Face ([n C, n (n + 2)] and [n C, n]).

  • D layers: kv_b_proj ([H (nope + v), C], per head W_UK rows then W_UV rows) is split into k_b_proj = W_UK^T per head ([H C, nope]) and v_b_proj = W_UV per head ([H v, C]), the two matrices the latent-MQA layer keeps (:func:split_kv_b_proj), and joined again on export (:func:join_kv_b_proj).

  • D layers: Megatron-Core’s absorbed MLA rotates adjacent RoPE channel pairs. A checkpoint with mqa_latent_rope_adjacent_pairing: true uses the same convention and maps one to one; without it the reference implementation rotates channel i with i + R/2, so the R RoPE rows of q_b_proj (per head) and kv_a_proj_with_mqa are permuted, megatron[2i] = hf[i] and megatron[2i + 1] = hf[R/2 + i] (:func:rope_row_permutation). The indexer has no such switch.

  • Gated MLPs (dense, shared expert, routed experts): linear_fc1 is [gate; up] from gate_proj/up_proj (MoE: w1/w3), and w2/down_proj is linear_fc2. Grouped routed experts with Megatron-Core’s moe_mlp_glu_interleave_size, and a grouped shared expert (use_grouped_gemm_for_shared_expert) with moe_shared_expert_glu_interleave_size, keep their fc1 rows block-interleaved instead ([g_0:k, u_0:k, g_k:2k, ...]); the conversion interleaves them on import and restores [gate; up] on export. SequentialMLP experts and dense MLPs never do.

Dtypes. In a Hugging Face ERNIE 5.5 checkpoint the router (both gate matrices, the per-expert scale and e_score_correction_bias), every hyper-connection tensor, the hc_head_* contractions, the H-layer attn_sink and compressor ape, the indexer k_norm, the VHA factors and the latent-MoE projections are F32 by the keep-in-fp32 contract, and everything else is in the checkpoint dtype (dtype / torch_dtype, bf16). The released bf16 checkpoints store the contract tensors in bf16 too, and import widens them exactly (:func:_check_hf_dtype). Import rejects any other dtype mismatch, such as a checkpoint-dtype tensor stored in F32, instead of changing dtype silently. Megatron keeps the contract tensors in fp32, and loading one into a narrower parameter is an error; the other tensors load into parameters of the model’s dtype (an fp32 checkpoint into a bf16 model rounds them, as for any model). Export casts every tensor to its checkpoint dtype. Bridge keeps the D-layer attn_sink in fp32 while the checkpoint stores softmax_offset in the checkpoint dtype (bf16): imports widen it exactly, and exports round it back.

Supported envelope (anything else raises): compress_ratios entries 128 and -2 only, hybrid_mla_attention="mqa_dsa" for -2 layers, hca_rope_type "rope" or "yarn", and SD-MTP. Bridge reads n_routed_experts, first_k_dense_replace and n_shared_experts only; a config whose other spellings of them (which the reference implementation also accepts) would give a different value is rejected. ERNIE 5.5’s attention runs at tensor-parallel size 1, so non-expert tensors move whole; routed experts follow expert parallelism (Bridge renumbers local experts to global ones) and expert tensor parallelism. Exporting from Megatron-FSDP or GTP-sharded D-layer k_b_proj/v_b_proj is not supported.

Module Contents#

Classes#

Ernie55DLayerDims

Geometry of the D-layer (latent MQA) K/V up-projection and RoPE (Hugging Face hybrid_mla_*).

Ernie55HFLayout

What a Hugging Face ERNIE 5.5 config fixes about the checkpoint’s tensors.

_Ernie55TensorMapping

One Hugging Face tensor <-> one non-expert Megatron parameter or buffer, moved whole.

_Ernie55RopeRowsMapping

A D-layer projection whose Hugging Face RoPE rows are in half-rotation order (no adjacent pairing).

_Ernie55KVUpMapping

Hugging Face kv_b_proj <-> a D layer’s k_b_proj (part="k") or v_b_proj (part="v").

_Ernie55GatedMLPMapping

linear_fc1 = [gate; up] of a dense MLP, the shared expert or a routed expert, in the HF dtype.

_Ernie55ExpertFc2Mapping

A routed expert’s linear_fc2 (row parallel over expert tensor parallelism), in the HF dtype.

Ernie55WeightConversionMixin

ERNIE 5.5 weight conversion for a MegatronModelBridge subclass, listed before it among the bases.

Functions#

_hf_get

Read name from a Hugging Face config object or a plain dict.

_hf_checkpoint_dtype

The checkpoint dtype of a Hugging Face config (dtype or torch_dtype; bf16 when unset).

split_kv_b_proj

(k_b_proj, v_b_proj) of a D layer from Hugging Face kv_b_proj.

join_kv_b_proj

Hugging Face kv_b_proj from a D layer’s k_b_proj and v_b_proj (inverse of :func:split_kv_b_proj).

rope_row_permutation

perm with megatron_rows = hf_rows[perm] for D-layer RoPE rows without adjacent pairing.

_permute_rope_rows

Rows offset .. offset + len(perm) of every block-row block reordered as rows[perm].

_to_hf_dtype

_check_hf_dtype

A checkpoint tensor must have its ERNIE 5.5 dtype (the export dtype hf_dtype), or be a 16-bit copy of an F32 one.

ernie55_param_mappings

Every ERNIE 5.5 mapping for layout, in model order (see the module docstring).

ernie55_mapping_registry

The ERNIE 5.5 mapping registry for a Hugging Face config (a PretrainedConfig or a dict).

ernie55_hf_param_dtypes

Every tensor name of a Hugging Face ERNIE 5.5 checkpoint, with its ERNIE 5.5 (export) dtype.

ernie55_fp8_block_size

The block size of a checkpoint’s FP8 block-scaled weights, or None for an unquantized checkpoint.

_dequantize_fp8

An FP8 checkpoint tensor times its blockwise inverse scales, in dtype; any other tensor unchanged.

ernie55_mtp_body_copy_names

For every tensor of the shared MTP body, the names a checkpoint may also store it under.

ernie55_mtp_body_copy_keys

Names of the MTP body copies a checkpoint may hold besides :func:ernie55_hf_param_dtypes.

check_ernie55_checkpoint_keys

Check that a checkpoint holds exactly the tensors the ERNIE 5.5 registry reads for its config.

_check_checkpoint_of

func:

check_ernie55_checkpoint_keys on the checkpoint behind hf_pretrained, if there is one.

_exports_an_mtp_layer

Whether tasks convert a parameter an MTP layer owns, which a model built without MTP does not have.

Data#

API#

bridge.models.ernie.ernie55_mappings.__all__#

[‘ERNIE55_HF_ARCHITECTURE’, ‘HF_HCA_COMPRESS_RATIO’, ‘HF_LATENT_MQA_COMPRESS_RATIO’, ‘Ernie55DLayerD…

bridge.models.ernie.ernie55_mappings.ERNIE55_HF_ARCHITECTURE#

None

bridge.models.ernie.ernie55_mappings.HF_HCA_COMPRESS_RATIO#

128

bridge.models.ernie.ernie55_mappings.HF_LATENT_MQA_COMPRESS_RATIO#

None

bridge.models.ernie.ernie55_mappings._ATTENTION_SYMBOLS#

None

bridge.models.ernie.ernie55_mappings._MTP_BODY_MOE_INDEX#

1

bridge.models.ernie.ernie55_mappings._FP32#

None

bridge.models.ernie.ernie55_mappings._hf_get(
hf_config: Any,
name: str,
default: Any = None,
) → Any#

Read name from a Hugging Face config object or a plain dict.

bridge.models.ernie.ernie55_mappings._hf_checkpoint_dtype(hf_config: Any) → torch.dtype#

The checkpoint dtype of a Hugging Face config (dtype or torch_dtype; bf16 when unset).

class bridge.models.ernie.ernie55_mappings.Ernie55DLayerDims#

Geometry of the D-layer (latent MQA) K/V up-projection and RoPE (Hugging Face hybrid_mla_*).

num_heads: int#

None

kv_lora_rank: int#

None

qk_nope_head_dim: int#

None

qk_rope_head_dim: int#

None

v_head_dim: int#

None

class bridge.models.ernie.ernie55_mappings.Ernie55HFLayout#

What a Hugging Face ERNIE 5.5 config fixes about the checkpoint’s tensors.

.. attribute:: attention

"H" or "D" for every Hugging Face layer, MTP depths included (num_hidden_layers + num_mtp_layers entries, from compress_ratios).

.. attribute:: num_hidden_layers

Decoder layers.

.. attribute:: num_mtp_layers

MTP depths (num_nextn_predict_layers).

.. attribute:: first_k_dense

Leading decoder layers with a dense MLP (first_k_dense_replace); the others and every MTP depth are MoE.

.. attribute:: num_experts

Routed experts per MoE layer (n_routed_experts).

.. attribute:: shared_expert

Whether MoE layers have a shared expert (n_shared_experts > 0).

.. attribute:: moe_latent

Latent MoE (moe_latent_size): fp32 fc1/fc2_latent_proj.

.. attribute:: moe_latent_norm

The latent norm (latent_moe_use_norm, Megatron-Core’s fc2_norm).

.. attribute:: d_dims

D-layer geometry, or None without D layers.

.. attribute:: rope_adjacent_pairing

mqa_latent_rope_adjacent_pairing (rope_interleave when absent): D-layer RoPE rows are already in Megatron-Core’s adjacent-pair order.

.. attribute:: dtype

Checkpoint dtype of every tensor that is not F32 by contract.

attention: tuple[str, ...]#

None

num_hidden_layers: int#

None

num_mtp_layers: int#

None

first_k_dense: int#

None

num_experts: int#

None

shared_expert: bool#

None

moe_latent: bool#

None

moe_latent_norm: bool#

None

d_dims: bridge.models.ernie.ernie55_mappings.Ernie55DLayerDims | None#

None

rope_adjacent_pairing: bool#

None

dtype: torch.dtype#

None

classmethod from_hf_config(
hf_config: Any,
) → bridge.models.ernie.ernie55_mappings.Ernie55HFLayout#

Parse and validate a Hugging Face ERNIE 5.5 config (a PretrainedConfig or a dict).

Raises:
  • ValueError – If there is no config, or it is outside the supported envelope (see the module docstring).

  • NotImplementedError – For MTP depths that do not share the decoder’s last layer.

is_moe(hf_layer: int) → bool#

Whether Hugging Face layer hf_layer (an MTP depth included) has an MoE MLP.

property hybrid_layer_pattern: str#

Megatron-Core hybrid pattern of the model, MTP depths after / (e.g. "H-DEHEDE/DE").

bridge.models.ernie.ernie55_mappings.split_kv_b_proj(
kv_b_proj: torch.Tensor,
dims: bridge.models.ernie.ernie55_mappings.Ernie55DLayerDims,
) → tuple[torch.Tensor, torch.Tensor]#

(k_b_proj, v_b_proj) of a D layer from Hugging Face kv_b_proj.

kv_b_proj is [H (nope + v), C]; per head its first nope rows are W_UK and the next v rows W_UV. k_b_proj is W_UK^T per head, [H C, nope], and v_b_proj is W_UV per head, [H v, C].

Raises:

ValueError – If kv_b_proj does not have the shape dims gives.

bridge.models.ernie.ernie55_mappings.join_kv_b_proj(
k_b_proj: torch.Tensor,
v_b_proj: torch.Tensor,
dims: bridge.models.ernie.ernie55_mappings.Ernie55DLayerDims,
) → torch.Tensor#

Hugging Face kv_b_proj from a D layer’s k_b_proj and v_b_proj (inverse of :func:split_kv_b_proj).

Raises:

ValueError – If the tensors do not have the shapes dims gives.

bridge.models.ernie.ernie55_mappings.rope_row_permutation(rope_dim: int) → torch.Tensor#

perm with megatron_rows = hf_rows[perm] for D-layer RoPE rows without adjacent pairing.

perm[2i] = i and perm[2i + 1] = rope_dim / 2 + i: Megatron-Core’s de-interleave cat(x[0::2], x[1::2]) then restores the Hugging Face order before the half rotation.

bridge.models.ernie.ernie55_mappings._permute_rope_rows(
weight: torch.Tensor,
*,
block: int,
offset: int,
perm: torch.Tensor,
) → torch.Tensor#

Rows offset .. offset + len(perm) of every block-row block reordered as rows[perm].

bridge.models.ernie.ernie55_mappings._to_hf_dtype(
converted: dict[str, torch.Tensor],
dtype: torch.dtype,
) → dict[str, torch.Tensor]#
bridge.models.ernie.ernie55_mappings._check_hf_dtype(
hf_param: str,
hf_weight: torch.Tensor,
hf_dtype: torch.dtype,
) → None#

A checkpoint tensor must have its ERNIE 5.5 dtype (the export dtype hf_dtype), or be a 16-bit copy of an F32 one.

The released bf16 checkpoints store the keep-in-fp32 tensors in bf16 too; the import widens them, exactly, into their fp32 parameters. A tensor of the checkpoint dtype stored in F32 would be rounded instead, which is rejected.

Raises:

TypeError – If hf_weight is neither hf_dtype nor a 16-bit float for an F32 hf_dtype.

class bridge.models.ernie.ernie55_mappings._Ernie55TensorMapping(
megatron_param: str,
hf_param: str,
*,
hf_dtype: torch.dtype,
keep_fp32: bool = False,
transpose: bool = False,
)#

Bases: megatron.bridge.models.conversion.param_mapping.ReplicatedMapping

One Hugging Face tensor <-> one non-expert Megatron parameter or buffer, moved whole.

ERNIE 5.5’s attention runs at tensor-parallel size 1 (Megatron-Core’s DSv4 attention asserts it), so every non-expert tensor is replicated across the tensor-parallel group. hf_dtype is the tensor’s ERNIE 5.5 dtype: export casts to it, and import accepts it (or a 16-bit copy of an F32 tensor, see

Func:

_check_hf_dtype). keep_fp32 marks a tensor of the keep-in-fp32 contract (F32 on export), which must load into an fp32 Megatron tensor. transpose maps a 2-D tensor that Hugging Face stores transposed.

Initialization

_changes_layout#

False

local_hf_param_specs(
global_param_name: str | None = None,
) → tuple[megatron.bridge.models.conversion.param_mapping.LocalHFParamSpec, ...]#

Canonical local Hugging Face views; a transposed, permuted or split tensor has none.

resolve(
captures: tuple[str, ...],
) → megatron.bridge.models.conversion.param_mapping.MegatronParamMapping#
_check_target(megatron_module: torch.nn.Module) → None#

A keep-in-fp32 tensor must land in an fp32 Megatron tensor: a narrower one would round it.

_to_megatron_layout(hf_weights: torch.Tensor) → torch.Tensor#
_to_hf_layout(tensor: torch.Tensor) → torch.Tensor#
hf_to_megatron(
hf_weights: torch.Tensor,
megatron_module: torch.nn.Module,
) → torch.Tensor#
megatron_to_hf(
megatron_weights: torch.Tensor | None,
megatron_module: torch.nn.Module | None,
) → dict[str, torch.Tensor]#
class bridge.models.ernie.ernie55_mappings._Ernie55RopeRowsMapping(
megatron_param: str,
hf_param: str,
*,
hf_dtype: torch.dtype,
block: int,
offset: int,
rope_dim: int,
)#

Bases: bridge.models.ernie.ernie55_mappings._Ernie55TensorMapping

A D-layer projection whose Hugging Face RoPE rows are in half-rotation order (no adjacent pairing).

The rope_dim rows at offset of every block-row block are permuted with

Func:

rope_row_permutation on import and back on export: q_b_proj has one block per head (nope + rope rows), kv_a_proj_with_mqa one block (C + rope rows).

Initialization

_changes_layout#

True

resolve(
captures: tuple[str, ...],
) → megatron.bridge.models.conversion.param_mapping.MegatronParamMapping#
_to_megatron_layout(hf_weights: torch.Tensor) → torch.Tensor#
_to_hf_layout(tensor: torch.Tensor) → torch.Tensor#
class bridge.models.ernie.ernie55_mappings._Ernie55KVUpMapping(
megatron_param: str,
hf_param: str,
*,
hf_dtype: torch.dtype,
part: str,
dims: bridge.models.ernie.ernie55_mappings.Ernie55DLayerDims,
)#

Bases: bridge.models.ernie.ernie55_mappings._Ernie55TensorMapping

Hugging Face kv_b_proj <-> a D layer’s k_b_proj (part="k") or v_b_proj (part="v").

Both Megatron tensors read the one checkpoint tensor (:func:split_kv_b_proj). On export the k mapping emits the joined kv_b_proj from both tensors of its module (:func:join_kv_b_proj), broadcasting them from the pipeline stage that owns the layer, and the v mapping emits nothing. An export that reports Megatron source names (with_megatron_names) therefore attributes kv_b_proj to k_b_proj alone.

Bridge prepares the k_b_proj it passes in (gathering a Megatron-FSDP DTensor or a GTP shard), but the mapping reads v_b_proj from the module itself, so the export rejects a sharded v_b_proj (Megatron-FSDP or GTP) instead of joining a shard. The ERNIE 5.5 setups use neither; with SD-MTP, Megatron-FSDP is rejected anyway (validate_ernie55_mtp_sharing).

Initialization

_changes_layout#

True

resolve(
captures: tuple[str, ...],
) → megatron.bridge.models.conversion.param_mapping.MegatronParamMapping#
_to_megatron_layout(hf_weights: torch.Tensor) → torch.Tensor#
megatron_to_hf(
megatron_weights: torch.Tensor | None,
megatron_module: torch.nn.Module | None,
) → dict[str, torch.Tensor]#
class bridge.models.ernie.ernie55_mappings._Ernie55GatedMLPMapping(
megatron_param: str,
gate: str,
up: str,
*,
hf_dtype: torch.dtype,
glu_interleave: str | None = None,
)#

Bases: megatron.bridge.models.conversion.param_mapping.GatedMLPMapping

linear_fc1 = [gate; up] of a dense MLP, the shared expert or a routed expert, in the HF dtype.

Class:

GatedMLPMapping owns GLU row-layout conversion and tensor- and expert-parallel distribution. glu_interleave ("routed" or "shared") identifies mappings that cannot expose config-independent local HF views because their runtime rows may be block-interleaved. Import requires gate and up to be hf_dtype.

Initialization

resolve(
captures: tuple[str, ...],
) → megatron.bridge.models.conversion.param_mapping.MegatronParamMapping#
hf_to_megatron(
hf_weights: dict[str, torch.Tensor],
megatron_module: torch.nn.Module,
) → torch.Tensor#
megatron_to_hf(
megatron_weights: torch.Tensor | None,
megatron_module: torch.nn.Module | None,
) → dict[str, torch.Tensor]#
local_hf_param_specs(
global_param_name: str | None = None,
) → tuple[megatron.bridge.models.conversion.param_mapping.LocalHFParamSpec, ...]#

Canonical local gate/up views; none for an fc1 that Megatron-Core may keep GLU-interleaved.

Whether those rows are interleaved depends on the model config, which this method does not see, so a glu_interleave mapping reports no views and Bridge converts the tensor normally.

class bridge.models.ernie.ernie55_mappings._Ernie55ExpertFc2Mapping(
megatron_param: str,
hf_param: str,
*,
hf_dtype: torch.dtype,
)#

Bases: megatron.bridge.models.conversion.param_mapping.RowParallelMapping

A routed expert’s linear_fc2 (row parallel over expert tensor parallelism), in the HF dtype.

Import requires the checkpoint tensor to be hf_dtype.

Initialization

resolve(
captures: tuple[str, ...],
) → megatron.bridge.models.conversion.param_mapping.MegatronParamMapping#
hf_to_megatron(
hf_weights: torch.Tensor,
megatron_module: torch.nn.Module,
) → torch.Tensor#
megatron_to_hf(
megatron_weights: torch.Tensor | None,
megatron_module: torch.nn.Module | None,
) → dict[str, torch.Tensor]#
bridge.models.ernie.ernie55_mappings.ernie55_param_mappings(
layout: bridge.models.ernie.ernie55_mappings.Ernie55HFLayout,
) → list[megatron.bridge.models.conversion.param_mapping.MegatronParamMapping]#

Every ERNIE 5.5 mapping for layout, in model order (see the module docstring).

Parameters:

layout – The parsed Hugging Face config (:meth:Ernie55HFLayout.from_hf_config).

Returns:

The mappings, ready for :class:MegatronMappingRegistry.

bridge.models.ernie.ernie55_mappings.ernie55_mapping_registry(
hf_config: Any,
) → megatron.bridge.models.conversion.mapping_registry.MegatronMappingRegistry#

The ERNIE 5.5 mapping registry for a Hugging Face config (a PretrainedConfig or a dict).

Class:

Ernie55WeightConversionMixin makes it a bridge’s mapping_registry().

Raises:

ValueError, NotImplementedError – If the config is missing or outside the supported envelope (:meth:Ernie55HFLayout.from_hf_config).

bridge.models.ernie.ernie55_mappings.ernie55_hf_param_dtypes(
hf_config: Any,
) → dict[str, torch.dtype]#

Every tensor name of a Hugging Face ERNIE 5.5 checkpoint, with its ERNIE 5.5 (export) dtype.

Routed-expert wildcards are expanded over n_routed_experts. This is the key set the registry reads on import and writes on export; export writes these dtypes, and import also accepts a 16-bit copy of an F32 tensor.

bridge.models.ernie.ernie55_mappings._FP8_SCALE_SUFFIX#

‘_scale_inv’

bridge.models.ernie.ernie55_mappings.ernie55_fp8_block_size(hf_config: Any) → int | None#

The block size of a checkpoint’s FP8 block-scaled weights, or None for an unquantized checkpoint.

The released FP8 checkpoints (quantization_config with quant_method fp8 and weight_block_size [128, 128]) store their linear projections (attention, dense MLP, experts, latent and MTP projections) as e4m3 with one power-of-two inverse scale per block under <name>_scale_inv; the router, the norms, the hyper-connections and the other tensors keep their dtypes. The import dequantizes such a checkpoint tensor by tensor (:meth:Ernie55WeightConversionMixin.maybe_modify_loaded_hf_weight).

Parameters:

hf_config – The checkpoint’s Hugging Face config (a PretrainedConfig or a dict).

Raises:

NotImplementedError – For a quantization other than blockwise FP8 with square blocks.

bridge.models.ernie.ernie55_mappings._dequantize_fp8(
weight: torch.Tensor,
name: str,
hf_state_dict: collections.abc.Mapping[str, torch.Tensor],
block_size: int,
dtype: torch.dtype,
) → torch.Tensor#

An FP8 checkpoint tensor times its blockwise inverse scales, in dtype; any other tensor unchanged.

Raises:

ValueError – If weight is FP8 but not 2D, or <name>_scale_inv is missing or does not hold one scale per block_size x block_size block. A plain cast would silently load the weight without its scales.

bridge.models.ernie.ernie55_mappings.ernie55_mtp_body_copy_names(
hf_config: Any,
hf_keys: collections.abc.Iterable[str] | None = None,
) → dict[str, tuple[str, ...]]#

For every tensor of the shared MTP body, the names a checkpoint may also store it under.

Every MTP depth shares the decoder’s last layer (mtp_shared_last_layer), so the registry reads and writes that body once, under the last layer’s names. A checkpoint that also stores it under the MTP layer, as the released ones do, holds a copy of those tensors; this maps each last-layer name to its copies’ names. The released checkpoints name the copied hyper-connections transformer_layer.{self_attention,mlp}_hyper_connection.*; both spellings are listed. A name the MTP layer owns (its router’s e_score_correction_bias) is never a copy.

Parameters:
  • hf_config – The checkpoint’s Hugging Face config (a PretrainedConfig or a dict).

  • hf_keys –

    func:

    ernie55_hf_param_dtypes of hf_config, when the caller already has it.

Returns:

The copies’ names by last-layer tensor name; a tensor without copies has no entry.

bridge.models.ernie.ernie55_mappings.ernie55_mtp_body_copy_keys(
hf_config: Any,
hf_keys: collections.abc.Iterable[str] | None = None,
) → set[str]#

Names of the MTP body copies a checkpoint may hold besides :func:ernie55_hf_param_dtypes.

The union of :func:ernie55_mtp_body_copy_names. The import skips these tensors, and the export writes the ones its source checkpoint holds (:meth:Ernie55WeightConversionMixin.maybe_modify_converted_hf_weight).

Parameters:
  • hf_config – The checkpoint’s Hugging Face config (a PretrainedConfig or a dict).

  • hf_keys –

    func:

    ernie55_hf_param_dtypes of hf_config, when the caller already has it.

Returns:

The copies’ names.

bridge.models.ernie.ernie55_mappings.check_ernie55_checkpoint_keys(
hf_config: Any,
hf_keys: collections.abc.Iterable[str],
) → None#

Check that a checkpoint holds exactly the tensors the ERNIE 5.5 registry reads for its config.

Bridge’s import fails on a mapped tensor that the checkpoint lacks, but ignores a checkpoint tensor that no mapping reads, which would drop weights silently: for example the shared experts of a config without n_shared_experts. The one exception is :func:ernie55_mtp_body_copy_keys: the released checkpoints also store the shared MTP body under every MTP layer, a copy of the decoder’s last layer that the import does not read. An FP8 checkpoint (:func:ernie55_fp8_block_size) also holds the inverse scales of its weights, <name>_scale_inv, which the import consumes together with the weights.

Parameters:
  • hf_config – The checkpoint’s Hugging Face config (a PretrainedConfig or a dict).

  • hf_keys – The checkpoint’s tensor names.

Raises:
  • ValueError – If the config is outside the supported envelope, or tensors are missing or unexpected (the first ten of each are named).

  • NotImplementedError – For MTP depths that do not share the decoder’s last layer.

bridge.models.ernie.ernie55_mappings._check_checkpoint_of(hf_pretrained: Any) → None#
Func:

check_ernie55_checkpoint_keys on the checkpoint behind hf_pretrained, if there is one.

bridge.models.ernie.ernie55_mappings._exports_an_mtp_layer(
tasks: collections.abc.Iterable[Any],
) → bool#

Whether tasks convert a parameter an MTP layer owns, which a model built without MTP does not have.

class bridge.models.ernie.ernie55_mappings.Ernie55WeightConversionMixin#

ERNIE 5.5 weight conversion for a MegatronModelBridge subclass, listed before it among the bases.

  • meth:

    mapping_registry is :func:ernie55_mapping_registry of the bridge’s Hugging Face config.

  • Loading a checkpoint first checks that it holds exactly the tensors the registry reads (:func:check_ernie55_checkpoint_keys). A weight source with no checkpoint behind it (an external state dict, a config-only wrapper) is not checked.

  • Export also writes the shared MTP body under the MTP layers, for every copy the source checkpoint holds (:meth:maybe_modify_converted_hf_weight), so the export has the source checkpoint’s tensor names.

  • An FP8 checkpoint’s weights are dequantized as they are loaded, with the inverse scales stored next to them (:func:ernie55_fp8_block_size); a strict export does not expect those scales in the source shards.

Example::

@MegatronModelBridge.register_bridge(source=ERNIE55_HF_ARCHITECTURE, target=Ernie55HybridModel)
class Ernie55Bridge(Ernie55WeightConversionMixin, MegatronModelBridge):
    ...
DEQUANTIZED_SOURCE_KEY_SUFFIXES: ClassVar[tuple[str, ...]]#

()

mapping_registry() → megatron.bridge.models.conversion.mapping_registry.MegatronMappingRegistry#

The ERNIE 5.5 mapping registry of self.hf_config.

Raises:

ValueError, NotImplementedError – If hf_config is unset or outside the supported envelope.

load_weights_hf_to_megatron(
hf_pretrained: Any,
megatron_model: Any,
*args: Any,
**kwargs: Any,
) → Any#

Check the checkpoint’s tensor names, then load it as MegatronModelBridge does.

Raises:

ValueError – If the checkpoint does not hold exactly the tensors its config describes.

stream_weights_hf_to_megatron(
hf_pretrained: Any,
megatron_model: Any,
*args: Any,
**kwargs: Any,
) → collections.abc.Iterable[Any]#

Check the checkpoint’s tensor names (unless an external hf_state_dict is given), then stream it.

Raises:

ValueError – If the checkpoint does not hold exactly the tensors its config describes.

build_conversion_tasks(
hf_pretrained: Any,
megatron_model: Any,
*args: Any,
**kwargs: Any,
) → Any#

Build the conversion tasks as MegatronModelBridge does, and note whether the model has an MTP layer.

The copies of the shared MTP body belong to the MTP layer: :meth:maybe_modify_converted_hf_weight writes them only when the export writes that layer’s own tensors too. A model built without MTP exports no MTP layer, and a strict save of it leaves that layer out of the expected tensors.

Returns:

The conversion tasks.

_stream_weight_events_megatron_to_hf(
megatron_model: Any,
hf_pretrained: Any,
cpu: bool = True,
show_progress: bool = True,
conversion_tasks: Any = None,
merge_adapter_weights: bool = True,
weight_dtype: torch.dtype | None = None,
with_megatron_names: bool = False,
current_pp_stage_only: bool = False,
) → collections.abc.Iterable[Any]#

Export as MegatronModelBridge does, and note from caller-supplied tasks whether the model has MTP.

Tasks the export builds itself go through :meth:build_conversion_tasks on this bridge. Supplied tasks do not, and AutoBridge resolves a new bridge for every call, so the tasks of AutoBridge.get_conversion_tasks reach the export on a bridge that never built any. The decision of

Meth:

maybe_modify_converted_hf_weight is therefore taken here from the tasks this export runs, before any pipeline-stage filtering, and not from an earlier call.

maybe_modify_converted_hf_weight(
task: Any,
converted_weights_dict: dict[str, torch.Tensor],
hf_state_dict: collections.abc.Mapping[str, torch.Tensor],
) → dict[str, torch.Tensor]#

Also write the shared MTP body under the MTP layers, for every copy the source checkpoint holds.

The registry writes the body once, under the decoder’s last layer. The released checkpoints store it a second time under every MTP layer (:func:ernie55_mtp_body_copy_names), and inference engines build their MTP draft layer for speculative decoding from those names. Every copy the source checkpoint holds is written with the exported tensor, so the export has the source checkpoint’s tensor names and a strict save completes the shards that hold the copies. Nothing is added for a source checkpoint without copies (one written by an export that left them out, or a config-only wrapper), nor for a model built without MTP (:meth:build_conversion_tasks, :meth:_stream_weight_events_megatron_to_hf).

Parameters:
  • task – The conversion task of the exported tensors.

  • converted_weights_dict – The tensors the task’s mapping exported, by Hugging Face name.

  • hf_state_dict – The source checkpoint’s state, for its tensor names.

Returns:

converted_weights_dict, with the copies of its tensors added.

maybe_modify_loaded_hf_weight(
hf_param: str | dict[str, str],
hf_state_dict: collections.abc.Mapping[str, torch.Tensor],
) → torch.Tensor | dict[str, torch.Tensor]#

Load hf_param’s tensor(s); an FP8 checkpoint’s weights come back dequantized in the checkpoint dtype.

Raises:
  • ValueError – If an FP8 tensor has no <name>_scale_inv with one inverse scale per block.

  • NotImplementedError – For a quantization other than blockwise FP8 with square blocks.