Skip to content

Commit 574fc53

Browse files
committed
test(model): validate MiMo V2 conversion and checkpoints on GPU
Signed-off-by: Neil Kale <263453039+kalectory@users.noreply.github.com>
1 parent b244f24 commit 574fc53

1 file changed

Lines changed: 373 additions & 0 deletions

File tree

Lines changed: 373 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,373 @@
1+
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Tiny MiMo-V2.6 text conversion, numerical parity and native checkpoint tests."""
16+
17+
import argparse
18+
import hashlib
19+
import inspect
20+
import json
21+
import logging
22+
import os
23+
import shutil
24+
import subprocess
25+
import sys
26+
from pathlib import Path
27+
28+
import pytest
29+
import torch
30+
import torch.nn.functional as F
31+
from megatron.core import dist_checkpointing
32+
from megatron.core.utils import unwrap_model
33+
from safetensors.torch import load_file, save_file
34+
from transformers import AutoConfig, AutoModelForCausalLM
35+
36+
from megatron.bridge import AutoBridge
37+
from megatron.bridge.peft.lora import LoRA
38+
39+
40+
logger = logging.getLogger(__name__)
41+
HF_MODEL = "XiaomiMiMo/MiMo-V2.6-Flash-RL"
42+
HF_REVISION = "5711b268169967567844e1e560e8a3966da959b1"
43+
44+
45+
def checkpoint_weights(model, checkpoint_tp_size=4):
46+
"""Encode published TP-chunked QKV rows independently of Bridge's mappings."""
47+
result = {}
48+
config = model.config
49+
for name, tensor in model.state_dict().items():
50+
if name.endswith(".self_attn.qkv_proj.weight"):
51+
layer = int(name.split(".")[2])
52+
groups = (
53+
config.swa_num_key_value_heads if config.hybrid_layer_pattern[layer] else config.num_key_value_heads
54+
)
55+
sizes = (
56+
config.num_attention_heads * config.head_dim,
57+
groups * config.head_dim,
58+
groups * config.v_head_dim,
59+
)
60+
projections = tensor.split(sizes)
61+
tensor = torch.cat(
62+
[part for shard in zip(*(p.chunk(checkpoint_tp_size) for p in projections)) for part in shard]
63+
)
64+
result[name] = tensor.detach().contiguous().cpu()
65+
return result
66+
67+
68+
def create_tiny_checkpoint(checkpoint: Path, hf_source: str, dtype: torch.dtype) -> dict:
69+
"""Use unchanged official HF classes; keep global/SWA and dense/MoE layers."""
70+
config = AutoConfig.from_pretrained(hf_source, revision=HF_REVISION, trust_remote_code=True)
71+
overrides = dict(
72+
num_hidden_layers=2,
73+
hidden_size=128,
74+
intermediate_size=256,
75+
num_attention_heads=8,
76+
swa_num_attention_heads=8,
77+
num_key_value_heads=4,
78+
swa_num_key_value_heads=8,
79+
head_dim=192,
80+
swa_head_dim=192,
81+
v_head_dim=128,
82+
swa_v_head_dim=128,
83+
vocab_size=128,
84+
max_position_embeddings=256,
85+
n_routed_experts=4,
86+
num_experts_per_tok=2,
87+
moe_intermediate_size=128,
88+
hybrid_layer_pattern=[0, 1],
89+
moe_layer_freq=[0, 1],
90+
vision_config={},
91+
audio_config={},
92+
pad_token_id=0,
93+
bos_token_id=1,
94+
eos_token_id=2,
95+
use_cache=False,
96+
)
97+
for name, value in overrides.items():
98+
if not hasattr(config, name):
99+
raise ValueError(f"Official MiMo config has no field {name}")
100+
setattr(config, name, value)
101+
del config.quantization_config
102+
config.dtype = dtype
103+
config._attn_implementation = "eager"
104+
torch.manual_seed(41)
105+
reference = (
106+
AutoModelForCausalLM.from_config(config, trust_remote_code=True, code_revision=HF_REVISION).to(dtype).eval()
107+
)
108+
# These custom parameters use torch.empty in the official implementation.
109+
with torch.no_grad():
110+
for name, parameter in reference.named_parameters():
111+
if name.endswith("mlp.gate.weight"):
112+
parameter.normal_(0, 0.02)
113+
elif name.endswith("e_score_correction_bias"):
114+
parameter.copy_(torch.linspace(-0.01, 0.01, parameter.numel()).reshape_as(parameter))
115+
elif name.endswith("attention_sink_bias"):
116+
parameter.copy_(torch.linspace(-0.2, 0.2, parameter.numel()).reshape_as(parameter))
117+
assert all(torch.isfinite(p).all() for p in reference.parameters())
118+
canonical, raw = checkpoint / "hf", checkpoint / "raw"
119+
canonical.mkdir(parents=True)
120+
raw.mkdir()
121+
reference.save_pretrained(canonical, safe_serialization=True)
122+
# Preserve official remote code byte-for-byte in both local fixtures.
123+
source_directory = Path(inspect.getfile(type(reference))).parent
124+
code_hashes = {}
125+
for name in ("configuration_mimo_v2.py", "modeling_mimo_v2.py"):
126+
source = source_directory / name
127+
code_hashes[name] = hashlib.sha256(source.read_bytes()).hexdigest()
128+
for destination in (canonical, raw):
129+
shutil.copyfile(source, destination / name)
130+
config.save_pretrained(raw)
131+
weights = checkpoint_weights(reference)
132+
save_file(weights, raw / "model.safetensors")
133+
(raw / "model.safetensors.index.json").write_text(
134+
json.dumps({"metadata": {"tp_size": 4}, "weight_map": {name: "model.safetensors" for name in weights}})
135+
)
136+
receipt = dict(
137+
hf_model=HF_MODEL,
138+
revision=HF_REVISION,
139+
code_sha256=code_hashes,
140+
parameters=sum(p.numel() for p in reference.parameters()),
141+
tensors=len(weights),
142+
dtype=str(dtype),
143+
checkpoint_tp_size=4,
144+
config_overrides=overrides,
145+
reference_attention="official eager forward with explicit full/sliding attention-mask dictionary",
146+
)
147+
(checkpoint / "fixture.json").write_text(json.dumps(receipt, indent=2) + "\n")
148+
return receipt
149+
150+
151+
def reference_masks(tokens, dtype):
152+
"""Supported HF mask dictionary: causal and 128-token windows including self."""
153+
positions = torch.arange(tokens.shape[1], device=tokens.device)
154+
future = positions[None, :] > positions[:, None]
155+
outside_window = positions[None, :] < positions[:, None] - 127
156+
return {
157+
name: torch.zeros(1, 1, tokens.shape[1], tokens.shape[1], dtype=dtype, device=tokens.device).masked_fill(
158+
blocked, torch.finfo(dtype).min
159+
)
160+
for name, blocked in (("full_attention", future), ("sliding_window_attention", future | outside_window))
161+
}
162+
163+
164+
def compare_logits(actual, expected):
165+
"""Use the repository's cosine/next-token gate; absolute errors are diagnostics."""
166+
assert torch.isfinite(actual).all() and torch.isfinite(expected).all()
167+
difference = (actual.float() - expected.float()).abs()
168+
cosine = F.cosine_similarity(actual.float().flatten(), expected.float().flatten(), dim=0).item()
169+
next_token_matches = torch.equal(actual[:, -1].argmax(-1), expected[:, -1].argmax(-1))
170+
assert cosine >= 0.99, cosine
171+
assert next_token_matches
172+
return dict(
173+
cosine=cosine,
174+
max_abs=difference.max().item(),
175+
mean_abs=difference.mean().item(),
176+
next_token_matches=next_token_matches,
177+
all_position_argmax_match_fraction=(actual.argmax(-1) == expected.argmax(-1)).float().mean().item(),
178+
)
179+
180+
181+
def _exact_weights(actual, expected):
182+
assert actual.keys() == expected.keys()
183+
for name in expected:
184+
# Native router and expert-bias storage is FP32, even for BF16 HF weights.
185+
torch.testing.assert_close(actual[name].float(), expected[name].float(), atol=0, rtol=0)
186+
return dict(
187+
tensors=len(expected),
188+
dtype_differences={
189+
name: [str(expected[name].dtype), str(actual[name].dtype)]
190+
for name in expected
191+
if actual[name].dtype != expected[name].dtype
192+
},
193+
)
194+
195+
196+
def run_parity(checkpoint: Path, tp: int, ep: int) -> None:
197+
"""Run one bounded distributed layout with the prepared local tiny checkpoint."""
198+
from megatron.bridge.training.checkpointing import apply_peft_adapter_filter_to_state_dict
199+
200+
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
201+
torch.distributed.init_process_group("nccl")
202+
torch.backends.cuda.matmul.allow_tf32 = False
203+
raw = checkpoint / "raw"
204+
reference = AutoModelForCausalLM.from_pretrained(
205+
checkpoint / "hf", trust_remote_code=True, attn_implementation="eager", dtype="auto"
206+
)
207+
dtype = next(reference.parameters()).dtype
208+
original = load_file(raw / "model.safetensors")
209+
bridge = AutoBridge.from_hf_pretrained(raw, trust_remote_code=True, torch_dtype=dtype)
210+
provider = bridge.to_megatron_provider()
211+
provider.tensor_model_parallel_size = tp
212+
provider.expert_model_parallel_size = ep
213+
provider.expert_tensor_parallel_size = 1
214+
provider.sequence_parallel = tp > 1
215+
provider.parallel_output = False
216+
provider.attention_backend = "fused" if dtype == torch.bfloat16 else "unfused"
217+
provider.params_dtype = dtype
218+
provider.autocast_dtype = dtype
219+
provider.bf16 = dtype == torch.bfloat16
220+
provider.gradient_accumulation_fusion = False
221+
provider.finalize()
222+
models = provider.provide_distributed_model(wrap_with_ddp=False)
223+
model = models[0]
224+
core_model = unwrap_model(models)[0]
225+
model.eval()
226+
metrics = dict(tp=tp, ep=ep, dtype=str(dtype), sequence_length=160, batch_size=2)
227+
exported = dict(bridge.export_hf_weights(models, cpu=True))
228+
if torch.distributed.get_rank() == 0:
229+
metrics["roundtrip"] = _exact_weights(exported, original)
230+
logger.info("Exact checkpoint roundtrip: %s", metrics["roundtrip"])
231+
reference = reference.cuda().eval() # Official noaux_tc rejects training mode; autograd stays enabled.
232+
torch.manual_seed(42)
233+
tokens = torch.randint(0, 128, (2, 160), device="cuda")
234+
positions = torch.arange(tokens.shape[1], device="cuda").expand_as(tokens)
235+
masks = reference_masks(tokens, dtype)
236+
actual = model(tokens, positions, None)
237+
expected = reference(tokens, attention_mask=masks, use_cache=False).logits
238+
metrics["base_logits"] = compare_logits(actual, expected)
239+
logger.info("Base logits: %s", metrics["base_logits"])
240+
native_loss = F.cross_entropy(actual[:, :-1].float().flatten(0, 1), tokens[:, 1:].flatten())
241+
hf_loss = F.cross_entropy(expected[:, :-1].float().flatten(0, 1), tokens[:, 1:].flatten())
242+
native_loss.backward()
243+
hf_loss.backward()
244+
grads = [p.grad for p in model.parameters() if p.grad is not None]
245+
assert grads and all(torch.isfinite(grad).all() for grad in grads)
246+
metrics["backward"] = dict(
247+
native_loss=native_loss.item(), hf_loss=hf_loss.item(), finite_gradient_tensors=len(grads)
248+
)
249+
if tp == ep == 1:
250+
metrics["backward"]["gradient_cosines"] = {}
251+
for name, native_param, hf_param in (
252+
("embedding", core_model.embedding.word_embeddings.weight, reference.model.embed_tokens.weight),
253+
("output", core_model.output_layer.weight, reference.lm_head.weight),
254+
("router", core_model.decoder.layers[1].mlp.router.weight, reference.model.layers[1].mlp.gate.weight),
255+
):
256+
assert native_param.grad is not None and hf_param.grad is not None
257+
cosine = F.cosine_similarity(
258+
native_param.grad.float().flatten(), hf_param.grad.float().flatten(), dim=0
259+
).item()
260+
assert cosine >= 0.99, (name, cosine)
261+
metrics["backward"]["gradient_cosines"][name] = cosine
262+
model.zero_grad(set_to_none=True)
263+
reference.zero_grad(set_to_none=True)
264+
native_checkpoint = checkpoint / f"native_tp{tp}_ep{ep}"
265+
native_checkpoint.mkdir(exist_ok=True)
266+
torch.distributed.barrier()
267+
dist_checkpointing.save({"model": model.sharded_state_dict()}, str(native_checkpoint))
268+
with torch.no_grad():
269+
for parameter in model.parameters():
270+
parameter.zero_()
271+
restored = dist_checkpointing.load({"model": model.sharded_state_dict()}, str(native_checkpoint))
272+
model.load_state_dict(restored["model"])
273+
restored_export = dict(bridge.export_hf_weights(models, cpu=True))
274+
if torch.distributed.get_rank() == 0:
275+
metrics["base_checkpoint_restore"] = _exact_weights(restored_export, original)
276+
logger.info("Base backward and checkpoint restore: %s", metrics["backward"])
277+
278+
lora = LoRA(target_modules=["linear_qkv", "linear_proj"], dim=4, alpha=4, lora_dtype=dtype)
279+
models = lora(models, training=True)
280+
lora.set_params_to_save(models)
281+
model = models[0]
282+
model.eval()
283+
with torch.no_grad():
284+
for name, parameter in model.named_parameters():
285+
if ".adapter.linear_out.weight" in name:
286+
values = (torch.arange(parameter.numel(), device=parameter.device) % 31 - 15) * 1e-4
287+
parameter.copy_(values.reshape_as(parameter))
288+
adapters = dict(bridge.export_adapter_weights(models, cpu=True, show_progress=False))
289+
expected_names = {
290+
f"model.layers.{layer}.self_attn.{projection}.lora_{side}.weight"
291+
for layer in range(2)
292+
for projection in ("qkv_proj", "o_proj")
293+
for side in ("A", "B")
294+
}
295+
assert adapters.keys() == expected_names
296+
assert all(weight.count_nonzero() for name, weight in adapters.items() if ".lora_B." in name)
297+
with torch.no_grad():
298+
for layer in range(2):
299+
for projection in ("qkv_proj", "o_proj"):
300+
prefix = f"model.layers.{layer}.self_attn.{projection}"
301+
delta = adapters[f"{prefix}.lora_B.weight"].float() @ adapters[f"{prefix}.lora_A.weight"].float()
302+
weight = getattr(reference.model.layers[layer].self_attn, projection).weight
303+
weight.copy_((weight.float() + delta.to(weight.device)).to(weight.dtype))
304+
updated = models[0](tokens, positions, None)
305+
expected_updated = reference(tokens, attention_mask=masks, use_cache=False).logits
306+
metrics["lora_logits"] = compare_logits(updated, expected_updated)
307+
assert not torch.equal(updated, actual)
308+
merged = dict(bridge.export_hf_weights(models, cpu=True))
309+
if torch.distributed.get_rank() == 0:
310+
metrics["merged_lora_export"] = _exact_weights(merged, checkpoint_weights(reference))
311+
adapter_checkpoint = checkpoint / f"adapter_tp{tp}_ep{ep}"
312+
adapter_checkpoint.mkdir(exist_ok=True)
313+
torch.distributed.barrier()
314+
state = apply_peft_adapter_filter_to_state_dict({"model": model.sharded_state_dict()}, lora)
315+
dist_checkpointing.save(state, str(adapter_checkpoint))
316+
with torch.no_grad():
317+
for parameter in model.parameters():
318+
if parameter.requires_grad:
319+
parameter.zero_()
320+
state = apply_peft_adapter_filter_to_state_dict({"model": model.sharded_state_dict()}, lora)
321+
restored = dist_checkpointing.load(state, str(adapter_checkpoint))
322+
_, unexpected = unwrap_model(models)[0].load_state_dict(restored["model"], strict=False)
323+
assert not unexpected
324+
restored_adapters = dict(bridge.export_adapter_weights(models, cpu=True, show_progress=False))
325+
metrics["adapter_checkpoint_restore"] = _exact_weights(restored_adapters, adapters)
326+
with torch.no_grad():
327+
metrics["adapter_restore_logits"] = compare_logits(models[0](tokens, positions, None), updated)
328+
if torch.distributed.get_rank() == 0:
329+
(checkpoint / f"results_tp{tp}_ep{ep}.json").write_text(json.dumps(metrics, indent=2) + "\n")
330+
logger.info("MiMo-V2 parity passed: %s", metrics)
331+
torch.distributed.destroy_process_group()
332+
333+
334+
@pytest.mark.run_only_on("GPU")
335+
@pytest.mark.parametrize("tp,ep", [(1, 1), (2, 1), (1, 2)])
336+
def test_mimo_v2_text_conversion(tmp_path, tp, ep):
337+
source = os.environ.get("MIMO_V2_HF_SOURCE", HF_MODEL)
338+
checkpoint = tmp_path / "mimo_v2"
339+
create_tiny_checkpoint(checkpoint, source, torch.bfloat16)
340+
subprocess.run(
341+
[
342+
sys.executable,
343+
"-m",
344+
"torch.distributed.run",
345+
"--standalone",
346+
f"--nproc_per_node={max(tp, ep)}",
347+
__file__,
348+
"--checkpoint",
349+
str(checkpoint),
350+
"--tp",
351+
str(tp),
352+
"--ep",
353+
str(ep),
354+
],
355+
check=True,
356+
timeout=600,
357+
)
358+
359+
360+
if __name__ == "__main__":
361+
logging.basicConfig(level=logging.INFO)
362+
parser = argparse.ArgumentParser()
363+
parser.add_argument("--checkpoint", type=Path, required=True)
364+
parser.add_argument("--create-fixture", action="store_true")
365+
parser.add_argument("--hf-source", default=HF_MODEL)
366+
parser.add_argument("--dtype", choices=["bfloat16", "float32"], default="bfloat16")
367+
parser.add_argument("--tp", type=int, default=1)
368+
parser.add_argument("--ep", type=int, default=1)
369+
args = parser.parse_args()
370+
if args.create_fixture:
371+
logger.info("Fixture: %s", create_tiny_checkpoint(args.checkpoint, args.hf_source, getattr(torch, args.dtype)))
372+
else:
373+
run_parity(args.checkpoint, args.tp, args.ep)

0 commit comments

Comments
 (0)