Skip to content

fix(features): honor GPTQ dynamic exclusions and repair AUTO_NF12/EoRA/rotation/GSQ (#4077) - #4086

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4077-features
Nov 15, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4077-features

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4077

Audit of main @ ad0525c; branch based on 39b62765e, merged with origin/main @ 701e58b9f. All six items are fixed with a fail-before / pass-after regression test, on CUDA and ROCm.

TL;DR

# Item Root cause Fix
1 GPTQ dynamic -: loads as garbage in plain HF config.json carried no modules_in_block_to_quantize, so Optimum quantized every block layer and built an uninitialized MarlinLinear for excluded modules save_quantized writes the explicit quantized full-name set; the loader accepts full names
2 requantize(embed_quant_mode=INPUT/BOTH) crashes under AUTO_NF12 endpoint object is swapped twice; the layer reference stayed on the detached META source re-resolve the live endpoint after planning and before replay
3 post-quant EoRA crashes on BF16 sources under AUTO_NF12 AutoNF12HookedLinear has no weight; EoRA needs dense w - wq and wq + BA EoRA generation runs on dense native weights (explicit warning); processors also handle a packed source defensively
4 post-quant EoRA KeyError with dynamic -: DequantizeProcessor(qcfg=None) popped modules that were never quantized pass the checkpoint qcfg; skip modules whose dynamic rule is False
5 rotation half-rotates Qwen2.5 then asserts only the model class was validated before fuse_layer_norms validate hidden_size/intermediate_size against get_hadK first; raise a clear ValueError
6 staged GSQ fp16 aborts with a device assert FP16 MSE reduction, FP16 relaxation exponent, and FP16 training logits overflow; torch._assert_async poisons the context FP32 reduction/exponent/logits and a recoverable RuntimeError

1. GPTQ dynamic -: exclusions and plain HF loading

Optimum decides which modules to quantize from quantization_config.modules_in_block_to_quantize and matches entries with name.endswith. A GPTQ checkpoint with dynamic={"-:...": {}} used to serialize only the exclusion regex, so a plain AutoModelForCausalLM load built MarlinLinear with an uninitialized qweight for each excluded dense module (issue: PPL 689.8 vs 20.5).

flowchart TD
    A["GPTQ checkpoint with dynamic -: rules"] --> B{"modules_in_block_to_quantize"}
    B -- absent (old) --> C["Optimum quantizes every block layer"]
    C --> D["excluded module becomes MarlinLinear<br/>with uninitialized qweight"]
    D --> E["garbage logits / PPL 689.8"]
    B -- present (new) --> F["Optimum keeps only name.endswith entries"]
    F --> G["excluded module stays dense"]
    G --> H["matches GPTQModel.load"]
Loading
  • gptqmodel/models/writer.py:258 computes find_modules(model, layers=[BaseQuantLinear]) and writes one group [[full names]] (Optimum flattens with sum(..., []), so a flat string list raises TypeError).
  • gptqmodel/models/loader.py:2462 and gptqmodel/models/writer.py:2404 accept a block-relative or full name, so GPTQModel reload still honors the same payload.
  • gptqmodel/quantization/config.py:4747 adds has_dynamic_exclusions(); the key is written only for GPTQ checkpoints with -: rules.

Tiny-Llama HF check (AutoModelForCausalLM.from_pretrained + optimum 2.3.0):

excluded module type HF vs GPTQModel logits rel. error
before MarlinLinear 0.011763
after nn.Linear 0.000000

2. Endpoint requantize under AUTO_NF12

The input-embedding pseudo-layer is the projection. AUTO_NF12 replaces NamedModule.module with an AutoNF12Embedding; deferred dense-source materialization replaces it again with a dense nn.Embedding. The layer reference captured before those swaps pointed at a detached module, so direct-state materialization chased META tensors no longer in the model tree.

stateDiagram-v2
    state "dense Embedding in tree" as Dense
    state "AutoNF12Embedding in tree" as Packed
    state "dense quant_source in tree" as Source
    state "detached dense Embedding (META)" as Stale
    Dense --> Packed: subset planning (AUTO_NF12)
    Packed --> Source: quant_source materialization
    Packed --> Stale: local layer reference
    Stale --> Stale: direct-state materialization fails
    Source --> Source: replay uses live endpoint
Loading

gptqmodel/looper/stage_layer.py:247 adds _resolve_live_endpoint_module; it is called after planning (:976) and again after the subset passes (:1106) for input embeddings, output embeddings, and lm_head. The second read prevents replaying the released AUTO_NF12 wrapper, whose packed buffers are empty by then.

pytest tests/test_requant_embed_lm_head_e2e.py:

result
before (origin/main) 1 failed in 19.29s — RuntimeError: Lazy forward direct-state materialization left META tensors under ``.
after 1 passed in 45.72s

3. Post-quant EoRA under AUTO_NF12

EoRA needs dense native weights twice: w - wq and wq + BA installed back into the module. AutoNF12HookedLinear has no weight, so adapter.generate now disables AUTO_NF12 for that pass and logs why (gptqmodel/models/base.py:2687). The saved adapter dtype and the quantized checkpoint are unchanged.

sequenceDiagram
    participant C as adapter.generate
    participant Q as GPTQModel.load quantized
    participant N as GPTQModel.load native
    participant D as DequantizeProcessor
    participant E as EoraProcessor
    C->>Q: find TorchLinear modules
    C->>N: load with checkpoint qcfg
    C->>N: AUTO_NF12 -> OFF (logged)
    C->>D: process modules
    D->>D: skip qcfg.dynamic_get(name) is False
    D->>D: dense source weight (NF12 decode fallback)
    D->>E: w_wq_diff + wq
    E->>E: wq + B@A
    E->>C: save adapter
Loading

gptqmodel/looper/dequantize_processor.py:68 also decodes a packed source through dequantize_weight when a caller supplies one directly (NF12 stores BF16 exactly), and gptqmodel/looper/eora_processor.py:159 takes the hook device from the module buffers instead of .weight.

EoRA r64, 512 calibration rows, Llama-3.2-1B-Instruct (wikitext-2 PPL):

checkpoint / harness before after
...-GPTQ-4bits-gp32, 16 docs × 256 tokens 26.2964 25.4852
...-gptqmodel-4bit-vortex-v1, 16 docs × 256 tokens 26.4168 25.9521
...-vortex-v1, 40 × 2048-token windows, stride 1024 63.4129 58.1698

The issue's absolute 19.89 -> 19.13 is harness-dependent; the vortex artifact measures much higher under every long-context window here, while the adapter lowers PPL on every harness. The generator itself previously raised AttributeError: 'AutoNF12HookedLinear' object has no attribute 'weight'.

4. Post-quant EoRA with dynamic -: exclusions

DequantizeProcessor now receives the checkpoint qcfg (gptqmodel/models/base.py:2720) and implements is_skipped (dequantize_processor.py:59), so a module left dense by a -: rule is never popped from the quantized-weight map.

Fail-before (with AUTO_NF12 off, as in the issue): KeyError: 'model.layers.1.self_attn.q_proj' at dequantize_processor.py:69. Pass-after: adapter saved.

5. Rotation validation

rotate_model rotates embeddings, head, norms, and attention in place before reaching the MLP output. get_hadK then rejected Qwen2.5's intermediate_size=4864 with a bare AssertionError, leaving a half-rotated model.

flowchart TD
    A["quantize(rotation=...)"] --> B["validate_rotation_dimensions"]
    B --> C{"hadamard_supported(hidden_size)<br/>and hadamard_supported(intermediate_size)"}
    C -- no --> D["ValueError naming the dimension<br/>no weights modified"]
    C -- yes --> E["fuse_layer_norms"]
    E --> F["rotate_model"]
Loading
  • gptqmodel/quantization/rotation/hadamard_utils.py:73 hadamard_supported() asks the same get_hadK contract the transform uses, so the predicate cannot drift.
  • gptqmodel/quantization/rotation/rotation.py:27 raises ValueError naming the dimension; gptqmodel/models/base.py:2049 calls it before fuse_layer_norms and before untying the embeddings.

Qwen2.5-0.5B-Instruct, {"bits":4,"group_size":128,"rotation":"hadamard"}:

result weights changed
before AssertionError (bare) 173
after ValueError: ... intermediate_size=4864 has no exact Hadamard transform ... No weights were modified. 0

6. Staged GSQ fp16

A staged loss used F.mse_loss in the model dtype; FP16 (student - teacher)^2 overflows to inf. The relaxation exponent logits * multiplier (multiplier reaches hundreds) and the FP16 training logits also overflow, and torch._assert_async then poisons the CUDA context.

flowchart TD
    A["student / teacher outputs"] --> B["cast both to FP32"]
    B --> C["mse_loss"]
    C --> D["finite flag = isfinite(loss) and isfinite(grad)"]
    D --> E{"distributed?"}
    E -- yes --> F["GSQDistributed.check_finite<br/>all_reduce MAX"]
    E -- no --> G["read flag once"]
    F --> H{"any nonfinite?"}
    G --> H
    H -- yes --> I["RuntimeError (recoverable)"]
    H -- no --> J["optimizer.step()"]
Loading
  • gptqmodel/quantization/gsq_training.py:322 _stage_mse_loss widens the reduction to FP32.
  • gsq_training.py:70 evaluates the relaxation exponent in FP32 for FP16/BF16; FP64 keeps its dtype so the exact oracle is unchanged.
  • gsq_training.py:984 stores the trainable logits in FP32 (Q/K already did; every projection needs it for a half-precision model to finish).
  • gsq_training.py:573 raises a Python RuntimeError; gsq_distributed.py:164 check_finite keeps ranks in agreement.

Llama-3.2-1B-Instruct fp16, 32 docs × 96 tokens, epochs=1, qk_steps=20:

result
before CUDA error: device-side assert triggered (poisoned context)
after STATE complete blocks 16 secs=108.4, all validation losses finite

Validation

Commands run from the clone; PYTHONPATH=$PWD. CUDA venv /opt/venvs/cu130t, ROCm venv /opt/venvs/rocm101t.

CUDA (RTX 4090, GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42):

command result
pytest tests/test_requant_embed_lm_head_e2e.py -q 1 passed (before: 1 failed, META)
pytest tests/test_auto_nf12_excluded_layers.py -q -k "optimum_inclusion or post_quant_eora_generation" 3 passed (before: KeyError / AttributeError / KeyError)
pytest tests/test_gsq_training_math.py tests/test_gsq_staged_public.py -q 35 passed
pytest tests/test_rotation_persistence.py tests/test_requant_embed_lm_head.py -q 52 passed, 1 skipped
pytest tests/test_checkpoint_interop_4053.py -q (neighbour of the writer change) 12 passed
pytest tests/test_gsq_staged_public.py -q 25 passed
ruff check gptqmodel docs/eora tests setup.py All checks passed

ROCm (R9700, HIP_VISIBLE_DEVICES=2 only):

command result
pytest tests/test_gsq_training_math.py -q 10 passed
pytest tests/test_rotation_persistence.py -q -k "hadamard_supported or rotation_rejects" 2 passed
pytest tests/test_auto_nf12_excluded_layers.py -q -k "optimum_inclusion or post_quant_eora_generation" 3 passed
requantize BOTH + save + reload + forward + generate (Qwen2.5-0.5B) ROCm_FORWARD_OK, ROCm_GENERATE_OK

Limitations

  • On ROCm, the full test_requant_embed_lm_head_e2e.py requantizes successfully (1 layer(s), 2 module(s), 8s) but the second ARC evaluation (batch 64) hits a pre-existing dequant_kernel HSA memory fault in the TorchLinear path. The same requantized model forwards and generates correctly on ROCm (ROCm_FORWARD_OK, ROCm_GENERATE_OK); the full ARC run is not claimed.
  • The issue's absolute EoRA PPL numbers depend on its corpus/harness; the table above reports the measured values on wikitext-2 with the stated geometry.
  • modules_in_block_to_quantize is written as one group because Optimum flattens it with sum(..., []). Optimum loading only filters block layers by suffix; re-quantizing one of these checkpoints through Optimum itself would need the block-relative grouping, which is out of scope for a load-compatibility fix.

…n, GSQ (#4077)

- save_quantized writes modules_in_block_to_quantize for GPTQ checkpoints
  with dynamic `-:` rules, so Optimum leaves excluded modules dense instead
  of building uninitialized Marlin layers; the loader accepts full names.
- endpoint requantize re-resolves the live input/output/lm_head module after
  planning and before replay, so AUTO_NF12's swapped endpoint is not chased
  through a detached META reference.
- post-quant EoRA generation runs on dense native weights (AUTO_NF12 is
  disabled for that pass with a warning) and DequantizeProcessor honors the
  checkpoint's dynamic `-:` exclusions.
- rotation validates hidden_size/intermediate_size against get_hadK before
  fuse_layer_norms and raises a clear ValueError without touching weights.
- staged GSQ reduces losses in FP32, evaluates the relaxation exponent in
  FP32, keeps trainable logits in FP32, and raises a recoverable RuntimeError
  instead of torch._assert_async poisoning the CUDA context.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant