ergo-mxfp4 / .meta /create_model.py
yujiepan's picture
Upload folder using huggingface_hub
66d2756 verified
Raw History Blame Contribute Delete
11.2 kB
def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str:
import json
import re
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download
from safetensors.torch import save_file
from transformers import ErgoConfig, ErgoForCausalLM, set_seed
folder = Path(save_folder)
folder.mkdir(parents=True, exist_ok=True)
# The tiny geometry: 8 Q / 4 KV heads (source 2:1 GQA), one dense block,
# three MoE blocks and one global layer. hidden/expert width 128 is the
# MXFP4 floor shared by the MX siblings; head_dim 64 is the smallest head
# the fused qk-norm-rope kernel supports, so the Q width (512)
# intentionally exceeds hidden_size.
hidden_size = 128
num_attention_heads = 8
num_key_value_heads = 4
head_dim = 64
num_hidden_layers = 4
num_dense_blocks = 1
first_dense_intermediate_size = 512
moe_intermediate_size = 128
shared_intermediate_size = 128
num_experts = 256
num_experts_per_tok = 8
config = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text())
config.update(
hidden_size=hidden_size,
num_hidden_layers=num_hidden_layers,
num_attention_heads=num_attention_heads,
num_key_value_heads=num_key_value_heads,
head_dim=head_dim,
intermediate_size=first_dense_intermediate_size,
first_dense_intermediate_size=first_dense_intermediate_size,
num_dense_blocks=num_dense_blocks,
moe_intermediate_size=moe_intermediate_size,
shared_intermediate_size=shared_intermediate_size,
num_experts=num_experts,
num_experts_per_tok=num_experts_per_tok,
)
# Keep the release's declared precision: MXFP4 serialized expert stacks.
expected_quantization = {"quant_method": "mxfp4"}
if config.get("quantization_config") != expected_quantization:
raise ValueError(f"Unexpected source quantization_config: {config.get('quantization_config')}")
# Transformers' ErgoConfig takes the HF-style name for the sliding window
# and does not declare the checkpoint-only fields (head_dim, model_flavor,
# moe_latent_size, source_tp_size, moe_routing_method, ...). Build the
# construction config from declared fields only; the saved document above
# keeps every source field.
construction = {
"vocab_size": config["vocab_size"],
"hidden_size": hidden_size,
"num_hidden_layers": num_hidden_layers,
"num_attention_heads": num_attention_heads,
"num_key_value_heads": num_key_value_heads,
# Ergo's Transformers implementation derives head_dim as
# hidden_size // num_attention_heads; the checkpoint-only head_dim
# field must be injected for this shrunk, non-divisible geometry.
"head_dim": head_dim,
"first_dense_intermediate_size": first_dense_intermediate_size,
"num_dense_blocks": num_dense_blocks,
"moe_intermediate_size": moe_intermediate_size,
"shared_intermediate_size": shared_intermediate_size,
"num_experts": num_experts,
"num_experts_per_tok": num_experts_per_tok,
"moe_routed_scaling_factor": config["moe_routed_scaling_factor"],
"max_position_embeddings": config["max_position_embeddings"],
"rms_norm_eps": config["rms_norm_eps"],
"sliding_window": config["local_attention_window"],
"global_attention_every_n_layers": config["global_attention_every_n_layers"],
"pad_token_id": config["pad_token_id"],
"eos_token_id": config["eos_token_id"],
"bos_token_id": config["bos_token_id"],
"tie_word_embeddings": config["tie_word_embeddings"],
"rope_theta": config["rope_theta"],
}
set_seed(42)
previous_dtype = torch.get_default_dtype()
try:
torch.set_default_dtype(torch.bfloat16)
model = ErgoForCausalLM(ErgoConfig(**construction))
finally:
torch.set_default_dtype(previous_dtype)
# Transformers 5.25's ErgoAttention derives head_dim as
# hidden_size // num_attention_heads and ignores config.head_dim. Rebuild
# the attention projections for the deliberately decoupled Q width; the
# released checkpoint and vLLM both use config.head_dim directly.
if head_dim != hidden_size // num_attention_heads:
for layer in model.model.layers:
attention = layer.self_attn
attention.head_dim = head_dim
attention.scaling = head_dim**-0.5
attention.qkv_proj = torch.nn.Linear(
hidden_size,
(num_attention_heads + 2 * num_key_value_heads) * head_dim,
bias=False,
dtype=torch.bfloat16,
)
attention.o_proj = torch.nn.Linear(
num_attention_heads * head_dim,
hidden_size,
bias=False,
dtype=torch.bfloat16,
)
attention.q_norm = type(attention.q_norm)(head_dim, eps=config["rms_norm_eps"])
attention.k_norm = type(attention.k_norm)(head_dim, eps=config["rms_norm_eps"])
std = config.get("initializer_range", 0.02)
torch.nn.init.normal_(attention.qkv_proj.weight, mean=0.0, std=std)
torch.nn.init.normal_(attention.o_proj.weight, mean=0.0, std=std)
# Reverse Transformers' module tree onto the released checkpoint names.
def checkpoint_name(name):
if name == "lm_head.weight":
return "output.weight"
name = name.removeprefix("model.")
if name == "embed_tokens.weight":
return "tok_embeddings.weight"
match = re.fullmatch(r"layers\.(\d+)\.(.+)", name)
if match is None:
return name
index, rest = match.groups()
for hf_suffix, source_suffix in (
("self_attn.qkv_proj.weight", "attention.wqkv.weight"),
("self_attn.o_proj.weight", "attention.wo.weight"),
("self_attn.q_norm.weight", "attention.q_norm.weight"),
("self_attn.k_norm.weight", "attention.k_norm.weight"),
("input_layernorm.weight", "attention_norm.weight"),
("post_attention_layernorm.weight", "post_attention_norm.weight"),
("pre_feedforward_layernorm.weight", "ffn_norm.weight"),
("post_feedforward_layernorm.weight", "post_ffn_norm.weight"),
("attention_residual_gate.weight", "post_attention_residual.scale"),
("feedforward_residual_gate.weight", "post_ffn_residual.scale"),
("mlp.up_proj.weight", "feed_forward.up.weight"),
("mlp.down_proj.weight", "feed_forward.down.weight"),
("mlp.experts.up_proj", "feed_forward.up_proj"),
("mlp.experts.down_proj", "feed_forward.down_proj"),
("mlp.experts.post_expert_norm.weight", "feed_forward.expert_output_norm.scale"),
("mlp.gate.linear.weight", "feed_forward.gate_kernel"),
("mlp.gate.e_score_correction_bias", "feed_forward.router_bias"),
("mlp.shared_experts.up_proj.weight", "feed_forward.shared_up_proj"),
("mlp.shared_experts.down_proj.weight", "feed_forward.shared_down_proj"),
("mlp.shared_experts.norm.weight", "feed_forward.shared_expert_output_norm.scale"),
):
if rest == hf_suffix:
rest = source_suffix
break
else:
raise ValueError(f"Unmapped tensor: {name}")
return f"layers.{index}.{rest}"
def source_dtype(name):
# Every norm weight, residual gate and expert-norm scale is stored FP32;
# embeddings are FP32; everything else is BF16 before expert quantization.
if name.endswith(("tok_embeddings.weight", "norm.weight", ".scale", "router_bias")):
return torch.float32
return torch.bfloat16
state = {}
for hf_name, value in sorted(model.state_dict().items()):
name = checkpoint_name(hf_name)
value = value.detach().cpu()
if name.endswith("feed_forward.gate_kernel"):
value = value.t()
elif name.endswith(("feed_forward.shared_up_proj", "feed_forward.shared_down_proj")):
# The release stores both shared projections input-first.
value = value.t()
state[name] = value.to(source_dtype(name)).contiguous()
def quantize_mxfp4(weight):
"""Packed E2M1 with one UE8M0 scale per 32 input elements, input last."""
*lead, k = weight.shape
blocks = weight.float().reshape(-1, k // 32, 32)
mantissa, exponent = torch.frexp(blocks.abs().amax(dim=-1).clamp_min(1e-30) / 6.0)
# frexp(2^e) returns mantissa 0.5 with exponent e + 1; decrementing
# makes the scale the ceiling power of two of amax / 6.
exponent = torch.where(mantissa == 0.5, exponent - 1, exponent)
magnitude = torch.ldexp(blocks.abs(), -exponent.unsqueeze(-1))
# Indices into E2M1 magnitudes {0, 0.5, 1, 1.5, 2, 3, 4, 6}; ties go to
# the even mantissa (0.75 -> 1.0, 1.25 -> 1.0, 2.5 -> 2.0, 5.0 -> 4.0).
code = (
(magnitude > 0.25).to(torch.uint8)
+ (magnitude >= 0.75).to(torch.uint8)
+ (magnitude > 1.25).to(torch.uint8)
+ (magnitude >= 1.75).to(torch.uint8)
+ (magnitude > 2.5).to(torch.uint8)
+ (magnitude >= 3.5).to(torch.uint8)
+ (magnitude > 5.0).to(torch.uint8)
)
# A value that rounds to zero is stored as +0, as in the source.
code = code | (((blocks < 0) & (code != 0)).to(torch.uint8) << 3)
nibbles = code.reshape(-1, k // 2, 2)
packed = (nibbles[..., 0] | (nibbles[..., 1] << 4)).reshape(*lead, k // 2)
return packed, (exponent + 127).to(torch.uint8).reshape(*lead, k // 32)
for layer in range(num_dense_blocks, num_hidden_layers):
for projection in ("up_proj", "down_proj"):
key = f"layers.{layer}.feed_forward.{projection}"
# BF16 stacks are [experts, in, out]; packed weights and scales
# store the quantized input dimension last.
weight = state.pop(key).transpose(1, 2).contiguous()
quantized, scale = quantize_mxfp4(weight)
state[key] = quantized
state[key + "_scale"] = scale
if len(state) != 75:
raise ValueError(f"Unexpected Ergo tensor count: {len(state)}")
save_file(state, str(folder / "model.safetensors"), metadata={"format": "pt"})
(folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
for name in (
"tokenizer.json",
"tokenizer.model",
"tokenizer_config.json",
"chat_template.jinja",
"generation_config.json",
"LICENSE.md",
):
(folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes())
print(model)
return str(model)
if __name__ == "__main__":
create_model(
source_model_id="Amazon-FMR/Ergo",
source_revision="368c86648a928e769539f3f720a42aa85450d1eb",
save_folder="/tmp/ergo-mxfp4",
)