def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str: import json from pathlib import Path import torch from huggingface_hub import get_safetensors_metadata, hf_hub_download from safetensors.torch import save_file # Tiny dimensions keep every fixed kernel contract: head_dim 512, the # 7-HCA/1-MLA compression cycle, 8 output groups, 512-wide MLA latent, # 64 DeepGEMM index heads and the three-layer DSpark draft. The MoE latent # stays 256: the Hopper MXFP4 Marlin path pads this width to a 256 multiple, # so a 128-wide latent would not match the runtime's per-32 scale layout. hidden_size = 128 intermediate_size = 256 moe_intermediate_size = 128 moe_latent_size = 256 num_layers = 15 compress_ratios = [128] * 7 + [-2] + [128] * 6 + [-2] torch.manual_seed(42) folder = Path(save_folder) folder.mkdir(parents=True, exist_ok=True) raw = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text()) config = json.loads(json.dumps(raw)) config.update( hidden_size=hidden_size, intermediate_size=intermediate_size, moe_intermediate_size=moe_intermediate_size, moe_latent_size=moe_latent_size, n_routed_experts=16, num_experts_per_tok=10, num_hidden_layers=num_layers, first_k_dense_replace=1, compress_ratios=compress_ratios, num_attention_heads=4, num_key_value_heads=1, head_dim=512, qk_nope_head_dim=448, q_lora_rank=128, o_lora_rank=128, o_groups=8, hybrid_mla_num_attention_heads=4, hybrid_mla_num_key_value_heads=4, hybrid_mla_q_lora_rank=128, hybrid_mla_kv_lora_rank=512, hybrid_mla_qk_nope_head_dim=192, hybrid_mla_qk_rope_head_dim=64, hybrid_mla_v_head_dim=256, # DeepGEMM's paged MQA logits kernel requires exactly 32 or 64 heads. index_n_heads=64, index_head_dim=128, index_topk=2048, max_position_embeddings=2048, dspark_target_layer_ids=[12, 13, 14], dspark_markov_rank=8, ) config["rope_scaling"] = {**config["rope_scaling"], "original_max_position_embeddings": 2048} bf16, f32, fp8 = "bf16", "f32", "fp8" def tensor_specs(source: dict, fp4: bool) -> dict[str, tuple[tuple[int, ...], str]]: """Serialized name -> (shape, dtype family), mirroring the source schema.""" h = source["hidden_size"] inter = source["intermediate_size"] latent = source["moe_latent_size"] msi = source["moe_intermediate_size"] heads = source["num_attention_heads"] hd = source["head_dim"] mheads = source["hybrid_mla_num_attention_heads"] qkn = source["hybrid_mla_qk_nope_head_dim"] vh = source["hybrid_mla_v_head_dim"] rope = source["hybrid_mla_qk_rope_head_dim"] qr = source["q_lora_rank"] orank = source["o_lora_rank"] groups = source["o_groups"] kvl = source["hybrid_mla_kv_lora_rank"] iheads = source["index_n_heads"] idim = source["index_head_dim"] experts = source["n_routed_experts"] rank = source["dspark_markov_rank"] hc = source["hc_mult"] vocab = source["vocab_size"] stages = len(source["dspark_target_layer_ids"]) gor = groups * orank hc3 = hc * (2 + hc) specs: dict[str, tuple[tuple[int, ...], str]] = {} def add(name, shape, kind): specs[name] = (tuple(shape), kind) def linear(name, out_dim, in_dim): add(f"{name}.weight", (out_dim, in_dim), fp8) add(f"{name}.weight_scale_inv", (-(-out_dim // 128), -(-in_dim // 128)), f32) def expert(name, out_dim, in_dim): if fp4: add(f"{name}.weight", (out_dim, in_dim // 2), "i8") add(f"{name}.weight_scale_inv", (out_dim, in_dim // 32), "e8m0") else: linear(name, out_dim, in_dim) def hyper_connection(prefix): for field, shape in ( ("alpha_pre", (1,)), ("alpha_post", (1,)), ("alpha_res", (1,)), ("bias", (hc3,)), ("mapping_proj.weight", (hc * h, hc3)), ): add(f"{prefix}.{field}", shape, f32) def moe(prefix): add(f"{prefix}.e_score_correction_bias", (experts,), f32) for e in range(experts): expert(f"{prefix}.experts.{e}.w1", msi, latent) expert(f"{prefix}.experts.{e}.w2", latent, msi) expert(f"{prefix}.experts.{e}.w3", msi, latent) linear(f"{prefix}.fc1_latent_proj", latent, h) linear(f"{prefix}.fc2_latent_proj", h, latent) add(f"{prefix}.gate.routed_scaling_factor_param", (experts,), f32) add(f"{prefix}.gate.weight", (experts, h), bf16) add(f"{prefix}.gate.weight_1", (experts, h), bf16) add(f"{prefix}.latent_norm.weight", (latent,), bf16) linear(f"{prefix}.shared_experts.w1", msi, h) linear(f"{prefix}.shared_experts.w2", h, msi) linear(f"{prefix}.shared_experts.w3", msi, h) def hca_attention(prefix, with_compressor=True): add(f"{prefix}.core_attention.attn_sink", (heads,), f32) if with_compressor: add(f"{prefix}.core_attention.compressor.ape", (128, hd), f32) add(f"{prefix}.core_attention.compressor.linear_wgate.weight", (hd, h), bf16) add(f"{prefix}.core_attention.compressor.linear_wkv.weight", (hd, h), bf16) add(f"{prefix}.core_attention.compressor.norm.weight", (hd,), bf16) linear(f"{prefix}.gate_proj", gor, qr) add(f"{prefix}.kv_layernorm.weight", (kvl,), bf16) linear(f"{prefix}.linear_kv_proj", hd, h) # wo_a takes each output group's heads*head_dim/o_groups attention slice. wo_a_in = heads * hd // groups add(f"{prefix}.linear_o_group_proj", (gor, wo_a_in), fp8) add(f"{prefix}.linear_o_group_proj_scale_inv", (-(-gor // 128), -(-wo_a_in // 128)), f32) linear(f"{prefix}.linear_q_down_proj", qr, h) linear(f"{prefix}.linear_q_up_proj", heads * hd, qr) linear(f"{prefix}.o_proj", h, gor) add(f"{prefix}.q_layernorm.weight", (qr,), bf16) add(f"{prefix}.vha_postmix_U", (heads, heads // 4), bf16) add(f"{prefix}.vha_postmix_V", (heads, heads // 4), bf16) def mla_attention(prefix): add(f"{prefix}.core_attention.indexer.k_norm.bias", (idim,), bf16) add(f"{prefix}.core_attention.indexer.k_norm.weight", (idim,), bf16) add(f"{prefix}.core_attention.indexer.weights_proj.weight", (iheads, h), bf16) add(f"{prefix}.core_attention.indexer.wk.weight", (idim, h), bf16) linear(f"{prefix}.core_attention.indexer.wq_b", iheads * idim, qr) add(f"{prefix}.core_attention.softmax_offset", (mheads,), bf16) linear(f"{prefix}.gate_proj", mheads * vh, qr) add(f"{prefix}.kv_a_layernorm.weight", (kvl,), bf16) linear(f"{prefix}.kv_a_proj_with_mqa", kvl + rope, h) linear(f"{prefix}.kv_b_proj", mheads * (qkn + vh), kvl) linear(f"{prefix}.o_proj", h, mheads * vh) add(f"{prefix}.q_a_layernorm.weight", (qr,), bf16) linear(f"{prefix}.q_a_proj", qr, h) linear(f"{prefix}.q_b_proj", mheads * (qkn + rope), qr) add(f"{prefix}.vha_postmix_U", (mheads, mheads // 4), bf16) add(f"{prefix}.vha_postmix_V", (mheads, mheads // 4), bf16) def decoder(prefix, layer_id, ratio, draft=False): add(f"{prefix}.input_layernorm.weight", (h,), bf16) add(f"{prefix}.post_attention_layernorm.weight", (h,), bf16) hyper_connection(f"{prefix}.self_attention_hyper_connection") hyper_connection(f"{prefix}.mlp_hyper_connection") if ratio == -2: mla_attention(f"{prefix}.self_attn") else: # The DSpark draft layers ship no compressed-KV compressor. hca_attention(f"{prefix}.self_attn", with_compressor=not draft) if layer_id < source["first_k_dense_replace"]: linear(f"{prefix}.mlp.gate_proj", inter, h) linear(f"{prefix}.mlp.up_proj", inter, h) linear(f"{prefix}.mlp.down_proj", h, inter) else: moe(f"{prefix}.block_sparse_moe") add("model.embed_tokens.weight", (vocab, h), bf16) add("lm_head.weight", (vocab, h), bf16) add("model.lm_head.multimax_ranges", (4,), bf16) add("model.lm_head.multimax_ts", (4,), bf16) add("model.mhc_contract.hc_head_fn", (hc * h, hc), f32) add("model.mhc_contract.hc_head_base", (hc,), f32) add("model.mhc_contract.hc_head_scale", (1,), f32) add("model.norm.weight", (h,), bf16) for layer_id, ratio in enumerate(source["compress_ratios"]): decoder(f"model.layers.{layer_id}", layer_id, ratio) add("model.mtp.feature_norm.weight", (h,), bf16) linear("model.mtp.feature_projection", h, h * stages) add("model.mtp.markov_head.markov_w1.weight", (rank, vocab), bf16) add("model.mtp.markov_head.markov_w2.weight", (vocab, rank), bf16) add("model.mtp.confidence_head.projection.weight", (1, h + rank), bf16) add("model.mtp.mhc_contract.hc_head_fn", (hc * h, hc), f32) add("model.mtp.mhc_contract.hc_head_base", (hc,), f32) add("model.mtp.mhc_contract.hc_head_scale", (1,), f32) add("model.mtp.norm.weight", (h,), bf16) for stage in range(stages): decoder(f"model.mtp.{stage}", 1, 128, draft=True) return specs # Prove the schema function reproduces the source checkpoint exactly when # given the full source config; only then does shrinking the config shrink it. source_specs = tensor_specs(raw, True) metadata = get_safetensors_metadata(source_model_id, revision=source_revision) headers = { name: (tuple(tensor.shape), tensor.dtype) for file in metadata.files_metadata.values() for name, tensor in file.tensors.items() } dtype_names = {"fp8": "F8_E4M3", "f32": "F32", "bf16": "BF16", "i8": "I8", "e8m0": "F8_E8M0"} assert set(source_specs) == set(headers), "spec names diverge from the source checkpoint" for name, (shape, kind) in source_specs.items(): assert tuple(shape) == headers[name][0], (name, shape, headers[name][0]) assert dtype_names[kind] == headers[name][1], (name, kind, headers[name][1]) specs = tensor_specs(config, True) fp4_bounds = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0]) def materialize() -> dict[str, torch.Tensor]: """Random values quantized with the source's FP8 and MXFP4 recipes.""" tensors: dict[str, torch.Tensor] = {} for name, (shape, kind) in specs.items(): if kind == fp8 and name.endswith("_scale_inv"): continue if kind == fp8: scale_name = name + "_scale_inv" scale_shape = specs[scale_name][0] block_out, block_in = (-(-shape[0] // scale_shape[0]), -(-shape[1] // scale_shape[1])) value = torch.empty(shape, dtype=torch.float32).uniform_(-0.2, 0.2) padded = torch.zeros(scale_shape[0] * block_out, scale_shape[1] * block_in) padded[: shape[0], : shape[1]] = value blocked = padded.view(scale_shape[0], block_out, scale_shape[1], block_in).permute(0, 2, 1, 3) amax = blocked.abs().amax(dim=(2, 3)) tiny = torch.finfo(torch.float32).tiny scale = torch.pow(2.0, torch.round(torch.log2(amax.clamp_min(tiny) / 448.0))) weight = (blocked / scale[..., None, None]).clamp(-448, 448).to(torch.float8_e4m3fn) weight = weight.permute(0, 2, 1, 3).reshape(padded.shape) tensors[name] = weight[: shape[0], : shape[1]].contiguous() tensors[scale_name] = scale elif kind == "i8": scale_name = name + "_scale_inv" scale_shape = specs[scale_name][0] logical = torch.empty((shape[0], shape[1] * 2), dtype=torch.float32).uniform_(-0.2, 0.2) blocks = logical.view(shape[0], scale_shape[1], 32) scale = torch.pow(2.0, torch.round(torch.log2(blocks.abs().amax(-1).clamp_min(1e-30) / 6.0))) normalized = (blocks / scale[..., None]).clamp(-6, 6) code = torch.bucketize(normalized.abs(), fp4_bounds) + normalized.signbit() * 8 code = code.view(shape[0], shape[1] * 2) packed = (code[..., ::2] | (code[..., 1::2] << 4)).to(torch.uint8).view(torch.int8) tensors[name] = packed.contiguous() exponents = (scale.clamp(2.0**-127, 2.0**127).log2() + 127).to(torch.uint8) tensors[scale_name] = exponents.view(torch.float8_e8m0fnu) for name, (shape, kind) in specs.items(): if name in tensors: continue if kind == "e8m0" or (kind == f32 and name.endswith("_scale_inv")): continue if kind == bf16: value = torch.empty(shape, dtype=torch.float32).uniform_(-0.2, 0.2).to(torch.bfloat16) else: value = torch.empty(shape, dtype=torch.float32).uniform_(-0.2, 0.2) if name.endswith("norm.weight"): value.fill_(1.0) elif name.endswith(("attn_sink", "softmax_offset", "e_score_correction_bias")): value.zero_() elif name.endswith("routed_scaling_factor_param"): value.fill_(1.0) tensors[name] = value for name, (shape, kind) in specs.items(): assert name in tensors, name assert tuple(tensors[name].shape) == shape, (name, tensors[name].shape, shape) return tensors class _Block(torch.nn.Module): """Container that prints the checkpoint tensors registered directly on it.""" def extra_repr(self): return "\n".join( f"{name}: {tuple(value.shape)} {str(value.dtype).removeprefix('torch.')}" for name, value in self._parameters.items() ) class Ernie5_5_MoeForCausalLM(torch.nn.Module): """Module hierarchy of the serialized checkpoint (inference-only artifact).""" tensors = materialize() model = Ernie5_5_MoeForCausalLM() # Register in schema order so the printed hierarchy follows the checkpoint. for name in specs: tensor = tensors[name] target = model parts = name.split(".") for part in parts[:-1]: child = target._modules.get(part) if child is None: child = _Block() target.add_module(part, child) target = child target.register_parameter(parts[-1], torch.nn.Parameter(tensor, requires_grad=False)) save_file(model.state_dict(), str(folder / "model.safetensors"), metadata={"format": "pt"}) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n") for name in ( "generation_config.json", "tokenizer.json", "tokenizer_config.json", "tokenization_ernie.py", "encoding_ernie.py", "decoding_ernie.py", "LICENSE", ): (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes()) return str(model) if __name__ == "__main__": create_model( source_model_id="baidu/ERNIE-5.5-Flash-Preview", source_revision="ace1100dcde7bf4eb06add6ae11ce4f43a11ddfe", save_folder="/tmp/ernie-5.5-flash-preview", )