Skip to content

Commit ba64bfe

Browse files
justinchubyCopilot
andauthored
Support Qwen3.8 compressed NVFP4 checkpoints (#654)
## Summary - parse compressed-tensors 0.17.2 mixed FP8/NVFP4 metadata before graph construction, preserving ordered targets, ignores, and the last-eight-layer FP8 override - stream each shard tensor into exact dense reconstruction with strict dtype/shape/qparam guards, then retain lazy transpose/concat folding - keep FP8 KV cache disabled by default and require a complete scale map plus an emitted EP-supported GQA FP8 ABI when explicitly enabled - add independent packed-code ORT parity, Qwen3.5 VLM package loading, and immutable official/quantized checkpoint evidence ## Capability - **Native preserved FP8/NVFP4 weights:** none; current available ORT dense operator schemas do not exactly match this checkpoint ABI - **Fallback:** FP8 weights reconstruct as `q * channel_scale`; NVFP4 weights reconstruct as `E2M1(code) * E4M3(block_scale) / stored_global_scale`, emitted as dense floating-point weights. The package report and warning explicitly state that output is no longer NVFP4 and dynamic activation quantization is not represented. - **KV cache:** float by default. FP8 is opt-in only through the existing EP-gated GQA feature with every checkpoint `k_scale`/`v_scale` supplied. ## Immutable evidence - official base: `Qwen/Qwen3.8-27B@1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0` - quantized derivative: `unsloth/Qwen3.8-27B-NVFP4@9e3d73c76eddb75f795cc24ccfbc5affe41c66bd` - derivative index total: 23,417,592,488 bytes; representative safetensors header offsets/dtypes/shapes and LFS identity are pinned in tests ## Validation - `8371 passed, 57 skipped, 12 deselected` in the broad serial suite - targeted compressed-tensors, Qwen3.5, adjacent quantization, FP8 KV-cache, and ORT numerical tests pass - `lintrunner f --output oneline --all-files` and `lintrunner -a` pass - three GPT-5.6 Sol medium review rounds completed; all findings fixed ## Waivers - Full-checkpoint L4/L5 and generation were not run because the task explicitly prohibits downloading the 23.4 GB payload. Reduced independently generated FP8/NVFP4 matrices execute in ORT with exact parity, and the full immutable config/index/header schema is pinned without payload artifacts. - Native NVFP4 preservation is unavailable because no actually available ORT dense operator ABI matches the checkpoint layout and dynamic activation contract exactly. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: acdf6027-4e8f-40aa-8600-abc9ee8591a4
1 parent 4ee4580 commit ba64bfe

19 files changed

Lines changed: 2976 additions & 14 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -758,7 +758,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
758758
logging in `_config_resolver.py`, `_diffusers_builder.py`, and
759759
`__main__.py`.
760760
- Added dependency lower bounds: `onnxscript>=0.6.0`, `onnx_ir>=0.1.0`,
761-
`numpy>=1.24.0`, `torch>=2.1.0`.
761+
`numpy>=1.24.0`, `torch>=2.10.0`.
762762
- Lazy-import heavy dependencies (`torch`, `transformers`,
763763
`safetensors.torch`) in CLI for faster `list`/`info` subcommands.
764764
- Mllama cross-attention K/V now cached after first computation in

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ dependencies = [
2121
"onnxscript>=0.7.1",
2222
"rfc8785",
2323
"safetensors",
24-
"torch>=2.1.0",
24+
"torch>=2.10.0",
2525
"tqdm",
2626
"transformers", # >5.0 recommended
2727
]

‎src/mobius/__main__.py‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
250250
)
251251

252252
load_weights = not args.no_weights
253+
keep_quantized = not getattr(args, "dequantize", False)
253254
task: str | ModelTask | None = args.task
254255

255256
# FP8 KV cache: resolve the optional per-layer scale file up front so both
@@ -350,6 +351,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
350351

351352
# Build from HuggingFace model ID or local config
352353
if args.config:
354+
import onnx_ir as ir
353355
import transformers
354356

