Skip to content

Commit 6617fe2

Browse files
justinchubyCopilot
andauthored
Promote exact scaled-RoPE and MLA GGUF subsets (#640)
## Summary Promotes the maximal exact, fail-closed GGUF subset for this architecture cohort: - Apertus: serialized per-dimension RoPE factors, pre-RoPE Q/K RMSNorm, optional norm/projection biases, xIELU metadata ownership, and packed projection preservation. - MiniCPM: dense split-QKV graph with exact embedding/residual/logit scales, Q/K transforms, LongRoPE, tied/untied output closure, and ordinary expanded KV cache. - MiniCPM3: Q/KV-LoRA MLA with shared RoPE key, asymmetric expanded K/V cache geometry, exact scales, strict dense tensor closure, and packed fused KV-B repacking. - PLM: direct Q, normalized KV-A, fused per-head KV-B, shared interleaved RoPE key, asymmetric expanded cache, tied single-owner output, and ReLU-squared FFN. - Pangu-Embedded: ordinary full-head RoPE, split Q/K/V, mandatory attention-output bias, complete-or-none QKV bias, dense SwiGLU, tied-output ownership, and packed split projections. - Shared safety: rejects quantization-preserving imports when required tensor processors lack exact packed-domain transforms; GPT-2 transpose remains float-only. Serialized RoPE sidecars are accepted only where represented exactly and with floating-point storage. Runtime/OGA promotion remains deferred because representative real-weight GGUF full-logit and deterministic generation parity was not available. ## Residual blockers - Maincoder: Q/K RMSNorm occurs after RoPE, unlike the current generic attention ordering. - Mistral4: DeepSeek-style MLA, conditional dense/MoE loading, and latent-vs-expanded cache ABI. - PLaMo: parallel RMSNorm topology plus converter Q/output projection shuffles. - PLaMo3: fused QKV/SwiGLU, architecture-specific norm offsets, and periodic seven-sliding/one-full iSWA cache scheduling. - MiniCPM routed MoE, MiniCPM3 latent/static/paged state, legacy MiniCPM files missing unambiguous scale metadata, fused Pangu QKV, and tensor-backed/scaled Pangu RoPE remain fail-closed. ## Validation - Initialized all-files lintrunner: clean. - Targeted architecture/config/GGUF suite: 1,503 passed, 1 skipped. - Direct-review regression suite: 32 passed. - Final broad non-integration suite: 8,244 passed, 57 skipped, 12 deselected, 1 subtest passed. - Generated GGUF documentation check: current. - Direct GPT-5.6 Sol medium review found and fixed Pangu `rope_freqs.weight` admission and quantized MiniCPM LongRoPE sidecar acceptance. ## Waivers No runtime/OGA, representative real-weight GGUF prefill/decode full-logit parity, or generation claim is made. Synthetic graph, tensor closure, packed-value transformation, and cached execution coverage is included for promoted routes. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: 1a957193-e630-44b2-bc50-8e506899acc2
1 parent 710b032 commit 6617fe2

21 files changed

Lines changed: 2637 additions & 80 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 19 additions & 16 deletions
Large diffs are not rendered by default.

‎src/mobius/_configs/_base.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,8 @@ class ArchitectureConfig(BaseModelConfig):
457457

458458
attn_qk_norm: bool = False
459459
attn_qk_norm_full: bool = False
460+
attn_q_norm_biases: tuple[bool, ...] | None = None
461+
attn_k_norm_biases: tuple[bool, ...] | None = None
460462
mlp_bias: bool = False
461463
attention_scale: float | None = None
462464
alibi_max_bias: float | None = None
@@ -465,6 +467,13 @@ class ArchitectureConfig(BaseModelConfig):
465467
layer_attention_head_counts: tuple[int, ...] = ()
466468
layer_attention_kv_head_counts: tuple[int, ...] = ()
467469

470+
# Apertus xIELU parameters. GGUF stores these learned per-layer scalars as
471+
# metadata rather than tensors, so they must survive config replacement.
472+
xielu_alpha_p: tuple[float, ...] | None = None
473+
xielu_alpha_n: tuple[float, ...] | None = None
474+
xielu_beta: tuple[float, ...] | None = None
475+
xielu_eps: tuple[float, ...] | None = None
476+
468477
# Encoder-specific config
469478
type_vocab_size: int = 0
470479
encoder_use_token_type_embeddings: bool = False

‎src/mobius/_registry.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@
116116
PhiCausalLMModel,
117117
PhiMoEGGUFCausalLMModel,
118118
Plamo2ForCausalLM,
119+
PLMCausalLMModel,
119120
Qwen2MoECausalLMModel,
120121
Qwen2VLCausalLMModel,
121122
Qwen3CausalLMModel,
@@ -176,6 +177,7 @@
176177
from mobius.models.llava import LLaVAModel
177178
from mobius.models.longcat_flash import LongcatFlashCausalLMModel
178179
from mobius.models.mamba import Mamba2CausalLMModel, MambaCausalLMModel
180+
from mobius.models.minicpm import MiniCPM3CausalLMModel, MiniCPMCausalLMModel
179181
from mobius.models.minicpmv4_6 import MiniCPMV46ForConditionalGeneration
180182
from mobius.models.minimax import MiniMaxCausalLMModel
181183
from mobius.models.mllama import MllamaCausalLMModel
@@ -445,6 +447,8 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
445447
"llama": ModelRegistration(CausalLMModel),
446448
"minicpm": ModelRegistration(CausalLMModel),
447449
"minicpm3": ModelRegistration(CausalLMModel),
450+
"minicpm_gguf": ModelRegistration(MiniCPMCausalLMModel),
451+
"minicpm3_gguf": ModelRegistration(MiniCPM3CausalLMModel),
448452
"ministral": ModelRegistration(CausalLMModel),
449453
"ministral3": ModelRegistration(CausalLMModel),
450454
"mistral": ModelRegistration(CausalLMModel),
@@ -491,6 +495,13 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
491495
test_model_id="pfnet/plamo-2-1b",
492496
family="plamo2",
493497
),
498+
"plm": ModelRegistration(
499+
PLMCausalLMModel,
500+
test_model_id="PLM-Team/PLM-1.8B-Instruct",
501+
test_revision="62d188c7d58843d7013d5b3ffe198db448787860",
502+
family="plm",
503+
),
504+
"pangu_embedded": ModelRegistration(CausalLMModel, family="pangu-embedded"),
494505
"gemma": ModelRegistration(GemmaCausalLMModel),
495506
"gemma2": ModelRegistration(Gemma2CausalLMModel),
496507
"gemma3": ModelRegistration(Gemma3MultiModalModel, task="gemma3-vision-language"),
Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
from __future__ import annotations
5+
6+
import dataclasses
7+
from types import SimpleNamespace
8+
9+
import numpy as np
10+
import pytest
11+
import torch
12+
13+
from mobius._configs import QuantizationConfig
14+
from mobius._registry import registry
15+
from mobius.components import QuantizedLinear, RMSNormBias
16+
from mobius.integrations.gguf._arch_registry import get_arch_spec
17+
from mobius.integrations.gguf._builder import _validate_gguf_model
18+
from mobius.integrations.gguf._config_mapping import gguf_to_config
19+
from mobius.integrations.gguf._tensor_mapping import map_gguf_to_hf_names
20+
from mobius.models.apertus import ApertusCausalLMModel
21+
from mobius.tasks import CausalLMTask
22+
23+
_HIDDEN = 8
24+
_HEADS = 2
25+
_KV_HEADS = 1
26+
_HEAD_DIM = 4
27+
_INTERMEDIATE = 16
28+
_LAYERS = 2
29+
_VOCAB = 32
30+
31+
32+
class _FakeGGUF:
33+
def __init__(
34+
self,
35+
metadata: dict,
36+
tensors: dict[str, np.ndarray],
37+
*,
38+
qtypes: dict[str, int] | None = None,
39+
):
40+
self.architecture = "apertus"
41+
self.metadata = metadata
42+
self._tensors = tensors
43+
self.tensor_names = list(tensors)
44+
self._qtypes = qtypes or {}
45+
46+
def get_metadata(self, key, default=None):
47+
return self.metadata.get(key, default)
48+
49+
def get_tensor(self, name):
50+
return self._tensors[name]
51+
52+
def tensor_items_raw(self):
53+
for name, tensor in self._tensors.items():
54+
yield name, None, SimpleNamespace(value=self._qtypes.get(name, 0)), tensor.shape
55+
56+
57+
def _metadata() -> dict:
58+
return {
59+
"apertus.embedding_length": _HIDDEN,
60+
"apertus.feed_forward_length": _INTERMEDIATE,
61+
"apertus.block_count": _LAYERS,
62+
"apertus.attention.head_count": _HEADS,
63+
"apertus.attention.head_count_kv": _KV_HEADS,
64+
"apertus.attention.layer_norm_rms_epsilon": 1e-5,
65+
"apertus.context_length": 32,
66+
"apertus.rope.freq_base": 12_000_000.0,
67+
"apertus.rope.dimension_count": _HEAD_DIM,
68+
"apertus.vocab_size": _VOCAB,
69+
"apertus.xielu.alpha_p": [-0.2, -0.1],
70+
"apertus.xielu.alpha_n": [-1.0, -0.9],
71+
"apertus.xielu.beta": 0.5,
72+
"apertus.xielu.eps": -1e-6,
73+
}
74+
75+
76+
def _tensors(*, biases: bool = True) -> dict[str, np.ndarray]:
77+
tensors = {
78+
"token_embd.weight": np.zeros((_VOCAB, _HIDDEN), np.float32),
79+
"output_norm.weight": np.ones((_HIDDEN,), np.float32),
80+
"output.weight": np.zeros((_VOCAB, _HIDDEN), np.float32),
81+
"rope_freqs.weight": np.asarray([1.0, 8.0], np.float32),
82+
}
83+
for layer in range(_LAYERS):
84+
prefix = f"blk.{layer}."
85+
tensors.update(
86+
{
87+
prefix + "attn_norm.weight": np.ones((_HIDDEN,), np.float32),
88+
prefix + "attn_q.weight": np.zeros((_HIDDEN, _HIDDEN), np.float32),
89+
prefix + "attn_k.weight": np.zeros((_HEAD_DIM, _HIDDEN), np.float32),
90+
prefix + "attn_v.weight": np.zeros((_HEAD_DIM, _HIDDEN), np.float32),
91+
prefix + "attn_output.weight": np.zeros((_HIDDEN, _HIDDEN), np.float32),
92+
prefix + "attn_q_norm.weight": np.ones((_HEAD_DIM,), np.float32),
93+
prefix + "attn_k_norm.weight": np.ones((_HEAD_DIM,), np.float32),
94+
prefix + "ffn_norm.weight": np.ones((_HIDDEN,), np.float32),
95+
prefix + "ffn_up.weight": np.zeros((_INTERMEDIATE, _HIDDEN), np.float32),
96+
prefix + "ffn_down.weight": np.zeros((_HIDDEN, _INTERMEDIATE), np.float32),
97+
}
98+
)
99+
if biases:
100+
tensors[prefix + "attn_q_norm.bias"] = np.zeros((_HEAD_DIM,), np.float32)
101+
tensors[prefix + "attn_k_norm.bias"] = np.zeros((_HEAD_DIM,), np.float32)
102+
tensors[prefix + "attn_output.bias"] = np.zeros((_HIDDEN,), np.float32)
103+
return tensors
104+
105+
106+
def test_apertus_registry_promotes_exact_float_and_quantized_graph_import() -> None:
107+
spec = get_arch_spec("apertus")
108+
assert spec.is_importable
109+
assert spec.model_type == "apertus"
110+
assert spec.tensor_map_recipe == ("llama", "apertus_extras")
111+
assert spec.config_postprocessor == "apertus"
112+
assert spec.quantized_import.value == "supported"
113+
assert spec.runtime.value == "deferred"
114+
115+
116+
def test_apertus_consumes_serialized_rope_and_xielu_values_exactly() -> None:
117+
model = _FakeGGUF(_metadata(), _tensors())
118+
config = gguf_to_config(model)
119+
120+
assert config.rope_type == "longrope"
121+
assert config.original_max_position_embeddings == config.max_position_embeddings
122+
assert config.rope_scaling == {
123+
"short_factor": [1.0, 8.0],
124+
"long_factor": [1.0, 8.0],
125+
}
126+
assert config.xielu_alpha_p == (-0.2, -0.1)
127+
assert config.xielu_alpha_n == (-1.0, -0.9)
128+
assert config.xielu_beta == (0.5, 0.5)
129+
assert config.xielu_eps == (-1e-6, -1e-6)
130+
assert config.attn_q_norm_biases == (True, True)
131+
assert config.attn_k_norm_biases == (True, True)
132+
assert config.attn_o_bias
133+
134+
135+
def test_apertus_maps_qk_norm_and_output_bias_without_value_transform() -> None:
136+
assert (
137+
map_gguf_to_hf_names("blk.1.attn_q_norm.bias", "apertus")
138+
== "model.layers.1.self_attn.q_norm.bias"
139+
)
140+
assert (
141+
map_gguf_to_hf_names("blk.1.attn_k_norm.weight", "apertus")
142+
== "model.layers.1.self_attn.k_norm.weight"
143+
)
144+
assert (
145+
map_gguf_to_hf_names("blk.1.attn_output.bias", "apertus")
146+
== "model.layers.1.self_attn.o_proj.bias"
147+
)
148+
assert map_gguf_to_hf_names("rope_freqs.weight", "apertus") is None
149+
150+
151+
def test_apertus_rejects_quantized_or_malformed_serialized_rope_factors() -> None:
152+
tensors = _tensors()
153+
with pytest.raises(ValueError, match="F32/F16/BF16"):
154+
gguf_to_config(
155+
_FakeGGUF(
156+
_metadata(),
157+
tensors,
158+
qtypes={"rope_freqs.weight": 2},
159+
)
160+
)
161+
162+
tensors = _tensors()
163+
tensors["rope_freqs.weight"] = np.ones((3,), np.float32)
164+
with pytest.raises(ValueError, match=r"shape \(2,\)"):
165+
gguf_to_config(_FakeGGUF(_metadata(), tensors))
166+
167+
168+
def test_apertus_consumes_complete_longrope_factor_pair_exactly() -> None:
169+
tensors = _tensors()
170+
tensors.pop("rope_freqs.weight")
171+
tensors["rope_factors_short.weight"] = np.asarray([1.0, 2.0], np.float32)
172+
tensors["rope_factors_long.weight"] = np.asarray([4.0, 8.0], np.float32)
173+
metadata = _metadata()
174+
metadata["apertus.rope.scaling.original_context_length"] = 16
175+
176+
config = gguf_to_config(_FakeGGUF(metadata, tensors))
177+
178+
assert config.rope_scaling == {
179+
"short_factor": [1.0, 2.0],
180+
"long_factor": [4.0, 8.0],
181+
}
182+
assert config.original_max_position_embeddings == 16
183+
184+
metadata.pop("apertus.rope.scaling.original_context_length")
185+
with pytest.raises(ValueError, match="original_context_length"):
186+
gguf_to_config(_FakeGGUF(metadata, tensors))
187+
188+
189+
def test_apertus_tensor_contract_and_tiny_graph_close_all_owned_values() -> None:
190+
model = _FakeGGUF(_metadata(), _tensors())
191+
_validate_gguf_model(model, source="synthetic-apertus.gguf")
192+
config = gguf_to_config(model)
193+
module = ApertusCausalLMModel(config)
194+
195+
assert isinstance(module.model.layers[0].self_attn.q_norm, RMSNormBias)
196+
assert isinstance(module.model.layers[0].self_attn.k_norm, RMSNormBias)
197+
package = CausalLMTask().build(module, config)
198+
initializers = package["model"].graph.initializers
199+
for layer in range(_LAYERS):
200+
prefix = f"model.layers.{layer}.mlp.act_fn."
201+
for name in ("alpha_p", "alpha_n", "beta", "eps"):
202+
assert initializers[prefix + name].const_value is not None
203+
assert initializers["model.rotary_emb.cos_cache"].const_value is not None
204+
assert initializers["model.rotary_emb.sin_cache"].const_value is not None
205+
206+
207+
def test_apertus_quantized_mlp_keeps_packed_linear_modules() -> None:
208+
config = gguf_to_config(_FakeGGUF(_metadata(), _tensors()))
209+
config = dataclasses.replace(
210+
config,
211+
quantization=QuantizationConfig(
212+
bits=4,
213+
group_size=16,
214+
quant_method="gguf",
215+
sym=True,
216+
),
217+
)
218+
module = ApertusCausalLMModel(config)
219+
assert isinstance(module.model.layers[0].mlp.up_proj, QuantizedLinear)
220+
assert isinstance(module.model.layers[0].mlp.down_proj, QuantizedLinear)
221+
222+
223+
def test_apertus_tiny_prefill_and_decode_execute() -> None:
224+
from mobius._testing.ort_inference import OnnxModelSession
225+
226+
tensors = _tensors()
227+
rng = np.random.default_rng(0)
228+
for name, tensor in tensors.items():
229+
if tensor.ndim == 2 and "rope_" not in name:
230+
tensors[name] = rng.normal(0.0, 0.02, tensor.shape).astype(np.float32)
231+
config = gguf_to_config(_FakeGGUF(_metadata(), tensors))
232+
module = registry.get("apertus")(config)
233+
package = CausalLMTask().build(module, config)
234+
state_dict = {
235+
mapped: torch.from_numpy(tensor)
236+
for name, tensor in tensors.items()
237+
if (mapped := map_gguf_to_hf_names(name, "apertus")) is not None
238+
}
239+
package.apply_weights(state_dict)
240+
241+
session = OnnxModelSession(package["model"])
242+
try:
243+
prefill = session.run(
244+
{
245+
"input_ids": np.array([[1, 2]], np.int64),
246+
"attention_mask": np.ones((1, 2), np.int64),
247+
"position_ids": np.array([[0, 1]], np.int64),
248+
"past_key_values.0.key": np.empty((1, _KV_HEADS, 0, _HEAD_DIM), np.float32),
249+
"past_key_values.0.value": np.empty((1, _KV_HEADS, 0, _HEAD_DIM), np.float32),
250+
"past_key_values.1.key": np.empty((1, _KV_HEADS, 0, _HEAD_DIM), np.float32),
251+
"past_key_values.1.value": np.empty((1, _KV_HEADS, 0, _HEAD_DIM), np.float32),
252+
}
253+
)
254+
decode = session.run(
255+
{
256+
"input_ids": np.array([[3]], np.int64),
257+
"attention_mask": np.ones((1, 3), np.int64),
258+
"position_ids": np.array([[2]], np.int64),
259+
**{
260+
name.replace("present.", "past_key_values."): value
261+
for name, value in prefill.items()
262+
if name.startswith("present.")
263+
},
264+
}
265+
)
266+
finally:
267+
session.close()
268+
269+
assert prefill["logits"].shape == (1, 2, _VOCAB)
270+
assert decode["logits"].shape == (1, 1, _VOCAB)
271+
assert np.isfinite(prefill["logits"]).all()
272+
assert np.isfinite(decode["logits"]).all()

0 commit comments

Comments
 (0)