bridge.models.ernie.ernie55_mappings#
Hugging Face <-> Megatron weight mappings for ERNIE 5.5 (Ernie5_5_MoeForCausalLM).
- func:
ernie55_mapping_registryreturns the :class:MegatronMappingRegistrya bridge’smapping_registry()returns; it covers every parameter and persistent buffer of- class:
~megatron.bridge.models.ernie.modeling_ernie55.model.Ernie55HybridModeland 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:
Ernie55WeightConversionMixingives a- class:
~megatron.bridge.models.conversion.model_bridge.MegatronModelBridgesubclass 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:Hwhencompress_ratios[i] == 128(Megatron-Core’s DSv4 attention at compress ratio 128) orDwhencompress_ratios[i] == -2(the latent-MQA layer);decoder.layers.{2i+1}, its MLP: a dense MLP fori < 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.weightof every hyper-connection module and everyhc_head_fnare stored transposed by Hugging Face ([n C, n (n + 2)]and[n C, n]).D layers:
kv_b_proj([H (nope + v), C], per headW_UKrows thenW_UVrows) is split intok_b_proj = W_UK^Tper head ([H C, nope]) andv_b_proj = W_UVper 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: trueuses the same convention and maps one to one; without it the reference implementation rotates channeliwithi + R/2, so theRRoPE rows ofq_b_proj(per head) andkv_a_proj_with_mqaare permuted,megatron[2i] = hf[i]andmegatron[2i + 1] = hf[R/2 + i](:func:rope_row_permutation). The indexer has no such switch.Gated MLPs (dense, shared expert, routed experts):
linear_fc1is[gate; up]fromgate_proj/up_proj(MoE:w1/w3), andw2/down_projislinear_fc2. Grouped routed experts with Megatron-Core’smoe_mlp_glu_interleave_size, and a grouped shared expert (use_grouped_gemm_for_shared_expert) withmoe_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.SequentialMLPexperts 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#
Geometry of the D-layer (latent MQA) K/V up-projection and RoPE (Hugging Face |
|
What a Hugging Face ERNIE 5.5 config fixes about the checkpoint’s tensors. |
|
One Hugging Face tensor <-> one non-expert Megatron parameter or buffer, moved whole. |
|
A D-layer projection whose Hugging Face RoPE rows are in half-rotation order (no adjacent pairing). |
|
Hugging Face |
|
|
|
A routed expert’s |
|
ERNIE 5.5 weight conversion for a |
Functions#
Read |
|
The checkpoint dtype of a Hugging Face config ( |
|
|
|
Hugging Face |
|
|
|
Rows |
|
A checkpoint tensor must have its ERNIE 5.5 dtype (the export dtype |
|
Every ERNIE 5.5 mapping for |
|
The ERNIE 5.5 mapping registry for a Hugging Face config (a |
|
Every tensor name of a Hugging Face ERNIE 5.5 checkpoint, with its ERNIE 5.5 (export) dtype. |
|
The block size of a checkpoint’s FP8 block-scaled weights, or |
|
An FP8 checkpoint tensor times its blockwise inverse scales, in |
|
For every tensor of the shared MTP body, the names a checkpoint may also store it under. |
|
Names of the MTP body copies a checkpoint may hold besides :func: |
|
Check that a checkpoint holds exactly the tensors the ERNIE 5.5 registry reads for its config. |
|
|
|
Whether |
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,
Read
namefrom 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 (
dtypeortorch_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_layersentries, fromcompress_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): fp32fc1/fc2_latent_proj... attribute:: moe_latent_norm
The latent norm (
latent_moe_use_norm, Megatron-Core’sfc2_norm)... attribute:: d_dims
D-layer geometry, or None without D layers.
.. attribute:: rope_adjacent_pairing
mqa_latent_rope_adjacent_pairing(rope_interleavewhen 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
None
- num_mtp_layers: int#
None
- first_k_dense: int#
None
- num_experts: int#
None
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,
Parse and validate a Hugging Face ERNIE 5.5 config (a
PretrainedConfigor 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,
(k_b_proj, v_b_proj)of a D layer from Hugging Facekv_b_proj.kv_b_projis[H (nope + v), C]; per head its firstnoperows areW_UKand the nextvrowsW_UV.k_b_projisW_UK^Tper head,[H C, nope], andv_b_projisW_UVper head,[H v, C].- Raises:
ValueError – If
kv_b_projdoes not have the shapedimsgives.
- 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,
Hugging Face
kv_b_projfrom a D layer’sk_b_projandv_b_proj(inverse of :func:split_kv_b_proj).- Raises:
ValueError – If the tensors do not have the shapes
dimsgives.
- bridge.models.ernie.ernie55_mappings.rope_row_permutation(rope_dim: int) torch.Tensor#
permwithmegatron_rows = hf_rows[perm]for D-layer RoPE rows without adjacent pairing.perm[2i] = iandperm[2i + 1] = rope_dim / 2 + i: Megatron-Core’s de-interleavecat(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,
Rows
offset .. offset + len(perm)of everyblock-row block reordered asrows[perm].
- bridge.models.ernie.ernie55_mappings._to_hf_dtype(
- converted: dict[str, torch.Tensor],
- dtype: torch.dtype,
- bridge.models.ernie.ernie55_mappings._check_hf_dtype(
- hf_param: str,
- hf_weight: torch.Tensor,
- hf_dtype: torch.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.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_weightis neitherhf_dtypenor a 16-bit float for an F32hf_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.ReplicatedMappingOne 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_dtypeis 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_fp32marks a tensor of the keep-in-fp32 contract (F32 on export), which must load into an fp32 Megatron tensor.transposemaps a 2-D tensor that Hugging Face stores transposed.
Initialization
- _changes_layout#
False
- local_hf_param_specs(
- global_param_name: str | None = None,
Canonical local Hugging Face views; a transposed, permuted or split tensor has none.
- resolve(
- captures: tuple[str, ...],
- _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,
- megatron_to_hf(
- megatron_weights: torch.Tensor | None,
- megatron_module: torch.nn.Module | None,
- 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._Ernie55TensorMappingA D-layer projection whose Hugging Face RoPE rows are in half-rotation order (no adjacent pairing).
The
rope_dimrows atoffsetof everyblock-row block are permuted with- Func:
rope_row_permutationon import and back on export:q_b_projhas one block per head (nope + roperows),kv_a_proj_with_mqaone block (C + roperows).
Initialization
- _changes_layout#
True
- resolve(
- captures: tuple[str, ...],
- _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._Ernie55TensorMappingHugging Face
kv_b_proj<-> a D layer’sk_b_proj(part="k") orv_b_proj(part="v").Both Megatron tensors read the one checkpoint tensor (:func:
split_kv_b_proj). On export thekmapping emits the joinedkv_b_projfrom both tensors of its module (:func:join_kv_b_proj), broadcasting them from the pipeline stage that owns the layer, and thevmapping emits nothing. An export that reports Megatron source names (with_megatron_names) therefore attributeskv_b_projtok_b_projalone.Bridge prepares the
k_b_projit passes in (gathering a Megatron-FSDP DTensor or a GTP shard), but the mapping readsv_b_projfrom the module itself, so the export rejects a shardedv_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, ...],
- _to_megatron_layout(hf_weights: torch.Tensor) torch.Tensor#
- megatron_to_hf(
- megatron_weights: torch.Tensor | None,
- megatron_module: torch.nn.Module | None,
- 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.GatedMLPMappinglinear_fc1 = [gate; up]of a dense MLP, the shared expert or a routed expert, in the HF dtype.- Class:
GatedMLPMappingowns 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 requiresgateandupto behf_dtype.
Initialization
- resolve(
- captures: tuple[str, ...],
- hf_to_megatron(
- hf_weights: dict[str, torch.Tensor],
- megatron_module: torch.nn.Module,
- megatron_to_hf(
- megatron_weights: torch.Tensor | None,
- megatron_module: torch.nn.Module | None,
- local_hf_param_specs(
- global_param_name: str | None = None,
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_interleavemapping 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.RowParallelMappingA 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, ...],
- hf_to_megatron(
- hf_weights: torch.Tensor,
- megatron_module: torch.nn.Module,
- megatron_to_hf(
- megatron_weights: torch.Tensor | None,
- megatron_module: torch.nn.Module | None,
- bridge.models.ernie.ernie55_mappings.ernie55_param_mappings( ) 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,
The ERNIE 5.5 mapping registry for a Hugging Face config (a
PretrainedConfigor a dict).- Class:
Ernie55WeightConversionMixinmakes it a bridge’smapping_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,
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
Nonefor an unquantized checkpoint.The released FP8 checkpoints (
quantization_configwithquant_methodfp8andweight_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
PretrainedConfigor 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,
An FP8 checkpoint tensor times its blockwise inverse scales, in
dtype; any other tensor unchanged.- Raises:
ValueError – If
weightis FP8 but not 2D, or<name>_scale_invis missing or does not hold one scale perblock_sizexblock_sizeblock. 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,
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-connectionstransformer_layer.{self_attention,mlp}_hyper_connection.*; both spellings are listed. A name the MTP layer owns (its router’se_score_correction_bias) is never a copy.- Parameters:
hf_config – The checkpoint’s Hugging Face config (a
PretrainedConfigor a dict).hf_keys –
- func:
ernie55_hf_param_dtypesofhf_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,
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
PretrainedConfigor a dict).hf_keys –
- func:
ernie55_hf_param_dtypesofhf_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],
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
PretrainedConfigor 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_keyson the checkpoint behindhf_pretrained, if there is one.
- bridge.models.ernie.ernie55_mappings._exports_an_mtp_layer(
- tasks: collections.abc.Iterable[Any],
Whether
tasksconvert 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
MegatronModelBridgesubclass, listed before it among the bases.- meth:
mapping_registryis :func:ernie55_mapping_registryof 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_configis unset or outside the supported envelope.
- load_weights_hf_to_megatron(
- hf_pretrained: Any,
- megatron_model: Any,
- *args: Any,
- **kwargs: Any,
Check the checkpoint’s tensor names, then load it as
MegatronModelBridgedoes.- 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,
Check the checkpoint’s tensor names (unless an external
hf_state_dictis 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,
Build the conversion tasks as
MegatronModelBridgedoes, 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_weightwrites 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,
Export as
MegatronModelBridgedoes, and note from caller-supplied tasks whether the model has MTP.Tasks the export builds itself go through :meth:
build_conversion_taskson this bridge. Supplied tasks do not, andAutoBridgeresolves a new bridge for every call, so the tasks ofAutoBridge.get_conversion_tasksreach the export on a bridge that never built any. The decision of- Meth:
maybe_modify_converted_hf_weightis 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],
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],
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_invwith one inverse scale per block.NotImplementedError – For a quantization other than blockwise FP8 with square blocks.