Repository navigation
Conversation
Lets mobius build directly from an AMD Quark quantization_config (global_quant_config.weight / exclude) without a separate conversion step, and fixes quantization resolution for Gemma4's per-layer-embedding (PLE) projections and lm_head: - _configs/_quantization.py: parse Quark's quantization_config schema natively (QuantizationConfig._from_quark_value), rejecting layouts this affine INT4 path can't honour instead of silently mis-dequantizing. - _weight_utils.py: preprocess_quark_weights/dequantize_quark_projections unpack Quark's int32-packed, AWQ-GEMM-interleaved uint4 codes into the MatMulNBits layout (no +1 zero-point offset, unlike the AWQ path -- Quark's zero points are unbiased and survive exactly). - _component_quantization.py, integrations/transformers/_builder.py, weights/_codecs.py: register "quark" alongside olive/gptq/awq wherever those affine quant methods are special-cased. - models/gemma4.py: per_layer_input_gate/per_layer_projection/ per_layer_model_projection now resolve quantized-vs-float per module against the checkpoint's own declarations (_per_layer_projection_linear_class / _per_layer_model_projection_linear_class), instead of being hardcoded to plain float Linear regardless of what the checkpoint supplies. _dequantize_float_only_projections keeps weight loading in sync with that per-module resolution for quark checkpoints. - __main__.py: add --int4-accuracy-level, forwarded to build() as matmul_nbits_accuracy_level so it reaches MatMulNBits through the existing build_context mechanism. The CPU EP defaults this to 4, which dynamically quantizes activations to int8; that error compounds with depth and context length (measured on Gemma4-E4B, 42 layers, uint4 g32: 3.4e-03 on one projection growing to 7.1e-01 on the final logits at ~900 tokens), so level 0 keeps the fp32 dequant + fp32 GEMM path. Tests added in _configs_test.py, _weight_utils_test.py, gemma4_test.py. Co-Authored-By: Claude Opus 5 <[email protected]>
Two defects on the per-layer-embedding path, both hit by AMD's own amd/gemma-4-E4B-it_AWQ_uint4_g32: 1. The ctor built per_layer_model_projection and its _consumer as a bare Linear unconditionally, ignoring _per_layer_model_projection_linear_class. The equivalent site further down resolves the class correctly, so a quantized projection got a float module and the packed weights had nowhere to land. 2. _split_per_layer_projection_weight handled only dense [N, K] weights. Quark-packed tensors need dim 1 split at producer/8 for weight and zero_point, and dim -1 split at producer for scale.
Quark signals float modules via `exclude`, so a module absent from that
list is quantized. The AWQ/GPTQ parser reads explicit lm_head/embeds
keys, which Quark never writes, so quantize_lm_head silently defaulted
False and the graph built a dense float head while the checkpoint
supplied packed MatMulNBits weights. Head-presence detection had the
same blind spot: testing only for the float head key reported "missing"
for a packed head and synthesized the embed table over it.
Accepting a packed head means the embedding table and the LM head can no
longer share one guard, so split preprocess_quantized_weights'
reject_quantized_embeddings_lm_head into two independent flags:
reject_quantized_embeddings - the embedding component would need
GatherBlockQuantized to consume a packed table, so this stays on
for every caller.
reject_quantized_lm_head - a decoder that builds a MatMulNBits head
can accept a packed head. Gemma4 opts out; qwen35 keeps it on, so
its behaviour is unchanged.
Keeping the single flag would have silently relaxed the head guard for
qwen35 too, which has no coverage for a packed head. Each guard now
raises naming only the parameter it rejected, rather than a combined
"embeddings and LM heads" message.
Tests: the packed-key and fails-closed cases are split per guard, the
qwen35 message assertions follow the per-parameter wording, and a new
case covers what this commit enables -- a packed Gemma4 head survives
preprocess_weights with no float head synthesized over it.
Co-Authored-By: Claude Opus 5 <[email protected]>
- RUFF/PIE810: collapse the two head-key startswith calls into one tuple call (both occurrences). - RUFF/D205, RUFF/D209: reflow the test docstring so the summary line is followed by a blank line and the closing quotes sit on their own line. - RUFF-FORMAT: let the formatter unwrap three raise ValueError calls that fit on one line, and restore the two blank lines before _typed_scalar_constant. Co-Authored-By: Claude Opus 5 <[email protected]>
7ea7e03 to
760b0ed
Compare
|
In the PR description, could you comment on example usage? |
Added example usage in PR description. |
There was a problem hiding this comment.
🟡 Changes recommended
Quark weight handling has unresolved sidecar detection, grouping, and splitting issues, plus missing partial-group padding, which can bypass unsupported-embedding rejection or cause export failures.
5 open issues
Pad codes for partial final quantization groups · New Reject Quark sidecars for unsupported quantized embeddings · New Exclude Quark-packed projections from the dense KV-sharing branch · New Split Quark sidecars with WebGPU embedding weights · New Group Quark weights and sidecars into one packed record · New
What changed in this PR
Extends Mobius’s checkpoint-loading and ONNX export paths to support AMD Quark uint4 Gemma 4 E2B/E4B checkpoints for Ryzen AI deployment.
Changes:
- Adds Quark configuration parsing, packed-weight conversion, and affine-loader registration.
- Updates Gemma 4 projection and LM-head handling, while separating embedding and head rejection guards.
- Adds
--int4-accuracy-leveland regression coverage for configuration, weight conversion, and model preprocessing.
| File | Description |
|---|---|
src/mobius/weights/_codecs.py |
Registers Quark with the affine codec. |
src/mobius/models/qwen35.py |
Preserves separate embedding and LM-head rejection guards. |
src/mobius/models/qwen35_test.py |
Updates assertions for parameter-specific guard errors. |
src/mobius/models/gemma4.py |
Adds per-module projection resolution, packed splitting, and head detection. |
src/mobius/models/gemma4_test.py |
Covers packed heads and per-layer projection handling. |
src/mobius/integrations/transformers/_builder.py |
Routes Quark checkpoints through the affine loader. |
src/mobius/_weight_utils.py |
Adds Quark unpacking, repacking, dequantization, and independent guards. |
src/mobius/_weight_utils_test.py |
Tests Quark tensor conversion and independent guards. |
src/mobius/_configs/_quantization.py |
Parses Quark’s nested schema and rejects unsupported layouts. |
src/mobius/_configs_test.py |
Tests Quark configuration parsing and validation. |
src/mobius/_component_quantization.py |
Recognizes Quark as an affine quantization method. |
src/mobius/__main__.py |
Adds and forwards the INT4 accuracy-level option. |
Review effort: Balanced
|
Thanks for this addition! Could you move quark specific helping logic into src/mobius/integrations/quark? We will be organizing existing code this way too for better maintainability. |
Follows the existing per-vendor integration layout (modelopt,
compressed_tensors): a thin __init__ re-exporting private modules.
Moved, unchanged:
- _weight_utils: _unpack_quark_int32, _pack_nibbles_ort,
preprocess_quark_weights, dequantize_quark_weight,
dequantize_quark_projections -> quark/_weights.py
- _configs/_quantization: _QUARK_DTYPE_BITS and _from_quark_value ->
quark/_config.py as is_quark_quant_config / parse_quark_config,
matching the is_modelopt_quant_config shape already dispatched to
from QuantizationConfig.from_value
- the corresponding tests -> quark/_{config,weights}_test.py
Call sites use deferred imports so the core modules stay independent of
the vendor packages, as the modelopt and compressed-tensors branches
already do.
QUARK_PACKED_QUANT_SUFFIXES stays in _weight_utils: it feeds the
module-level PACKED_QUANT_SUFFIXES predicate, which would otherwise
need a top-level vendor import.
No behaviour change.
Co-Authored-By: Claude Opus 5 <[email protected]>
Five fail-open paths, each with coverage: - PLE split picked its layout by shape alone. On the split-embedding route _split_per_layer_projection_weight runs after preprocess_quantized_weights, so the payload is already [N, n_blocks, blob] and dim 0 equals the dense `expected`: the dense branch fired and left .scales/.zero_points at full N, silently unbindable. Layout is now chosen by which sidecars are present, and the normalized branch splits the sidecars with the payload. - The same shape test could capture a raw Quark payload when hidden_size == num_hidden_layers * hidden_size_per_layer_input. - _is_packed_sidecar_of did not know Quark's .weight_scale / .weight_zero_point, so reject_quantized_embeddings was a no-op for Quark: quantize_embeddings is never derived from `exclude`, so a packed table passed both tests and reached a float initializer. - preprocess_quark_weights validated groups with ceil(), admitting a partial trailing group that then failed inside reshape with an opaque size error. Now an exact check with an explicit message. - _LegacyAffineCodec.group() keys off _qweight/.qweight, which Quark has neither of; it would emit three FloatWeight records instead of one PackedWeight. Quark now raises there, pointing at root quantization_config. Co-Authored-By: Claude Opus 5 <[email protected]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
ruff check --fix and ruff format over the new quark package and the PLE-split changes: - RUFF/W391 trailing newline and a stray CR at EOF, both artifacts of assembling the moved files - RUFF/I001 missing blank line after the import block in _weights_test.py - RUFF-FORMAT: collapse error strings that fit on one line No behaviour change. Co-Authored-By: Claude Opus 5 <[email protected]>
The grouper is also reached without an explicit component plan: a single-component (text-only) build whose root config carries module rules passes _uses_global_module_rules and routes here too. The old message told such a build to 'use a root quantization_config', which it already was. Co-Authored-By: Claude Opus 5 <[email protected]>
Codecov patch coverage was 89.13% against a 90.39% target; the gap was genuinely untested code, not a reporting artifact. - dequantize_quark_weight and dequantize_quark_projections had no direct tests at all, despite being public API used by gemma4's PLE path. Adds a round-trip against manually computed (code - zero_point) * scale, the no-zero-points case, dtype honouring, and the skip-absent-stem contract. - Covers the fail-closed branches the PR description advertises: missing or non-mapping global_quant_config.weight, non-sequence exclude, invalid re: patterns, layer_type_quant_config, non-4-bit payloads, output-feature mismatch, and odd zero-point column padding. - Asserts quantize_lm_head in both directions. The excluded-vs-not distinction is the headline fix and had no direct assertion. Co-Authored-By: Claude Opus 5 <[email protected]>
justinchuby
left a comment
There was a problem hiding this comment.
LGTM thanks. Also note that we have added https://onnx.ai/onnx/operators/onnx__DequantizePacked.html to opset 29 and will use this op for gguf weights in the future. Please check and let me know if there are extensions AMD wants to see.
Thanks for the note, will follow up on extensions if needed. No impact on this PR since the Quark path emits |
|
@kunal-vaishnavi, @titaiwangms - could you please help review the PR and merge. Thanks. |
|
@poganesh please make sure you have a local backup of your branch, thanks. Sorry for the recent churn. |

Enables AMD Quark quantized Gemma 4 (E2B / E4B) checkpoints to be exported through Mobius, for deployment on Ryzen AI. Today such a checkpoint can't be built directly: Mobius doesn't recognise Quark's
quantization_config, can't unpack its weight layout, and resolves Gemma 4's per-layer-embedding (PLE) projections and LM head to float regardless of what the checkpoint supplies.Adds
quantization_configparsing —QuantizationConfig._from_quark_valuereads Quark'sglobal_quant_config.weight/excludeschema directly, so no separate conversion step is needed. Layouts this affine INT4 path can't honour are rejected rather than silently mis-dequantized. Without this a Quark config falls through to the AWQ/GPTQ reader, which looks for top-levelbits/group_size/sym/modules_to_not_convertthat Quark never writes, and silently substitutes defaults.preprocess_quark_weights/dequantize_quark_projectionsconvert int32-packed, AWQ-GEMM-interleaveduint4codes into theMatMulNBitslayout. No+1zero-point offset, unlike the AWQ path: Quark's zero points are unbiased.quarkregistered as an affine quant method whereverolive/gptq/awqare already special-cased.--int4-accuracy-level— forwarded tobuild()asmatmul_nbits_accuracy_level, reachingMatMulNBitsthrough the existingbuild_contextmechanism. The CPU EP defaults this to4, which dynamically quantizes activations to int8; that error compounds with depth and context length (measured on Gemma 4 E4B, 42 layers, uint4 g32:3.4e-03on a single projection growing to7.1e-01on the final logits at ~900 tokens). Level0keeps the fp32 dequant + fp32 GEMM path.Fixes
PLE projections resolve per module —
per_layer_input_gate,per_layer_projectionandper_layer_model_projectionnow resolve quantized-vs-float against the checkpoint's own declarations, instead of being hardcoded to floatLinear._text_linear_classis a per-component decision and can't see amodules_to_not_convertpattern targeting one submodule.Packed PLE weight splitting — the per-layer-model-projection split at the first KV-sharing layer now handles Quark-packed
[K, N/8]weights with their scale / zero-point sidecars, not just dense[N, K].Quantized LM head detection — Quark signals float modules via
exclude, so a module absent from that list is quantized. The AWQ/GPTQ parser reads explicitlm_headkeys Quark never writes, soquantize_lm_headsilently defaultedFalseand a dense float head was built while the checkpoint supplied packedMatMulNBitsweights. Head-presence detection had the same blind spot and would synthesize the embed table over a packed head.Embedding and LM-head guards split —
preprocess_quantized_weights'sreject_quantized_embeddings_lm_headbecomes two independent flags:reject_quantized_embeddings— stays on for every caller; a packed table needsGatherBlockQuantizedin the embedding component.reject_quantized_lm_head— a decoder that builds aMatMulNBitshead can accept a packed head. Gemma 4 opts out;qwen35keeps it on, so its behaviour is unchanged. Keeping a single flag would have silently relaxed the head guard forqwen35, which has no coverage for a packed head.Each guard now raises naming only the parameter it rejected.
Scope
uint4only —_QUARK_DTYPE_BITSmaps that one layout, whose packing this path is verified against.int4stores sign-extended codes andint8/uint8are not int32-packed, so each would need its own unpack and zero-point convention.Testing
_configs_test.py,_weight_utils_test.py,gemma4_test.py, including a case asserting a packed Gemma 4 head reaches the graph inMatMulNBitsBlayout rather than being dequantized or overwritten.qwen35_test.pymessage assertions follow the per-parameter wording.tests/build_graph+tests/synthetic_parity_test.py: 1848 passed, 168 skipped, 22 xfailed.-m 'not integration and not arch_validation') run on this branch and onmainwith an identical environment produces identical failure sets — no regressions, +22 passing from the new tests.Example usage
No new command or opt-in flag — a Quark checkpoint is recognised from its
quantization_config, so the existing build path handles it:--modeltakes a HuggingFace model ID; a local checkpoint directory works thesame way with
--config <dir>.The config shape that selects this path:
excludelists the modules left in float. Anything outside this layout raisesrather than mis-dequantizing — see Scope.
The one new flag is optional, and is not Quark-specific:
It sets
accuracy_levelon 4-bitMatMulNBitsnodes. The CPU EP defaults to4,which dynamically quantizes activations to int8;
0keeps the fp32 dequant +fp32 GEMM path.