Skip to content

Commit 223b438

Browse files
xiaoyu-workCopilot
andauthored
Load quantized checkpoint weights per component (#733)
## Summary - Add typed weight records, component-owned bundles, and the Olive/GPTQ/AWQ codec registry. - Load existing quantized checkpoint weights using independent component layouts and per-projection HuggingFace source-name overrides and exclusions; do not quantize floating-point checkpoint weights. - Preserve Gemma4, Qwen3.5/QMoE, and T5 architecture-specific weight adaptations, tied tables, and component sidecar routing, and validate quantized parameter binding. - Preserve default attention head dimensions and KV-head counts when HuggingFace configuration overrides only a subset of layers. - Keep Gemma4 per-layer inputs in `[batch, sequence, layers, projection]` form between embedding and decoder components for OpenVINO; other execution providers retain the flattened layout. - Restore the seq2seq, vision-language, and speech independent-component quantization matrix coverage lost during the earlier graph-test file split. ## Loading correctness fixes - Recognize canonical weights only as complete, shape-matching groups so raw GPTQ/AWQ scales remain available to their codec; validate zero points using each projection's effective symmetry. - Normalize quantized embedding tables for two-dimensional GatherBlockQuantized storage rather than treating them as linear projections. - Honor Qwen3.5-MoE's model-declared float exclusions and Whisper's declared output head during both graph construction and loading. - Preserve the distinction between an absent component mapping (legacy global rules) and an explicitly empty mapping (float components). - Defer Gemma4 component packing until projection overrides are resolved. Restore T5 HuggingFace source aliases and separate decoder-stack rules from the independently owned top-level LM head. ## Consolidation Replaces #666, #669, and #670 and consolidates the related development from `test/per-component-quantization-stack` into this single PR. The branch starts directly from `main` at `a471d3416e9c52d5508d28730962e18c8a1053d0`. The design (#664) and canonical component manifests (#665) are already merged and are not separate dependencies of this PR. This includes all seven previously uncommitted Gemma4/config/EP files from the old development worktree, not just the three original PR heads. The committed old feature stack was also compared with main plus this PR: production feature areas were retained, and its missing graph-layout matrix tests were restored in the current split test modules. ## Review and CI follow-up Addressed all eight inline review threads, including duplicate/already-resolved reports, in `190eb8a5`: - Literal module rules now respect path boundaries; the compatibility normalizer rejects a missing task clearly. Redundant Protocol statements and alias parentheses are removed. - Fixed the Gemma3 split-tied loading regression, including its previously floating-point scaled embedding. A shared scaled quantized embedding preserves Gemma4 behavior, and actual embedding execution plus unsupported-tie guards are covered. - Corrected the LLaVA fixture's missing `vision_model` namespace without relaxing target validation. - Updated the stale GGUF integration expectation to the export contract already established by #688; tokenizer-identity rejection and full logit/generation comparisons remain intact. The original full L4/L5 jobs hit their explicit one-hour limits after recording failures. Those failed case IDs also occur on the exact base `a471d341`, but cancellation lost exception details, so they are not claimed to be infrastructure-only or fixed. No model selection, tolerance, or timeout was weakened. Isolated GPT-2 diagnostics at the original head each executed and passed exactly one selected case: L4 https://github.com/onnxruntime/mobius/actions/runs/34308638240 and L5 https://github.com/onnxruntime/mobius/actions/runs/34308638242 . These single-case successes do not certify the all-model golden jobs. Fresh full CI for the published follow-up: https://github.com/onnxruntime/mobius/actions/runs/34309655380 . ## Validation - **874 passed, 16 skipped, 4 deselected** in the focused loading/config/model/CLI/graph suite, including the repaired CI selectors and scaled quantized embedding execution. - **1 passed** for the real pinned `smollm2-135m-instruct-f16` GGUF CLI export/reload, full-logit, and generation integration case. - Ruff lint and formatting passed for the changed Python files. Independent review of this follow-up found no significant issues. - Runs used the repository-required onnx-ir API through isolated dependencies; the shared environment was not modified. - The original seven-file pending patch remains consolidated in this PR. Local evidence does not claim that the all-model golden jobs or physical NPU execution are green. --------- Signed-off-by: Xiaoyu Zhang <[email protected]> Signed-off-by: xiaoyu-work <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]>
1 parent 45a477d commit 223b438

47 files changed

Lines changed: 4369 additions & 1369 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1919
MXFP4 reconstruction eagerly loads and converts the checkpoint and can
2020
require substantial host memory; native streaming remains the default.
2121

22-
### Independent quantization for multi-component packages
22+
### Per-component quantized checkpoint loading
2323

2424
#### Added
2525

26-
- HuggingFace composite checkpoints can declare a `component_quantization`
27-
mapping (or `quantization_config.components`) whose keys match
28-
`ModelPackage` component names such as `decoder`, `encoder`,
29-
`vision_encoder`, `audio_encoder`, and `embedding`. Nested
30-
`vision_config.quantization_config` and `audio_config.quantization_config`
31-
values are also recognized.
32-
- `build_from_module` now configures every component independently. Existing
33-
quantized decoder modules are retargeted to the component's bit width and
34-
group size, float encoder/vision/audio projections are converted to
35-
`MatMulNBits`, quantized embeddings use `GatherBlockQuantized`, and components
36-
omitted from the mapping remain floating point.
37-
- Olive mixed-precision component-wide `modules_to_not_convert` and `overrides`
38-
are collapsed into component layouts. Partial module rules and genuinely
39-
mixed layouts inside one ONNX component fail with an actionable error instead
40-
of loading packed weights with the wrong configuration.
26+
- Multi-component checkpoints may declare an authoritative
27+
`component_quantization` mapping with independent affine layouts for decoder,
28+
encoder, vision, audio, and embedding components. Exact and regex
29+
`modules_to_not_convert` rules are evaluated for each component-local module
30+
against its HuggingFace source name, so selected projections remain floating
31+
point while the rest of the component binds existing packed weights.
32+
- Mobius validates and normalizes existing Olive, GPTQ, and AWQ sidecars per
33+
component. It does not quantize floating-point checkpoint weights.
34+
- Gemma4, Qwen3.5/QMoE, and T5 adapters preserve their architecture-specific
35+
rename, tied-weight, and expert-packing semantics while handing independently
36+
routed component sidecars to the generic codec and binding validator.
37+
- OpenVINO Gemma4 exports keep the layer and projection dimensions separate in
38+
`per_layer_inputs` between the embedding and decoder components. Other
39+
execution providers retain the existing flattened layout.
40+
41+
#### Fixed
42+
43+
- Local `--config` builds use the shared Transformers builder rather than a
44+
duplicate model/weight loader, preserving per-component normalization,
45+
GPT-OSS MXFP4 policies, and `--dequantize`/`--no-weights` behavior.
46+
- Component rewrites preserve learned positional embeddings and deliberately
47+
floating-point shared-expert gates. Input token-table selection respects
48+
source aliases rather than quantizing every embedding module.
49+
- Ordinary decoder sidecars, including Qwen3.5 text, MoE, and VL weights, remain
50+
raw until per-projection overrides are resolved. QMoE expert packing and
51+
float table tying remain in the shared compatibility preprocessor.
52+
- Graph construction and normalization agree on legacy module rules for any
53+
single-component manifest, not only packages using the `model` key.
54+
- The binding gate also covers model-wide affine configurations. Orphan packed
55+
sidecars are rejected without rejecting complete canonical affine or QMoE groups.
56+
- Dynamic component source resolvers use the available HuggingFace model type
57+
instead of receiving an empty identifier. Configs without a model type retain
58+
static component metadata and config-based aliases, including T5 layer mappings.
59+
- Split tied tables already materialized by a model adapter load into their
60+
quantized embedding and LM-head targets instead of being rejected solely
61+
because the checkpoint declares tied weights.
62+
- Literal quantization exclusions and overrides respect module-path boundaries
63+
rather than accidentally matching similarly named layers or unrelated paths.
64+
- The compatibility weight normalizer requires an explicit task and reports a
65+
clear error if it is missing.
66+
- Raw GPTQ/AWQ scales are no longer mistaken for already-normalized parameters.
67+
Canonical detection requires a complete group with the target layout, and
68+
zero-point requirements follow each projection's effective symmetry.
69+
- Independently quantized embedding tables retain the two-dimensional
70+
`GatherBlockQuantized` layout instead of being packed as linear projections.
71+
- Graph construction and loading honor model-declared float exclusions and
72+
output heads, including Qwen3.5-MoE and Whisper. Legacy global module rules
73+
no longer fail when the component mapping is absent.
74+
- Gemma4 preserves raw component sidecars until per-projection normalization,
75+
and T5 maps local projections back to their HuggingFace names, so component
76+
and projection overrides select the same layout for graph and weights.
77+
- Sparse per-layer configuration dictionaries preserve the default attention
78+
head dimension and KV-head count instead of replacing them with overrides
79+
declared for only a subset of layers.
4180

4281
### Packed fused MoE experts (Olive/GPTQ/AWQ) survive HF weight renaming
4382

‎docs/design/per-component-quantization-loading.md‎

Lines changed: 105 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,12 @@ Every consumer uses the same manifest:
186186
An unresolved component is a typed error. Consumers must not independently
187187
guess aliases or state-dict prefixes.
188188

189+
Dynamic `get_hf_component_sources(model_type=..., hf_config=...)` hooks use the
190+
explicit model type, or `hf_config.model_type` when it is not supplied. If neither
191+
is available, the dynamic hook is skipped without guessing static source paths.
192+
Classes without a dynamic hook still publish their `HF_COMPONENT_SOURCES` for
193+
manually constructed configs that omit the model type.
194+
189195
### Mapping local module paths to HuggingFace names
190196

191197
Quantizer metadata names runtime HuggingFace modules, while graph construction
@@ -203,6 +209,17 @@ Architectures whose names cannot be aligned structurally declare explicit path
203209
aliases on their component descriptor; individual loaders must not invent
204210
their own mapping.
205211

212+
Component-owned source roots also prefix local descendants without a shared
213+
anchor segment, such as T5's `encoder` and `decoder` stacks. Models can publish
214+
static `HF_COMPONENT_MODULE_ALIASES` or implement
215+
`get_hf_component_module_aliases(hf_config=...)` when aliases
216+
depend on configuration, such as distinct encoder and decoder layer counts.
217+
These config-based aliases do not require a model type and remain available
218+
for manually constructed T5 configs.
219+
An existing alias or separately declared source takes precedence over
220+
synthesizing a component-root name; a top-level `lm_head` must not also become
221+
`decoder.lm_head` for rule matching.
222+
206223
## 2. Component quantization manifest
207224

208225
The parsed architecture config keeps legacy compatibility while exposing an
@@ -239,9 +256,18 @@ class ComponentQuantizationPlan:
239256
`modules_to_not_convert` is evaluated for each candidate HuggingFace module
240257
name while the component is constructed. A matching module remains a normal
241258
`Linear`; other eligible projections use the component's packed layout.
259+
Literal exclusions and overrides match the complete module path or a
260+
dot-separated descendant, never an arbitrary substring: `model.layers.1`
261+
matches `model.layers.1.self_attn` but not `model.layers.10`. Patterns prefixed
262+
with `re:` continue to use full-match regular expressions.
242263
Different packed layouts inside one component require per-module overrides and
243264
must be represented explicitly rather than inferred from a root plan.
244265

266+
Legacy model-wide module rules apply when the resolved manifest owns one
267+
component, regardless of its package key. Graph construction and normalization
268+
use the same manifest-based decision; passing a one-component subset of a
269+
multi-component package does not enable those rules.
270+
245271
## 3. Component-specific construction
246272

247273
The component configuration is selected before creating its parameters:
@@ -265,6 +291,15 @@ This keeps `per_layer_input_gate`, `per_layer_projection`, and other explicit
265291
float exceptions as ordinary `Linear` modules without weakening the rest of a
266292
quantized decoder.
267293

294+
Graph construction and packed-weight normalization use the same effective
295+
module policy. Model-declared `COMPONENT_OUTPUT_HEADS` stay float unless
296+
`quantize_lm_head` is enabled. A module's
297+
`component_quantization_excluded_methods` applies to that module and all its
298+
descendants; selecting a quantized component must not override this invariant.
299+
This includes the deliberately floating-point shared-expert gates in Qwen2-MoE
300+
and Qwen3-Next. `quantize_embeddings` converts input token tables identified by
301+
their local or aliased source names, not learned positional embeddings.
302+
268303
This replaces post-construction scanning that tries to swap `Linear` instances
269304
after a model has already encoded architecture-specific choices.
270305

@@ -310,8 +345,10 @@ class WeightRecord:
310345
```
311346

312347
Grouping prevents several raw sidecar keys from being renamed, split, or
313-
overwritten independently. A missing scale or zero point is detected before
314-
any architecture transform executes.
348+
overwritten independently. Missing scales are rejected during grouping.
349+
Zero-point requirements are validated after resolving the module's effective
350+
symmetry, since an override may make one projection symmetric inside an
351+
otherwise asymmetric component.
315352

316353
`WeightBundle` owns records for one component:
317354

@@ -330,13 +367,20 @@ Format-specific layout handling lives in a registry:
330367
class QuantizationCodec(Protocol):
331368
method: str
332369

333-
def decode_metadata(self, value: object) -> QuantizationConfig: ...
370+
def group(
371+
self,
372+
component: ComponentDescriptor,
373+
state_dict: Mapping[str, torch.Tensor],
374+
config: QuantizationConfig,
375+
) -> WeightBundle: ...
334376

335377
def normalize(
336378
self,
337379
record: WeightRecord,
338-
target: QuantizationConfig,
339-
) -> WeightRecord: ...
380+
config: QuantizationConfig,
381+
*,
382+
kind: Literal["linear", "embedding"] = "linear",
383+
) -> dict[str, torch.Tensor]: ...
340384
```
341385

342386
Initial codecs:
@@ -354,20 +398,45 @@ The codec:
354398

355399
Model names and model-specific parameter paths are prohibited inside codecs.
356400

401+
The target module supplies the weight kind: linear projections use the
402+
three-dimensional `MatMulNBits` layout, while embedding tables use the
403+
two-dimensional `GatherBlockQuantized` layout. A shared `.scales` suffix alone
404+
does not identify a canonical group; the packed tensor, scales, and required
405+
zero points must all match the target parameters before normalization is
406+
skipped.
407+
The component normalizer also retains complete canonical QMoE expert groups.
408+
When component plans or single-component module rules are active, it rejects
409+
unconsumed raw sidecars even when no qweight is present or no component owns
410+
them; valid canonical scales must not be mistaken for orphan checkpoint data.
411+
357412
## 6. ModelWeightAdapter
358413

359-
The model adapter receives one already-routed component bundle:
414+
The current implementation retains a raw-state compatibility adapter for
415+
architecture-specific name mapping, tying, and expert transformations:
360416

361417
```python
418+
@dataclasses.dataclass(frozen=True)
419+
class WeightAdapterContext:
420+
config: BaseModelConfig
421+
manifest: ComponentManifest
422+
423+
362424
class ModelWeightAdapter(Protocol):
363425
def adapt(
364426
self,
365-
component: ComponentDescriptor,
366-
weights: WeightBundle,
367-
config: BaseModelConfig,
368-
) -> WeightBundle: ...
427+
module: nn.Module,
428+
state_dict: Mapping[str, torch.Tensor],
429+
context: WeightAdapterContext,
430+
) -> dict[str, torch.Tensor]: ...
369431
```
370432

433+
Routing and codec grouping happen after this adapter. With component plans or
434+
single-component module rules, ordinary packed sidecars stay raw until the
435+
shared loader resolves their per-projection layouts. The shared legacy
436+
preprocessor can still pack QMoE expert banks and tie floating-point tables.
437+
A per-component `WeightBundle` adapter is a future migration target, not the
438+
currently implemented interface.
439+
371440
Appropriate model-specific operations include:
372441

373442
- HuggingFace-to-ONNX name alignment;
@@ -379,9 +448,9 @@ Appropriate model-specific operations include:
379448

380449
The adapter must not:
381450

382-
- choose a component quantization configuration;
383-
- read unrelated component weights;
384-
- dispatch Olive/GPTQ/AWQ formats;
451+
- override the producer's per-projection quantization policy;
452+
- eagerly repack ordinary sidecars using one model-wide or component-wide layout;
453+
- duplicate generic Olive/GPTQ/AWQ format conversion;
385454
- bind graph initializers;
386455
- silently drop unrecognized packed tensors.
387456

@@ -407,12 +476,18 @@ Required invariants:
407476

408477
These checks happen before save or runtime metadata generation.
409478

479+
The loading-time binding gate scans emitted `MatMulNBits` and
480+
`GatherBlockQuantized` nodes regardless of whether configuration came from a
481+
component mapping or a legacy root plan. `build(load_weights=False)` still
482+
returns an unbound skeleton. Independently, `ModelPackage.save()` checks all
483+
initializers by default.
484+
410485
## Ordering of normalization and model transforms
411486

412487
Some transforms operate on logical tensors while others depend on a source
413-
packing layout. The pipeline therefore distinguishes:
488+
packing layout. The target typed pipeline distinguishes:
414489

415-
1. **sidecar grouping** — always first;
490+
1. **sidecar grouping**;
416491
2. **semantic routing/name mapping** — typed records remain packed;
417492
3. **architecture transform planning** — split/fuse intent is declared;
418493
4. **codec normalization** — source layout becomes canonical target layout;
@@ -422,6 +497,10 @@ packing layout. The pipeline therefore distinguishes:
422497
A transform unsupported for packed storage fails explicitly. It must not
423498
silently dequantize and requantize.
424499

500+
The current compatibility path performs raw semantic name mapping before
501+
grouping, as described above. It preserves ordinary sidecars rather than
502+
claiming that the full typed transform-planning pipeline is already implemented.
503+
425504
## Compatibility plan
426505

427506
The migration keeps current APIs operational:
@@ -432,6 +511,17 @@ The migration keeps current APIs operational:
432511
manifest resolver;
433512
- loaders without a component manifest retain current single-model behavior.
434513

514+
Local Transformers `--config` builds use the same shared `build()` entry point
515+
as `--model`. The CLI forwards loading and quantization policy options; the
516+
shared builder owns component adaptation, normalization, and format-specific
517+
loading, including native GPT-OSS MXFP4 streaming. These steps must not be
518+
duplicated in a local CLI loader.
519+
520+
Component-aware compatibility adapters preserve raw sidecars through their
521+
architecture-specific renames. They must not normalize an entire component
522+
with one root-resolved layout before the generic loader evaluates projection
523+
overrides.
524+
435525
Compatibility paths emit no behavior changes in the first two implementation
436526
PRs. Removal occurs only after model migrations and parity coverage.
437527

‎src/mobius/_builder.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from onnxscript import nn
2626

2727
from mobius._build_context import build_context
28+
from mobius._component_manifest import ComponentManifest
2829
from mobius._component_quantization import configure_component_quantization
2930
from mobius._configs import BaseModelConfig
3031
from mobius._execution_providers import ep_registry
@@ -137,6 +138,7 @@ def build_from_module(
137138
fp8_kv_cache: bool = False,
138139
kv_cache_scales: dict[int, tuple[float, float]] | None = None,
139140
prune_prefill_prefix: bool = False,
141+
component_manifest: ComponentManifest | None = None,
140142
) -> ModelPackage:
141143
"""Build an ONNX :class:`ModelPackage` from a module instance and config.
142144
@@ -162,8 +164,12 @@ def build_from_module(
162164
if prune_prefill_prefix:
163165
task = _enable_prefill_prefix_pruning_task(task)
164166
resolved_task = get_task(task)
165-
component_manifest = resolved_task.component_manifest()
166-
configure_component_quantization(module, config, resolved_task)
167+
component_manifest = configure_component_quantization(
168+
module,
169+
config,
170+
resolved_task,
171+
manifest=component_manifest,
172+
)
167173
_cast_module_dtype(module, dtype)
168174
capabilities = ep_registry.require(execution_provider)
169175
with build_context(capabilities, dtype):

‎src/mobius/_component_manifest.py‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def source_module_names(self, local_module_path: str) -> tuple[str, ...]:
7474
return self.source_paths
7575

7676
local_parts = local_module_path.split(".")
77-
candidates = [local_module_path]
77+
candidates: list[str] = []
7878
for local_prefix, source_prefix in self.source_path_aliases:
7979
if local_module_path == local_prefix:
8080
candidates.append(source_prefix)
@@ -89,9 +89,16 @@ def source_module_names(self, local_module_path: str) -> tuple[str, ...]:
8989
]
9090
if anchor_indices:
9191
for index in anchor_indices:
92-
suffix = local_parts[index + 1 :]
93-
candidates.append(".".join((*source_parts, *suffix)))
94-
return tuple(dict.fromkeys(candidates))
92+
suffix_parts = local_parts[index + 1 :]
93+
candidates.append(".".join((*source_parts, *suffix_parts)))
94+
if not candidates:
95+
component_roots = {self.name, self.module_attribute_path.rsplit(".", 1)[-1]}
96+
for source_path in self.source_paths:
97+
if source_path.rsplit(".", 1)[-1] in component_roots:
98+
# Use the component root only if no alias or separate
99+
# source (such as a top-level output head) already owns it.
100+
candidates.append(f"{source_path}.{local_module_path}")
101+
return tuple(dict.fromkeys((local_module_path, *candidates)))
95102

96103

97104
@dataclasses.dataclass(frozen=True)
@@ -132,12 +139,15 @@ def names(self) -> tuple[str, ...]:
132139

133140
def get_hf_component_sources(
134141
module_class: type,
135-
model_type: str,
142+
model_type: str | None,
136143
hf_config: object,
137144
) -> dict[str, tuple[str, ...]]:
138-
"""Read runtime HuggingFace component paths from a registered model class."""
145+
"""Read component paths, invoking dynamic hooks only with a known model type."""
139146
resolver = getattr(module_class, "get_hf_component_sources", None)
140147
if resolver is not None:
148+
model_type = model_type or getattr(hf_config, "model_type", None)
149+
if not model_type:
150+
return {}
141151
resolved = resolver(model_type=model_type, hf_config=hf_config)
142152
else:
143153
resolved = getattr(module_class, "HF_COMPONENT_SOURCES", {})
@@ -158,13 +168,18 @@ def resolve_component_manifest(
158168

159169
component_sources: dict[str, tuple[str, ...]] = {}
160170
component_aliases: dict[str, tuple[tuple[str, str], ...]] = {}
161-
if module_class is not None and model_type is not None and hf_config is not None:
171+
if module_class is not None and hf_config is not None:
162172
component_sources = get_hf_component_sources(
163173
module_class,
164174
model_type,
165175
hf_config,
166176
)
167-
raw_aliases = getattr(module_class, "HF_COMPONENT_MODULE_ALIASES", {})
177+
alias_resolver = getattr(module_class, "get_hf_component_module_aliases", None)
178+
raw_aliases = (
179+
alias_resolver(hf_config=hf_config)
180+
if alias_resolver is not None
181+
else getattr(module_class, "HF_COMPONENT_MODULE_ALIASES", {})
182+
)
168183
component_aliases = {
169184
name: tuple(aliases.items()) for name, aliases in raw_aliases.items()
170185
}

0 commit comments

Comments
 (0)