355357
config_path = args.config
@@ -381,9 +383,27 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
381383
)
382384
if hasattr(hf_config, "text_config"):
383385
hf_config = hf_config.text_config
386+
from mobius.integrations.compressed_tensors import (
387+
CompressedTensorsConfig,
388+
stream_compressed_tensors_to_package,
389+
)
390+
391+
compressed_tensors_config = CompressedTensorsConfig.from_hf_config(parent_config)
384392
config = _config_from_hf(hf_config, parent_config=parent_config)
385393
if dtype_override is not None:
386394
config = dataclasses.replace(config, dtype=dtype_override)
395+
elif compressed_tensors_config is not None and keep_quantized:
396+
config = dataclasses.replace(config, dtype=ir.DataType.FLOAT16)
397+
if (
398+
compressed_tensors_config is not None
399+
and keep_quantized
400+
and config.dtype != ir.DataType.FLOAT16
401+
):
402+
raise SystemExit(
403+
"Error: storage-preserving compressed-tensors export requires "
404+
"--dtype f16 for the Microsoft W4A16/W8A16 custom-op ABI. "
405+
"Use --dtype f16 or --dequantize."
406+
)
387407
if args.glm_full_attention:
388408
if model_type != "glm_moe_dsa":
389409
raise SystemExit(
@@ -419,10 +439,32 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
419439
for name, model in pkg.items():
420440
model.graph.name = f"{config_path}/{name}"
421441
if load_weights:
422-
state_dict = _load_weights_from_dir(config_path)
423-
if hasattr(model_module, "preprocess_weights"):
424-
state_dict = model_module.preprocess_weights(state_dict)
425-
pkg.apply_weights(state_dict)
442+
if compressed_tensors_config is not None:
443+
# Packed FP4 weights cannot pass through ordinary apply_weights.
444+
# The same loader owns both faithful native storage and the
445+
# explicit keep_quantized=False dense reconstruction policy.
446+
checkpoint_dir = (
447+
os.path.dirname(config_path)
448+
if os.path.isfile(config_path)
449+
else config_path
450+
)
451+
stream_compressed_tensors_to_package(
452+
pkg,
453+
checkpoint_dir,
454+
compressed_tensors_config,
455+
preprocess_weights=getattr(
456+
model_module,
457+
"preprocess_weights",
458+
None,
459+
),
460+
fp8_kv_cache=fp8_kv_cache,
461+
keep_quantized=keep_quantized,
462+
)
463+
else:
464+
state_dict = _load_weights_from_dir(config_path)
465+
if hasattr(model_module, "preprocess_weights"):
466+
state_dict = model_module.preprocess_weights(state_dict)
467+
pkg.apply_weights(state_dict)
426468
else:
427469
model_id_or_path = args.model
428470
if static_cache_params is not None:
@@ -450,6 +492,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
450492
prune_prefill_prefix=prune_prefill_prefix,
451493
glm_full_attention=args.glm_full_attention,
452494
export_paged_attention=export_paged_attention,
495+
keep_quantized=keep_quantized,
453496
)
454497

455498
_save_package(pkg, output_dir, args, optimize, component_filter)
@@ -1250,6 +1293,14 @@ def build_parser() -> argparse.ArgumentParser:
12501293
"without it all layers use a unit scale of 1.0."
12511294
),
12521295
)
1296+
build_parser.add_argument(
1297+
"--dequantize",
1298+
action="store_true",
1299+
help=(
1300+
"Explicitly reconstruct supported compressed-tensors weights as dense "
1301+
"floating point. By default their FP8/NVFP4 storage is preserved."
1302+
),
1303+
)
12531304
_add_shared_build_arguments(build_parser)
12541305
build_parser.set_defaults(func=_cmd_build)
12551306

‎src/mobius/_cli_option_parity_test.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,14 @@
1010

1111
from __future__ import annotations
1212

13+
from unittest import mock
14+
15+
import onnx_ir as ir
1316
import pytest
1417

1518
from mobius.__main__ import build_parser
19+
from mobius._model_package import ModelPackage
20+
from mobius._testing import make_config
1621

1722
_SOURCE_ARGS = {
1823
"build": ["--model", "some/model"],
@@ -119,6 +124,112 @@ def test_dequantize_still_works(self):
119124
default = build_parser().parse_args(["build-gguf", "some.gguf", "--output", "out"])
120125
assert default.dequantize is False
121126

127+
def test_transformers_build_uses_the_same_explicit_dequantize_spelling(self):
128+
args = build_parser().parse_args(
129+
["build", "--model", "some/model", "--output", "out", "--dequantize"]
130+
)
131+
assert args.dequantize is True
132+
133+
134+
class TestLocalCompressedCheckpointRouting:
135+
@staticmethod
136+
def _run(monkeypatch, tmp_path, *extra_args):
137+
from mobius import __main__ as cli
138+
from mobius.integrations import compressed_tensors
139+
140+
class DummyModule:
141+
def __init__(self, config):
142+
self.config = config
143+
144+
@staticmethod
145+
def preprocess_weights(state):
146+
return state
147+
148+
hf_config = type("HFConfig", (), {"model_type": "qwen2"})()
149+
compressed_config = object()
150+
config = make_config(model_type="qwen2")
151+
package = ModelPackage({})
152+
built_configs = []
153+
stream = mock.Mock()
154+
155+
import transformers
156+
157+
monkeypatch.setattr(
158+
transformers.AutoConfig,
159+
"from_pretrained",
160+
lambda *args, **kwargs: hf_config,
161+
)
162+
monkeypatch.setattr(cli, "_config_from_hf", lambda *args, **kwargs: config)
163+
monkeypatch.setattr(cli.registry, "get", lambda _model_type: DummyModule)
164+
165+
def fake_build_from_module(_module, built_config, *args, **kwargs):
166+
built_configs.append(built_config)
167+
return package
168+
169+
monkeypatch.setattr(cli, "build_from_module", fake_build_from_module)
170+
monkeypatch.setattr(cli, "_save_package", mock.Mock())
171+
monkeypatch.setattr(
172+
compressed_tensors.CompressedTensorsConfig,
173+
"from_hf_config",
174+
lambda _config: compressed_config,
175+
)
176+
monkeypatch.setattr(
177+
compressed_tensors,
178+
"stream_compressed_tensors_to_package",
179+
stream,
180+
)
181+
args = build_parser().parse_args(
182+
[
183+
"build",
184+
"--config",
185+
str(tmp_path),
186+
"--output",
187+
str(tmp_path / "output"),
188+
*extra_args,
189+
]
190+
)
191+
cli._resolve_build_features(args)
192+
193+
cli._cmd_build(args)
194+
195+
return built_configs, stream, compressed_config
196+
197+
def test_default_routes_local_checkpoint_to_native_streaming_loader(
198+
self, monkeypatch, tmp_path
199+
):
200+
built_configs, stream, compressed_config = self._run(
201+
monkeypatch,
202+
tmp_path,
203+
)
204+
205+
assert built_configs[0].dtype == ir.DataType.FLOAT16
206+
stream.assert_called_once()
207+
assert stream.call_args.args[2] is compressed_config
208+
assert stream.call_args.kwargs["keep_quantized"] is True
209+
210+
def test_dequantize_routes_local_checkpoint_to_dense_streaming_fallback(
211+
self, monkeypatch, tmp_path
212+
):
213+
built_configs, stream, _compressed_config = self._run(
214+
monkeypatch,
215+
tmp_path,
216+
"--dequantize",
217+
)
218+
219+
assert built_configs[0].dtype == ir.DataType.FLOAT
220+
stream.assert_called_once()
221+
assert stream.call_args.kwargs["keep_quantized"] is False
222+
223+
def test_no_weights_does_not_open_local_compressed_shards(self, monkeypatch, tmp_path):
224+
built_configs, stream, _compressed_config = self._run(
225+
monkeypatch,
226+
tmp_path,
227+
"--no-weights",
228+
)
229+
230+
assert built_configs[0].dtype == ir.DataType.FLOAT16
231+
stream.assert_not_called()
232+
122233

123234
class TestSharedSaveOptions:
124235
"""Options that control how the package is written exist on both commands."""

‎src/mobius/_configs/_base.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1993,16 +1993,16 @@ class KimiK3Config(CausalLMConfig):
19931993
def from_transformers(cls, config, parent_config=None) -> KimiK3Config:
19941994
parent = parent_config or config
19951995
text = _as_attribute_config(getattr(config, "text_config", None)) or config
1996-
base = ArchitectureConfig.from_transformers(text, parent)
1997-
if (
1998-
base.quantization is not None
1999-
and base.quantization.quant_method == "compressed-tensors"
2000-
):
1996+
quantization_config = getattr(text, "quantization_config", None)
1997+
from mobius.integrations.compressed_tensors import is_compressed_tensors_config
1998+
1999+
if is_compressed_tensors_config(quantization_config):
20012000
raise NotImplementedError(
20022001
"Kimi-K3 compressed-tensors checkpoints use selective MXFP4 routed "
20032002
"experts, which are not representable by the generic quantized-linear "
20042003
"loader. Use a GGUF checkpoint or an unquantized state dict."
20052004
)
2005+
base = ArchitectureConfig.from_transformers(text, parent)
20062006
linear = _as_attribute_config(getattr(text, "linear_attn_config", None))
20072007
if linear is None:
20082008
raise ValueError("Kimi-K3 requires text_config.linear_attn_config")

‎src/mobius/_configs/_quantization.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,18 @@ def from_transformers(cls, hf_config) -> QuantizationConfig | None:
7777
"onnxruntime_USE_FP4_QMOE=ON). Export the unquantized (bf16) "
7878
"checkpoint instead, or quantize the bf16 export via Olive."
7979
)
80+
# compressed-tensors is a container format, not an INT4 method. Its
81+
# ``bits``/``group_size`` values live inside ordered config groups and
82+
# may describe FP8 and NVFP4 simultaneously. Parsing it as this coarse
83+
# config would emit integer MatMulNBits nodes for FP4 E2M1 bytes.
84+
from mobius.integrations.compressed_tensors import (
85+
CompressedTensorsConfig,
86+
is_compressed_tensors_config,
87+
)
88+
89+
if is_compressed_tensors_config(qc):
90+
CompressedTensorsConfig.parse(qc)
91+
return None
8092
# Block-scaled fp8 (E4M3 weight + 2D UE8M0 block scale) and packed-fp4
8193
# routed experts (I8-packed E2M1 nibbles + UE8M0 micro-scale) are a
8294
# mixed-precision layout this INT4/per-tensor path cannot load — the

‎src/mobius/_model_package.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,13 @@ class ModelPackage(UserDict[str, ir.Model]):
281281
Attributes:
282282
config: The architecture configuration used to build the models,
283283
or ``None`` if not available (e.g. after :meth:`load`).
284+
gguf_quantization_report: Optional persisted report describing GGUF
285+
source-storage preservation and conversion behavior.
286+
quantization_report: Optional transient, loader-specific metadata describing
287+
quantization handling. The concrete report type and schema belong to the
288+
integration that produced it (for example, ``CompressedTensorsLoadReport``);
289+
they are not a stable shared ``ModelPackage`` API and are not persisted by
290+
:meth:`save`.
284291
mtp_head: Optional nested MTP sidecar package. :meth:`save` records its
285292
collision-free directory in an explicit package manifest, and
286293
:meth:`load` restores it automatically.
@@ -298,6 +305,7 @@ def __init__(
298305
super().__init__(models or {})
299306
self.config = config
300307
self.gguf_quantization_report: GGUFQuantizationReport | None = None
308+
self.quantization_report: object | None = None
301309
# Optional persistence policy attached by the GGUF importer.
302310
self.gguf_reuse_plan: Any = None
303311
self.mtp_head: ModelPackage | None = None

‎src/mobius/components/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"MLP",
5656
"MLPMultiModalProjector",
5757
"MuseGlimmerVisionModel",
58+
"NVFP4QuantizedLinear",
5859
"Cosmos3EdgeMultiModalProjector",
5960
"MobileNetV5Encoder",
6061
"MoELayer",
@@ -247,6 +248,7 @@
247248
)
248249
from mobius.components._quantized_linear import (
249250
BlockQuantizedLinear,
251+
NVFP4QuantizedLinear,
250252
QuantizedEmbedding,
251253
QuantizedLinear,
252254
TiedQuantizedLMHead,

0 commit comments

Comments
 (0)