Repository navigation
fix(features): honor GPTQ dynamic exclusions and repair AUTO_NF12/EoRA/rotation/GSQ (#4077) - #4086
Merged
Merged
Conversation
…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.
# Conflicts: # README.md
# Conflicts: # README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4077
Audit of
main@ad0525c; branch based on39b62765e, merged withorigin/main@701e58b9f. All six items are fixed with a fail-before / pass-after regression test, on CUDA and ROCm.TL;DR
dynamic-:loads as garbage in plain HFconfig.jsoncarried nomodules_in_block_to_quantize, so Optimum quantized every block layer and built an uninitializedMarlinLinearfor excluded modulessave_quantizedwrites the explicit quantized full-name set; the loader accepts full namesrequantize(embed_quant_mode=INPUT/BOTH)crashes under AUTO_NF12AutoNF12HookedLinearhas noweight; EoRA needs densew - wqandwq + BAKeyErrorwithdynamic-:DequantizeProcessor(qcfg=None)popped modules that were never quantizedqcfg; skip modules whose dynamic rule isFalsefuse_layer_normshidden_size/intermediate_sizeagainstget_hadKfirst; raise a clearValueErrortorch._assert_asyncpoisons the contextRuntimeError1. GPTQ
dynamic-:exclusions and plain HF loadingOptimum decides which modules to quantize from
quantization_config.modules_in_block_to_quantizeand matches entries withname.endswith. A GPTQ checkpoint withdynamic={"-:...": {}}used to serialize only the exclusion regex, so a plainAutoModelForCausalLMload builtMarlinLinearwith an uninitializedqweightfor 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"]gptqmodel/models/writer.py:258computesfind_modules(model, layers=[BaseQuantLinear])and writes one group[[full names]](Optimum flattens withsum(..., []), so a flat string list raisesTypeError).gptqmodel/models/loader.py:2462andgptqmodel/models/writer.py:2404accept a block-relative or full name, so GPTQModel reload still honors the same payload.gptqmodel/quantization/config.py:4747addshas_dynamic_exclusions(); the key is written only for GPTQ checkpoints with-:rules.Tiny-Llama HF check (
AutoModelForCausalLM.from_pretrained+ optimum 2.3.0):MarlinLinear0.011763nn.Linear0.0000002. Endpoint requantize under AUTO_NF12
The input-embedding pseudo-layer is the projection. AUTO_NF12 replaces
NamedModule.modulewith anAutoNF12Embedding; deferred dense-source materialization replaces it again with a densenn.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 endpointgptqmodel/looper/stage_layer.py:247adds_resolve_live_endpoint_module; it is called after planning (:976) and again after the subset passes (:1106) for input embeddings, output embeddings, andlm_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:origin/main)1 failed in 19.29s—RuntimeError: Lazy forward direct-state materialization left META tensors under ``.1 passed in 45.72s3. Post-quant EoRA under AUTO_NF12
EoRA needs dense native weights twice:
w - wqandwq + BAinstalled back into the module.AutoNF12HookedLinearhas noweight, soadapter.generatenow 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 adaptergptqmodel/looper/dequantize_processor.py:68also decodes a packed source throughdequantize_weightwhen a caller supplies one directly (NF12 stores BF16 exactly), andgptqmodel/looper/eora_processor.py:159takes the hook device from the module buffers instead of.weight.EoRA r64, 512 calibration rows,
Llama-3.2-1B-Instruct(wikitext-2 PPL):...-GPTQ-4bits-gp32, 16 docs × 256 tokens...-gptqmodel-4bit-vortex-v1, 16 docs × 256 tokens...-vortex-v1, 40 × 2048-token windows, stride 1024The issue's absolute
19.89 -> 19.13is 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 raisedAttributeError: 'AutoNF12HookedLinear' object has no attribute 'weight'.4. Post-quant EoRA with
dynamic-:exclusionsDequantizeProcessornow receives the checkpointqcfg(gptqmodel/models/base.py:2720) and implementsis_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'atdequantize_processor.py:69. Pass-after: adapter saved.5. Rotation validation
rotate_modelrotates embeddings, head, norms, and attention in place before reaching the MLP output.get_hadKthen rejected Qwen2.5'sintermediate_size=4864with a bareAssertionError, 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"]gptqmodel/quantization/rotation/hadamard_utils.py:73hadamard_supported()asks the sameget_hadKcontract the transform uses, so the predicate cannot drift.gptqmodel/quantization/rotation/rotation.py:27raisesValueErrornaming the dimension;gptqmodel/models/base.py:2049calls it beforefuse_layer_normsand before untying the embeddings.Qwen2.5-0.5B-Instruct,{"bits":4,"group_size":128,"rotation":"hadamard"}:AssertionError(bare)ValueError: ... intermediate_size=4864 has no exact Hadamard transform ... No weights were modified.6. Staged GSQ fp16
A staged loss used
F.mse_lossin the model dtype; FP16(student - teacher)^2overflows toinf. The relaxation exponentlogits * multiplier(multiplier reaches hundreds) and the FP16 training logits also overflow, andtorch._assert_asyncthen 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()"]gptqmodel/quantization/gsq_training.py:322_stage_mse_losswidens the reduction to FP32.gsq_training.py:70evaluates the relaxation exponent in FP32 for FP16/BF16; FP64 keeps its dtype so the exact oracle is unchanged.gsq_training.py:984stores the trainable logits in FP32 (Q/K already did; every projection needs it for a half-precision model to finish).gsq_training.py:573raises a PythonRuntimeError;gsq_distributed.py:164check_finitekeeps ranks in agreement.Llama-3.2-1B-Instructfp16, 32 docs × 96 tokens,epochs=1, qk_steps=20:CUDA error: device-side assert triggered(poisoned context)STATE complete blocks 16 secs=108.4, all validation losses finiteValidation
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):pytest tests/test_requant_embed_lm_head_e2e.py -qpytest tests/test_auto_nf12_excluded_layers.py -q -k "optimum_inclusion or post_quant_eora_generation"pytest tests/test_gsq_training_math.py tests/test_gsq_staged_public.py -qpytest tests/test_rotation_persistence.py tests/test_requant_embed_lm_head.py -qpytest tests/test_checkpoint_interop_4053.py -q(neighbour of the writer change)pytest tests/test_gsq_staged_public.py -qruff check gptqmodel docs/eora tests setup.pyROCm (R9700,
HIP_VISIBLE_DEVICES=2only):pytest tests/test_gsq_training_math.py -qpytest tests/test_rotation_persistence.py -q -k "hadamard_supported or rotation_rejects"pytest tests/test_auto_nf12_excluded_layers.py -q -k "optimum_inclusion or post_quant_eora_generation"ROCm_FORWARD_OK,ROCm_GENERATE_OKLimitations
test_requant_embed_lm_head_e2e.pyrequantizes successfully (1 layer(s), 2 module(s), 8s) but the second ARC evaluation (batch 64) hits a pre-existingdequant_kernelHSA 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.modules_in_block_to_quantizeis written as one group because Optimum flattens it withsum(..., []). 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.