# Copyright (C) 2025 the HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from collections import defaultdict from copy import deepcopy from typing import TYPE_CHECKING from .core_model_loading import ( Chunk, Concatenate, ErnieFuseAndSplitTextVisionExperts, GroupWeightRename, Interleave, MergeModulelist, PermuteForRope, PrefixChange, Transpose, WeightConverter, WeightRenaming, WeightTransform, ) if TYPE_CHECKING: from .modeling_utils import PreTrainedModel from .quantizers import HfQuantizer _MODEL_TO_CONVERSION_PATTERN = { # Mixtral-style MoE "minimax": "mixtral", "minimax_m2": "mixtral", # Qwen2-style MoE "afmoe": "qwen2_moe", "deepseek_v2": "qwen2_moe", "deepseek_v3": "qwen2_moe", "deepseek_v32": "qwen2_moe", "dots1": "qwen2_moe", "ernie4_5_moe": "qwen2_moe", "glm4_moe": "qwen2_moe", "glm4_moe_lite": "qwen2_moe", "glm_moe_dsa": "qwen2_moe", "glm4v_moe": "qwen2_moe", "longcat_flash": "qwen2_moe", "solar_open": "qwen2_moe", "mellum": "qwen2_moe", "qwen3_moe": "qwen2_moe", "qwen3_omni_moe": "qwen2_moe", "qwen3_omni_moe_thinker": "qwen2_moe", "qwen3_next": "qwen2_moe", "hunyuan_v1_moe": "qwen2_moe", "flex_olmo": "qwen2_moe", "olmoe": "qwen2_moe", "exaone_moe": "qwen2_moe", "cohere2_moe": "qwen2_moe", "rt_detr_v2": "rt_detr", "pp_doclayout_v2": "rt_detr", "pp_doclayout_v3": "rt_detr", "sam3_tracker_video": "sam3_tracker", "AltCLIPVisionModel": "CLIPVisionModel", "ChineseCLIPVisionModel": "CLIPVisionModel", "CLIPSegVisionModel": "CLIPVisionModel", "MetaClip2VisionModel": "CLIPVisionModel", "mlcd_vision": "CLIPVisionModel", "mlcd": "CLIPVisionModel", "SiglipVisionModel": "CLIPVisionModel", "Siglip2VisionModel": "CLIPVisionModel", "xCLIPVisionModel": "CLIPVisionModel", "CLIPSegTextModel": "CLIPTextModel", "MetaClip2TextModel": "CLIPTextModel", "SiglipTextModel": "CLIPTextModel", "Siglip2TextModel": "CLIPTextModel", "xCLIPTextModel": "CLIPTextModel", "aria": "llava", "paligemma": "llava", "aya_vision": "llava", "got_ocr2": "llava", "gemma3": "llava", "internvl": "llava", "vipllava": "llava", "mistral3": "llava", "pp_chart2table": "llava", "voxtral": "qwen2_audio", "voxtral_realtime": "qwen2_audio", "audioflamingo3": "qwen2_audio", "glmasr": "qwen2_audio", "musicflamingo": "qwen2_audio", "granite_speech_plus": "granite_speech", "granitemoeshared": "granitemoe", "granitemoehybrid": "granitemoe", "gemma3n_text": "qwen3_5_text", "qwen3_5_moe_text": "qwen3_5_text", "llava_next_video": "llava_next", "llava_onevision": "llava_next", # class-based mappings "AriaModel": "LlavaModel", "PaliGemmaModel": "LlavaModel", "AyaVisionModel": "LlavaModel", "GotOcr2Model": "LlavaModel", "Gemma3Model": "LlavaModel", "InternVLModel": "LlavaModel", "VipLlavaModel": "LlavaModel", "Mistral3Model": "LlavaModel", "PPChart2TableModel": "LlavaModel", "LlavaNextModel": "LlavaModel", "LlavaNextVideoModel": "LlavaModel", "LlavaOnevisionModel": "LlavaModel", "FuyuModel": "LlavaModel", "MllamaModel": "LlavaModel", "VoxtralModel": "Qwen2AudioModel", "VoxtralRealtimeModel": "Qwen2AudioModel", "AudioFlamingo3Model": "Qwen2AudioModel", "GlmAsrModel": "Qwen2AudioModel", "MusicFlamingoModel": "Qwen2AudioModel", "GraniteSpeechPlusModel": "GraniteSpeechModel", "MaskFormerDetrDecoder": "DetrModel", "Qwen2_5_VLModel": "Qwen2VLModel", "Qwen2_5_VLForConditionalGeneration": "Qwen2VLForConditionalGeneration", "Tipsv2VisionBackbone": "Tipsv2VisionModel", # ViT-style vision models (old HuggingFace checkpoint format → new modular format) "ASTModel": "ViTModel", "BeitModel": "ViTModel", "DeiTModel": "ViTModel", "IJepaModel": "ViTModel", "ViTMAEModel": "ViTModel", "ViTMSNModel": "ViTModel", "VivitModel": "ViTModel", } def _build_checkpoint_conversion_mapping(): mapping = { # Cosmos3 Edge's composite checkpoint stores its dense reasoner text tower as conventional attention + MLP # blocks. The visual/projector tensors already use their native module names and intentionally need no mapping. "cosmos3_edge": [ WeightRenaming(r"^embed_tokens\.", "model.language_model.embed_tokens."), WeightRenaming(r"^norm\.", "model.language_model.norm."), WeightRenaming(r"^layers\.", "model.language_model.layers."), WeightRenaming(r"\.self_attn\.to_q\.", ".self_attn.q_proj."), WeightRenaming(r"\.self_attn\.to_k\.", ".self_attn.k_proj."), WeightRenaming(r"\.self_attn\.to_v\.", ".self_attn.v_proj."), WeightRenaming(r"\.self_attn\.to_out\.", ".self_attn.o_proj."), WeightRenaming(r"\.mlp\.up_proj\.", ".mlp.fc1."), WeightRenaming(r"\.mlp\.down_proj\.", ".mlp.fc2."), ], "inkling_mm_model": [ WeightRenaming(source_patterns=r"model\.llm\.layers", target_patterns=r"model.language_model.layers"), WeightRenaming( source_patterns=r"model\.llm\.embed_norm\.weight", target_patterns=r"model.language_model.embed_norm.weight", ), WeightRenaming( source_patterns=r"model\.llm\.embed\.weight", target_patterns=r"model.language_model.embed_tokens.weight", ), WeightRenaming( source_patterns=r"model\.llm\.norm\.weight", target_patterns=r"model.language_model.norm.weight" ), WeightRenaming(source_patterns=r"model\.llm\.unembed\.weight", target_patterns=r"lm_head.weight"), WeightRenaming(source_patterns=r"model\.audio\.", target_patterns=r"model.audio_tower."), WeightRenaming(source_patterns=r"model\.visual", target_patterns=r"model.vision_tower"), # Vision encoder internals (run after the tower namespace renames) WeightRenaming( source_patterns=r"vision_tower.layers.linear_(\d+)", target_patterns=r"vision_tower.encoder_layers.\1.projection", ), WeightRenaming( source_patterns=r"vision_tower.layers.norm_(\d+)", target_patterns=r"vision_tower.encoder_layers.\1.layer_norm", ), # Audio tower internals. These run AFTER the generic `model.audio.` -> `model.audio_tower.` # rename above and substring-match its output. The audio dMel embedding moved from # `audio.encoder` to an `InklingAudioModelEmbeddings` submodule, and `final_norm` was # renamed to `norm`. WeightRenaming( source_patterns=r"audio_tower.encoder.weight", target_patterns=r"audio_tower.embed_audio_tokens.embed_audio_tokens.weight", ), WeightRenaming( source_patterns=r"audio_tower.final_norm.weight", target_patterns=r"audio_tower.norm.weight" ), # MoE and MLP # no Transpose ops here: the TP loader shards the raw tensor but validates the shard # shape on the target param, so dim-permuting conversions break sharded loads cc @cyril WeightConverter( source_patterns="shared_w13_weight", target_patterns=["gate_proj", "up_proj"], operations=[Interleave(dim=1), Chunk(dim=1)], ), WeightRenaming(source_patterns=r"shared_w2_weight", target_patterns=r"down_proj"), WeightConverter( source_patterns="mlp.experts.w13_weight", target_patterns=["mlp.experts.gate_up_proj"], operations=[Interleave(dim=1)], ), WeightRenaming(source_patterns=r"mlp.experts.w2_weight", target_patterns=r"mlp.experts.down_proj"), WeightConverter( source_patterns="mlp.w13_dn.weight", target_patterns=["mlp.gate_proj.weight", "mlp.up_proj.weight"], operations=[Interleave(dim=0), Chunk(dim=0)], ), WeightRenaming(source_patterns=r"mlp.w2_md.weight", target_patterns=r"mlp.down_proj.weight"), WeightRenaming(source_patterns=r"mlp.gate.bias", target_patterns=r"mlp.gate.e_score_correction_bias"), # Attn WeightRenaming(source_patterns=r"attn\.wq_du", target_patterns=r"self_attn.q_proj"), WeightRenaming(source_patterns=r"attn\.wk_dv", target_patterns=r"self_attn.k_proj"), WeightRenaming(source_patterns=r"attn\.wv_dv", target_patterns=r"self_attn.v_proj"), WeightRenaming(source_patterns=r"attn\.wr_du", target_patterns=r"self_attn.r_proj"), WeightRenaming(source_patterns=r"attn\.wo_ud", target_patterns=r"self_attn.o_proj"), WeightRenaming(source_patterns=r"\.attn\.q_norm", target_patterns=r".self_attn.q_norm"), WeightRenaming(source_patterns=r"\.attn\.k_norm", target_patterns=r".self_attn.k_norm"), WeightRenaming(source_patterns=r"\.attn\.k_sconv", target_patterns=r".self_attn.k_sconv.conv1d"), WeightRenaming(source_patterns=r"\.attn\.v_sconv", target_patterns=r".self_attn.v_sconv.conv1d"), WeightRenaming(source_patterns=r"\.attn\.rel_logits_proj", target_patterns=r".self_attn.rel_logits_proj"), WeightRenaming(source_patterns=r"attn_sconv\.weight$", target_patterns=r"attn_sconv.conv1d.weight"), WeightRenaming(source_patterns=r"mlp_sconv\.weight$", target_patterns=r"mlp_sconv.conv1d.weight"), WeightRenaming(source_patterns=r"mlp_norm", target_patterns=r"post_attention_layernorm"), WeightRenaming(source_patterns=r"attn_norm", target_patterns=r"input_layernorm"), ], "GPTNeoXForCausalLM": [ WeightRenaming(source_patterns=r"^embed_out\.", target_patterns="lm_head."), ], "axk2": [ # The A.X-K2 hub checkpoints store the routed experts as individual `experts.{i}` projections # (DeepSeek-V3 layout); the model packs them into the stacked expert tensors. WeightConverter( source_patterns=[ "mlp.experts.*.gate_proj.weight", "mlp.experts.*.up_proj.weight", ], target_patterns="mlp.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="mlp.experts.*.down_proj.weight", target_patterns="mlp.experts.down_proj", operations=[MergeModulelist(dim=0)], ), # The gated norms store their low-rank gate MLP as `W_down` / `W_up`; the model reuses `CLIPMLP` # (`fc1` / `fc2`). Bridge the names on load (and back on save). Patterns are unanchored (no # surrounding dots) so the same rename also normalizes the bare module names in an fp8 checkpoint's # `modules_to_not_convert` (`W_down`/`W_up` -> `mlp.fc1`/`mlp.fc2`); a dot-anchored pattern would # leave those bare names untouched and the gate MLP would be quantized by mistake. WeightRenaming(source_patterns=r"W_down", target_patterns="mlp.fc1"), WeightRenaming(source_patterns=r"W_up", target_patterns="mlp.fc2"), # The released checkpoints fuse the query up-projection and the attention output gate into a # single `q_b_proj` (vLLM layout); the model keeps it fused under the clearer name `q_gate_proj` # and splits the activation in the forward. A plain rename (kept fp8-safe: no weight split, and # the prefix also renames the `weight_scale_inv` companion). WeightRenaming(source_patterns=r"self_attn\.q_b_proj\.", target_patterns="self_attn.q_gate_proj."), ], "gemma4_unified": [ WeightRenaming(source_patterns=r"vision_embedder\.patch_ln1", target_patterns="embed_vision.patch_ln1"), WeightRenaming( source_patterns=r"vision_embedder\.patch_dense", target_patterns="embed_vision.patch_dense" ), WeightRenaming(source_patterns=r"vision_embedder\.patch_ln2", target_patterns="embed_vision.patch_ln2"), WeightRenaming( source_patterns=r"vision_embedder\.pos_embedding", target_patterns="embed_vision.pos_embedding" ), WeightRenaming(source_patterns=r"vision_embedder\.pos_norm", target_patterns="embed_vision.pos_norm"), WeightRenaming( source_patterns=r"embed_vision\.embedding_projection", target_patterns="embed_vision.multimodal_embedder.embedding_projection", ), ], "radio": [ WeightRenaming("radio_model.model.patch_generator.video_embedder", "embeddings.video_patch_projection"), WeightRenaming("radio_model.model.patch_generator.embedder", "embeddings.patch_projection"), WeightRenaming("radio_model.model.patch_generator.pos_embed", "embeddings.position_embedding"), WeightRenaming("radio_model.model.patch_generator.cls_token.token", "embeddings.cls_register_token"), WeightRenaming("radio_model.model.blocks", "encoder.layer"), WeightRenaming("attn.proj", "attention.output.dense"), WeightRenaming("radio_model.input_conditioner", "input_conditioner"), WeightRenaming("radio_model.summary_idxs", "summary_idxs"), WeightConverter( source_patterns="attn.qkv", target_patterns=[ "attention.attention.query", "attention.attention.key", "attention.attention.value", ], operations=[Chunk(dim=0)], ), ], "hrm_text": [ WeightConverter( source_patterns="mlp.gate_up_proj.weight", target_patterns=["mlp.gate_proj.weight", "mlp.up_proj.weight"], operations=[Chunk(dim=0)], ), WeightConverter( source_patterns="attn.gqkv_proj.weight", target_patterns=[ "self_attn.gate_proj.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight", ], operations=[Chunk(dim=0)], ), WeightRenaming(source_patterns=r"\.attn\.o_proj\.", target_patterns=".self_attn.o_proj."), ], "hunyuan_vl": [ WeightRenaming(source_patterns="mlp.dense_h_to_4h", target_patterns="mlp.fc1"), WeightRenaming(source_patterns="mlp.dense_4h_to_h", target_patterns="mlp.fc2"), WeightRenaming( source_patterns=r"^vit\.layers\.(\d+)\.input_layernorm\.", target_patterns=r"vit.layers.\1.layer_norm1.", ), WeightRenaming( source_patterns=r"^vit\.layers\.(\d+)\.post_attention_layernorm\.", target_patterns=r"vit.layers.\1.layer_norm2.", ), WeightRenaming(source_patterns=r"perceive\.proj\.0\.", target_patterns="perceive.proj_conv."), WeightRenaming(source_patterns=r"perceive\.proj\.2\.", target_patterns="perceive.proj_out."), WeightRenaming(source_patterns=r"perceive\.", target_patterns="patch_merger."), WeightRenaming( source_patterns=r"^model(?!\.(language_model|vit|vision_tower))", target_patterns="model.language_model", ), WeightRenaming(source_patterns=r"^model\.vit", target_patterns="model.vision_tower"), WeightRenaming(source_patterns=r"^vit", target_patterns="model.vision_tower"), ], "ViTModel": [ WeightRenaming(r"encoder\.layer\.", "layers."), WeightRenaming("attention.query", "q_proj"), WeightRenaming("attention.key", "k_proj"), WeightRenaming("attention.value", "v_proj"), WeightRenaming("attention.output.dense", "attention.o_proj"), WeightRenaming("intermediate.dense", "mlp.fc1"), WeightRenaming("output.dense", "mlp.fc2"), ], "ViTMSNForImageClassification": [ WeightRenaming(r"^encoder\.", "vit.encoder."), ], "ViTMAEForPreTraining": [ WeightRenaming("attention.query", "q_proj"), WeightRenaming("attention.key", "k_proj"), WeightRenaming("attention.value", "v_proj"), WeightRenaming("attention.output.dense", "attention.o_proj"), WeightRenaming("intermediate.dense", "mlp.fc1"), WeightRenaming("output.dense", "mlp.fc2"), ], "BeitBackbone": [ WeightRenaming(r"^fpn1\.0\.", "fpn.fpn1.conv_transpose1."), WeightRenaming(r"^fpn1\.1\.", "fpn.fpn1.normalization."), WeightRenaming(r"^fpn1\.3\.", "fpn.fpn1.conv_transpose2."), WeightRenaming(r"^fpn2\.0\.", "fpn.fpn2."), WeightRenaming(r"^encoder\.layer\.", "beit.encoder.layer."), WeightRenaming(r"^embeddings\.", "beit.embeddings."), WeightRenaming("attention.query", "q_proj"), WeightRenaming("attention.key", "k_proj"), WeightRenaming("attention.value", "v_proj"), WeightRenaming("attention.output.dense", "attention.o_proj"), WeightRenaming("intermediate.dense", "mlp.fc1"), WeightRenaming("output.dense", "mlp.fc2"), ], "BeitForSemanticSegmentation": [ WeightRenaming(r"(? `.self_attn.` # would otherwise also match the text decoder's `language_model.layers.*.self_attn.*` keys. "step3p5_vision": [ WeightRenaming(source_patterns=r"^conv1\.weight$", target_patterns="embeddings.patch_embedding.weight"), WeightRenaming( source_patterns=r"^positional_embedding$", target_patterns="embeddings.position_embedding.weight", ), WeightRenaming(source_patterns=r"^transformer\.resblocks\.", target_patterns="layers."), WeightRenaming(source_patterns=r"^ln_pre\.", target_patterns="pre_layernorm."), WeightRenaming(source_patterns=r"^vit_downsampler1\.", target_patterns="downsampler1."), WeightRenaming(source_patterns=r"^vit_downsampler2\.", target_patterns="downsampler2."), WeightRenaming(source_patterns=r"\.ls_1\.gamma$", target_patterns=".lambda_1"), WeightRenaming(source_patterns=r"\.ls_2\.gamma$", target_patterns=".lambda_2"), WeightRenaming(source_patterns=r"\.mlp\.c_fc\.", target_patterns=".mlp.fc1."), WeightRenaming(source_patterns=r"\.mlp\.c_proj\.", target_patterns=".mlp.fc2."), WeightRenaming(source_patterns=r"\.attn\.", target_patterns=".self_attn."), WeightRenaming(source_patterns=r"\.ln_1\.", target_patterns=".layernorm_before."), WeightRenaming(source_patterns=r"\.ln_2\.", target_patterns=".layernorm_after."), # Unfuse qkv and apply rope permutation. WeightConverter( source_patterns=r"attn\.in_proj_weight", target_patterns=[ r"attn.q_proj.weight", r"attn.k_proj.weight", r"attn.v_proj.weight", ], operations=[ Chunk(dim=0), PermuteForRope(subconfig_key="vision_config", permute_layer_names=["q_proj", "k_proj"]), ], ), WeightConverter( source_patterns=r"attn\.in_proj_bias", target_patterns=[ r"attn.q_proj.bias", r"attn.k_proj.bias", r"attn.v_proj.bias", ], operations=[ Chunk(dim=0), PermuteForRope(subconfig_key="vision_config", permute_layer_names=["q_proj", "k_proj"]), ], ), ], "colqwen2": [PrefixChange(prefix_to_remove="model", model_prefix="vlm")], "shieldgemma2": [PrefixChange(prefix_to_add="model", model_prefix="model")], "timm_wrapper": [PrefixChange(prefix_to_add="timm_model")], "pi0": [ WeightRenaming(source_patterns=r"state_proj", target_patterns="embed_action_time.state_proj"), WeightRenaming(source_patterns=r"action_in_proj", target_patterns="embed_action_time.action_in_proj"), WeightRenaming( source_patterns=r"action_time_mlp_in", target_patterns="embed_action_time.action_time_mlp_in" ), WeightRenaming( source_patterns=r"action_time_mlp_out", target_patterns="embed_action_time.action_time_mlp_out" ), WeightRenaming(source_patterns=r"^paligemma_with_expert.paligemma.model", target_patterns="model.vlm"), WeightRenaming(source_patterns=r"^paligemma_with_expert.gemma_expert.model", target_patterns="model.dit"), # Weight on the hub have only `lm_head` saved, but PI0 doesn't create any lm-head initialized! WeightRenaming( source_patterns=r"^paligemma_with_expert.gemma_expert.lm_head", target_patterns="model.dit.embed_tokens", ), WeightRenaming( source_patterns=r"^paligemma_with_expert.paligemma.lm_head", target_patterns="model.vlm.language_model.embed_tokens", ), ], "esm": [ WeightRenaming( "encoder.layer.*.attention.self.rotary_embeddings.inv_freq", "rotary_embeddings.inv_freq", ), ], "dinov3_convnext": [WeightRenaming(r"(? we end up with 2 tensors Concatenate(dim=1), # each process has 2 tensors, gate and up, we concat them into gate_up ], # we want the loading to add this shard operation here. Though we can't shard after concats and merge, needs to be first ), WeightConverter( source_patterns=[ ".experts.*.w2.weight", ], target_patterns=".experts.down_proj", # target key gets the list of two tensors operations=[ MergeModulelist( dim=0 ), # each process has two lists of tensors, we cat each list. -> we end up with 2 tensors ], # we want the loading to add this shard operation here. Though we can't shard after concats and merge, needs to be first ), ], "qwen2_moe": [ WeightConverter( source_patterns=[ "mlp.experts.*.gate_proj.weight", "mlp.experts.*.up_proj.weight", ], target_patterns="mlp.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="mlp.experts.*.down_proj.weight", target_patterns="mlp.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "qwen3_vl_moe": [ WeightConverter( source_patterns="mlp.experts.gate_up_proj", target_patterns="mlp.experts.gate_up_proj", operations=[Transpose(1, 2, check_dims=True)], ), WeightConverter( source_patterns="mlp.experts.down_proj", target_patterns="mlp.experts.down_proj", operations=[Transpose(1, 2, check_dims=True)], ), ], "cosmos3_omni": [ # Cosmos3 unified checkpoints store the Reasoner LLM with the old `model.` prefix # stripped off and the ViT under flat `blocks.*` / `merger.*` / `patch_embed.*` / # `pos_embed.*` / `deepstack_merger_list.*`. Re-target both to the nested Qwen3-VL # layout (`model.language_model.*` and `model.visual.*`). Newer checkpoints also # use Diffusers-style attention names; map them back to Qwen3-VL module names. WeightRenaming( source_patterns=r"^(layers\.|embed_tokens\.|norm\.)", target_patterns=r"model.language_model.\1", ), WeightRenaming( source_patterns=r"^(blocks\.|merger\.|patch_embed\.|pos_embed\.|deepstack_merger_list\.)", target_patterns=r"model.visual.\1", ), WeightRenaming(source_patterns=r"\.self_attn\.to_q\.", target_patterns=".self_attn.q_proj."), WeightRenaming(source_patterns=r"\.self_attn\.to_k\.", target_patterns=".self_attn.k_proj."), WeightRenaming(source_patterns=r"\.self_attn\.to_v\.", target_patterns=".self_attn.v_proj."), WeightRenaming(source_patterns=r"\.self_attn\.to_out\.", target_patterns=".self_attn.o_proj."), WeightRenaming(source_patterns=r"\.self_attn\.norm_q\.", target_patterns=".self_attn.q_norm."), WeightRenaming(source_patterns=r"\.self_attn\.norm_k\.", target_patterns=".self_attn.k_norm."), ], "phimoe": [ WeightRenaming(".block_sparse_moe.", ".mlp."), WeightRenaming(".gate.weight", ".router.weight"), WeightConverter( source_patterns=[ ".experts.*.w1.weight", ".experts.*.w3.weight", ], target_patterns=".experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns=".experts.*.w2.weight", target_patterns=".experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "lfm2_moe": [ WeightConverter( source_patterns=[ "feed_forward.experts.*.w1.weight", "feed_forward.experts.*.w3.weight", ], target_patterns="feed_forward.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="feed_forward.experts.*.w2.weight", target_patterns="feed_forward.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "ernie4_5_vl_moe": [ # vision WeightRenaming("vision_model", "vision_tower"), # resampler WeightRenaming("spatial_linear.0", "spatial_linear.fc1"), WeightRenaming("spatial_linear.2", "spatial_linear.fc2"), WeightRenaming("spatial_linear.3", "spatial_linear.ln"), WeightRenaming("temporal_linear.0", "temporal_linear.fc1"), WeightRenaming("temporal_linear.2", "temporal_linear.fc2"), WeightRenaming("temporal_linear.3", "temporal_linear.ln"), # language model WeightRenaming(r"(? None: """ Register a conversion mapping for a model type string or a class name. Class names take priority over `model_type` strings during lookup (see `extract_weight_conversions_for_model`), making it possible to define task-head-specific or class-specific conversions that differ from the shared `model_type` baseline. """ global _checkpoint_conversion_mapping_cache if _checkpoint_conversion_mapping_cache is None: _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping() if model_type_or_class_name in _checkpoint_conversion_mapping_cache and not overwrite: raise ValueError( f"Conversion mapping for '{model_type_or_class_name}' already exists. Pass overwrite=True to replace it." ) _checkpoint_conversion_mapping_cache[model_type_or_class_name] = mapping # Keep track of what was added manually by the user USER_REGISTERED_MAPPINGS.add(model_type_or_class_name) def extract_weight_conversions_for_model( model: PreTrainedModel, ) -> list[WeightTransform] | None: """ Return the registered conversion list for `model`, or `None` if none exists. Looks up by class name first (enables task-head-specific overrides), then falls back to `model.config.model_type`. Transforms are returned unmodified; the caller sets `scope_prefix` on each transform for sub-module isolation. """ class_name = type(model).__name__ model_type = model.config.model_type # Class name takes priority — allows ForXxx-specific overrides conversions = get_checkpoint_conversion_mapping(class_name) if conversions is None and model_type: conversions = get_checkpoint_conversion_mapping(model_type) return conversions def get_model_conversion_mapping( model: PreTrainedModel, key_mapping: dict[str, str] | None = None, hf_quantizer: HfQuantizer | None = None, add_legacy: bool = True, ) -> list[WeightTransform]: """ Collect the ordered list of weight transforms for `model` (used during loading and, when reversed, during saving). Each `PreTrainedModel` sub-module is looked up by class name then `model_type`. Root transforms are applied globally; sub-module transforms have their `scope_prefix` set so they only match keys under that prefix. After any sub-module is processed, both its class name and `model_type` are marked seen to prevent `XForY` / `XModel` pairs from applying the same mapping twice via different lookup paths. """ from .modeling_utils import PreTrainedModel # note: this function is used in PEFT, so changing the API requires coordination weight_conversions = [] # Load models with explicit, user-provided key mapping if key_mapping is not None: weight_conversions = [WeightRenaming(source_patterns=k, target_patterns=v) for k, v in key_mapping.items()] # Maps each identifier (class name or model_type) to the module paths that have # already claimed it. A later module is skipped only when one of those paths is # an ancestor of the current module path — siblings are never ancestors of each # other, so two sibling sub-models with the same model_type both get their own # scoped transforms. A child is an ancestor of everything nested under it, which # prevents a parent's transforms from being duplicated with a scoped copy for the child. seen_identifiers: defaultdict[str, list[str]] = defaultdict(list) for module_name, submodule in model.named_modules(): # Skip if it's not a submodel if not isinstance(submodule, PreTrainedModel): continue class_name = type(submodule).__name__ model_type = submodule.config.model_type # Skip it if it's custom code and it was NOT registered by the user directly: it may have the same `model_type`/ClassName # as a native model inside the library, but it uses custom modeling so it should not share the conversions if ( submodule.is_custom_code() and class_name not in USER_REGISTERED_MAPPINGS and model_type not in USER_REGISTERED_MAPPINGS ): continue # Skip if an ancestor already claimed this class (its unscoped transforms already cover this subtree). if any(seen == "" or module_name.startswith(seen + ".") for seen in seen_identifiers[class_name]): continue # Class name takes priority — a class-specific mapping bypasses the model_type # deduplication check (e.g. LlavaModel nested inside LlavaForConditionalGeneration # must still get its own scoped mapping even after "llava" is marked seen). conversions = get_checkpoint_conversion_mapping(class_name) found_via_class = conversions is not None if not found_via_class: # Same ancestor check as above, but via model_type for modules without a class-specific mapping. if model_type and any( seen == "" or module_name.startswith(seen + ".") for seen in seen_identifiers[model_type] ): continue if model_type is not None: conversions = get_checkpoint_conversion_mapping(model_type) if conversions is None: continue is_root_model = module_name == "" if not is_root_model: # Scope each transform so it only matches keys under this sub-module's prefix - but we still allow to # arbitrary add/remove base_model_prefix to load ForXXX model from BaseModel and the opposite # Note that we need 2 removeprefix calls here, as only one level of nesting would not have the ending dot to module_name scope_prefix = module_name.removeprefix(model.base_model_prefix) scope_prefix = scope_prefix.removeprefix(".") for transform in conversions: transform.scope_prefix = scope_prefix transform.base_model_prefix = model.base_model_prefix weight_conversions.extend(conversions) seen_identifiers[class_name].append(module_name) # Only record model_type when the hit was via model_type. When the hit was via # class name, other sub-modules sharing the same model_type but without a # class-specific mapping (e.g. DetrModel under DetrForSegmentation) must still # be reachable so their base transforms are picked up and scoped. if not found_via_class and model_type: seen_identifiers[model_type].append(module_name) if add_legacy: weight_conversions.extend(get_checkpoint_conversion_mapping("legacy")) # Let the quantizer rewrite / augment the conversion pipeline. This is where the # FP8 dequantizer (when `dequantize=True`) prepends a `Fp8Dequantize` op to # every existing converter so that per-block scales are applied *before* any # expert-merge / concat ops flatten the per-expert structure away. if hf_quantizer is not None: weight_conversions = hf_quantizer.update_weight_conversions(weight_conversions) return weight_conversions