Skip to content

Add AMD Quark checkpoint support for Gemma 4 - #828

Open
poganesh wants to merge 10 commits into
onnxruntime:mainfrom
poganesh:amd-quark-support
Open

poganesh wants to merge 10 commits into
onnxruntime:mainfrom
poganesh:amd-quark-support

Conversation

@poganesh

@poganesh poganesh commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Quark quantization_config parsing — QuantizationConfig._from_quark_value reads Quark's global_quant_config.weight / exclude schema 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-level bits / group_size / sym / modules_to_not_convert that Quark never writes, and silently substitutes defaults.
  • Quark weight unpacking — preprocess_quark_weights / dequantize_quark_projections convert 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.
  • quark registered as an affine quant method wherever olive / gptq / awq are already special-cased.
  • --int4-accuracy-level — forwarded to build() as matmul_nbits_accuracy_level, reaching 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 Gemma 4 E4B, 42 layers, uint4 g32: 3.4e-03 on a single projection growing to 7.1e-01 on the final logits at ~900 tokens). Level 0 keeps the fp32 dequant + fp32 GEMM path.

Fixes

  • PLE projections resolve per module — per_layer_input_gate, per_layer_projection and per_layer_model_projection now resolve quantized-vs-float against the checkpoint's own declarations, instead of being hardcoded to float Linear. _text_linear_class is a per-component decision and can't see a modules_to_not_convert pattern 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 explicit lm_head keys Quark never writes, so quantize_lm_head silently defaulted False and a dense float head was built while the checkpoint supplied packed MatMulNBits weights. 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's reject_quantized_embeddings_lm_head becomes two independent flags:

    • reject_quantized_embeddings — stays on for every caller; a packed table needs GatherBlockQuantized in the embedding component.
    • reject_quantized_lm_head — a decoder that builds a MatMulNBits head can accept a packed head. Gemma 4 opts out; qwen35 keeps it on, so its behaviour is unchanged. Keeping a single flag would have silently relaxed the head guard for qwen35, which has no coverage for a packed head.

    Each guard now raises naming only the parameter it rejected.

Scope

uint4 only — _QUARK_DTYPE_BITS maps that one layout, whose packing this path is verified against. int4 stores sign-extended codes and int8 / uint8 are not int32-packed, so each would need its own unpack and zero-point convention.

Testing

  • New coverage in _configs_test.py, _weight_utils_test.py, gemma4_test.py, including a case asserting a packed Gemma 4 head reaches the graph in MatMulNBits B layout rather than being dequantized or overwritten.
  • Existing packed-key and fails-closed tests split per guard; qwen35_test.py message assertions follow the per-parameter wording.
  • tests/build_graph + tests/synthetic_parity_test.py: 1848 passed, 168 skipped, 22 xfailed.
  • Full suite (-m 'not integration and not arch_validation') run on this branch and on main with 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:

mobius build --model <quark-quantized-gemma4-checkpoint> --output <onnx-output-dir>

--model takes a HuggingFace model ID; a local checkpoint directory works the
same way with --config <dir>.

The config shape that selects this path:

"quantization_config": {
  "quant_method": "quark",
  "global_quant_config": {
    "weight": {"dtype": "uint4", "qscheme": "per_group", "group_size": 32,
               "symmetric": false, "is_dynamic": false}
  },
  "exclude": [...]
}

exclude lists the modules left in float. Anything outside this layout raises
rather than mis-dequantizing — see Scope.

The one new flag is optional, and is not Quark-specific:

mobius build --model <quark-quantized-gemma4-checkpoint> \
    --output <onnx-output-dir> --int4-accuracy-level 0

It sets accuracy_level on 4-bit MatMulNBits nodes. The CPU EP defaults to 4,
which dynamically quantizes activations to int8; 0 keeps the fp32 dequant +
fp32 GEMM path.

poganesh and others added 3 commits November 15, 2026 13:28
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]>
@poganesh
poganesh requested a review from a team November 15, 2026 22:15
Comment thread src/mobius/models/gemma4.py Fixed
Comment thread src/mobius/models/gemma4.py Fixed
Comment thread src/mobius/models/gemma4_test.py Fixed
Comment thread src/mobius/models/gemma4_test.py Fixed
- 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]>
@justinchuby

Copy link
Copy Markdown
Member

In the PR description, could you comment on example usage?

@poganesh

Copy link
Copy Markdown
Contributor Author

In the PR description, could you comment on example usage?

Added example usage in PR description.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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-level and 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

Comment thread src/mobius/_weight_utils.py Resolved
Comment thread src/mobius/_weight_utils.py Resolved
Comment thread src/mobius/models/gemma4.py Resolved
Comment thread src/mobius/models/gemma4.py Resolved
Comment thread src/mobius/weights/_codecs.py Resolved
@justinchuby

Copy link
Copy Markdown
Member

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.

poganesh and others added 2 commits November 16, 2026 13:16
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

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.40678% with 33 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/mobius/models/gemma4.py 73.39% 17 Missing and 12 partials ⚠️
src/mobius/integrations/quark/_weights.py 94.44% 2 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

poganesh and others added 3 commits November 16, 2026 13:46
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 justinchuby left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@poganesh

Copy link
Copy Markdown
Contributor Author

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 MatMulNBits

@poganesh

Copy link
Copy Markdown
Contributor Author

@kunal-vaishnavi, @titaiwangms - could you please help review the PR and merge. Thanks.

@justinchuby

Copy link
Copy Markdown
Member

@poganesh please make sure you have a local backup of your branch, thanks. Sorry for the recent churn.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants