Skip to content

fix(nf12): keep excluded-layer replay dense and fail closed on leaked AUTO_NF12 buffers (#4007) - #4012

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4007
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4007

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4007

TL;DR

A dynamic rule that excludes every module of a non-final layer used to leave AUTO_NF12 source storage installed in that layer, so save() wrote nf12_packed / nf12_escapes / nf12_exp_base instead of weight while quantize_config.json declared the layer unquantized, and reloading produced NaN logits. Two changes: the excluded-layer replay no longer installs NF12 storage, and save() now refuses to write nf12_* buffers for a module the config does not declare as NF12. +79 lines of code, +1 test module, +1 docs page.

1. The problem

An excluded layer still runs one forward so the next layer receives activations (replay_skipped_layer, gptqmodel/looper/stage_layer.py:1060). That replay prepared each projection through the forward role, which is the role that packs a dense source into NF12.

flowchart TD
    A["stage_layer.py:1060 replay_skipped_layer"] --> B["_prepare_layer_direct_state_for_forward"]
    B --> C["_prepare_named_module_for_forward"]
    C --> D["shell_module_materialize role=forward"]
    D --> E["base.py:3529 _maybe_auto_dtype_cast_forward_module"]
    E --> F["cast_source_module installs AutoNF12HookedLinear"]
    F --> G["_replay_layer_outputs advances inputs"]
    F --> H["save(): nf12_* keys, no weight"]
    H --> I["reload: dense weight uninitialised"]
    I --> J["NaN logits"]
    style H fill:#fee,stroke:#c00
    style I fill:#fee,stroke:#c00
    style J fill:#fee,stroke:#c00
Loading

The dense restore only happens on the role == "quant_source" path (gptqmodel/models/base.py:4625), which an excluded layer never takes.

Before/after of the mechanisms involved:

Mechanism Before After
Excluded-layer replay module prep (stage_layer.py:1088) no state flag, forward role packs state["auto_dtype_cast_forward_disabled"] = True (stage_layer.py:1100)
_maybe_auto_dtype_cast_forward_module (base.py:3529) flag checked (base.py:3548) but never set for this replay flag now set, returns the dense module unchanged
save_quantized (writer.py:2104) wrote whatever the tree held _validate_nf12_payload_ownership raises for undeclared NF12 payloads
save_quantized_embeddings (writer.py:1678) same same guard, scoped to the replacement prefixes

Measured on the issue's repro (tiny BF16 Llama, 4 layers, dynamic={"-:.*layers\\.1\\..*": {}}, GPTQ 4-bit group 32):

State Saved layer-1 keys Reloaded logits rel-err
Before mlp.up_proj.nf12_packed, .nf12_escapes, .nf12_exp_base nan
Before, auto_dtype_cast="off" mlp.up_proj.weight 0.0384
After mlp.up_proj.weight 0.0384

2. The new flow

flowchart TD
    A["stage_layer.py:1060 replay_skipped_layer"] --> B["NamedModule for each projection"]
    B --> C["state auto_dtype_cast_forward_disabled = True"]
    C --> D["_prepare_named_module_for_forward"]
    D --> E["shell_module_materialize role=forward"]
    E --> F{"base.py:3548 flag set?"}
    F -- Yes --> G["dense source module, no cast"]
    F -- No --> H["quantized-subset path still packs, then quant_source restores"]
    G --> I["_replay_layer_outputs advances inputs"]
    H --> I
    I --> J["save(): dense weight, no nf12_* keys"]
    style G fill:#dfd,stroke:#080
    style J fill:#dfd,stroke:#080
Loading

The flag is set only on the wrappers this replay creates, so the quantized-subset path keeps packing its source and keeps restoring it through quant_source.

3. Save contract (fail closed)

flowchart TD
    A["save_quantized / save_quantized_embeddings"] --> B["_validate_nf12_payload_ownership writer.py:436"]
    B --> C{"module has nf12_* buffers?"}
    C -- No --> G["stream shards"]
    C -- Yes --> D["_module_declares_nf12_checkpoint writer.py:418"]
    D --> E{"resolved format is NF12 and the dynamic rule is not excluded?"}
    E -- Yes --> G
    E -- No --> F["ValueError: Save aborted"]
    style F fill:#fee,stroke:#c00
    style G fill:#dfd,stroke:#080
Loading

With the guard in place and the replay fix reverted, save() raises:

ValueError: Save aborted: AUTO_NF12 source storage is still installed on modules the
quantize config does not declare as NF12 (`model.layers.1.mlp.down_proj,
model.layers.1.mlp.gate_proj, model.layers.1.mlp.up_proj, model.layers.1.self_attn.k_proj,
model.layers.1.self_attn.o_proj, model.layers.1.self_attn.q_proj,
model.layers.1.self_attn.v_proj`). Saving would write `nf12_*` buffers in place of
`weight` for those modules, and reloading the checkpoint would leave their dense weights
uninitialised (NaN logits). Restore the dense source module before saving.

4. Change inventory

Area File +/- Purpose
Looper gptqmodel/looper/stage_layer.py +7 Disable AUTO_NF12 casting for the excluded-layer replay
Writer gptqmodel/models/writer.py +72 Fail-closed NF12 payload ownership check on both save paths
Tests tests/test_auto_nf12_excluded_layers.py +270 GPU end-to-end save/reload cases and CPU guard cases
Docs docs/auto-nf12-excluded-layers.md +117 Flow, save contract, measured numbers
Docs README.md +4/-1 Link the new page next to the AUTO_NF12 description

5. Tests

tests/test_auto_nf12_excluded_layers.py:

Test Invariant
test_fully_excluded_non_final_layer_saves_dense_weights[layers0/1/2/1+2-gptq/awq] Excluded non-final layer saves *.weight, no nf12_*, reloads finite with rel-err < 0.5, remaining layers still quantized
test_other_exclusions_never_serialize_nf12_buffers[last-layer/single-module/sub-block/cast-off] The unaffected cases stay unaffected
test_save_guard_rejects_nf12_buffers_under_an_excluded_module Writer fails closed for an excluded path
test_save_guard_rejects_nf12_buffers_for_a_non_nf12_config A GPTQ config never serializes NF12 storage
test_save_guard_allows_modules_the_config_declares_as_nf12 A real NF12Config checkpoint still saves
test_save_guard_ignores_modules_outside_the_requested_prefixes The module-replacement path only validates its own prefixes

Fail-before (fix reverted, guard reverted):

$ git checkout -- gptqmodel/looper/stage_layer.py gptqmodel/models/writer.py
$ PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e \
    /opt/venvs/cu130t/bin/python -m pytest tests/test_auto_nf12_excluded_layers.py -q -p no:randomly \
    -k "excluded_non_final or other_exclusions"
E   AssertionError: checkpoint serialized AUTO_NF12 source storage: ['model.layers.0.self_attn.q_proj.nf12_packed', 'model.layers.0.self_attn.q_proj.nf12_escapes', 'model.layers.0.self_attn.q_proj.nf12_exp_base', ...]
8 failed, 4 passed, 4 deselected

Pass-after (CUDA, merged with current origin/main):

$ PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e \
    /opt/venvs/cu130t/bin/python -m pytest tests/test_auto_nf12_excluded_layers.py \
    tests/test_auto_dtype_cast.py tests/test_nf12_codec.py tests/test_writer_dynamic_order.py \
    tests/test_embedding_save_lifecycle.py tests/test_offload_files.py -q -p no:randomly
211 passed, 9 skipped

Pass-after (ROCm):

$ HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
    tests/test_auto_nf12_excluded_layers.py -q -p no:randomly
16 passed

Lint:

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

6. Reviewer notes

  • The replay flag is the minimal fix: the excluded layer is only replayed to advance calibration inputs, so it must stay dense. restore_source_module after the replay would also work but would pack and immediately unpack the source.
  • The save guard is deliberately a hard error, not a warning: a checkpoint that mixes nf12_* payloads with an unquantized config cannot be reloaded correctly by any loader.
  • Scope: the flag covers the replay_skipped_layer branch only. The legacy catchup replay (stage_layer.py:693) is unchanged; it restores already-packed modules whose live tree entry already reports QUANT_TYPE, so the cast is skipped there by the existing check at base.py:3559.
  • Limitation: the guard validates the model tree, so it also rejects a hand-built module that keeps nf12_* buffers with empty storage; that state would still serialize NF12 keys without a weight, so failing is intended.

gptqmodel-agent and others added 2 commits November 14, 2026 14:59
… AUTO_NF12 buffers (#4007)

A dynamic `-:` rule that excludes every module of a non-final layer still
replays that layer once so the next decoder layer receives activations. The
replay prepared its projections through the `forward` role, which installs
AUTO_NF12 source storage, but an excluded layer never takes the `quant_source`
role that restores the dense module. The packed modules stayed in the model
tree, so save() wrote nf12_packed/nf12_escapes/nf12_exp_base instead of weight
while quantize_config.json declared the layer unquantized; a reload left the
dense weights uninitialised and produced NaN logits.

- Disable AUTO_NF12 casting for the excluded-layer replay only
  (stage_layer.py replay_skipped_layer).
- Make save() raise when nf12_* buffers belong to a module the config does not
  declare as NF12, so this corruption can never ship silently.
- Add GPU regression coverage for layers 0, 1, 2 and 1+2 with GPTQ and AWQ,
  plus the last-layer, single-module, sub-block and auto_dtype_cast=off cases.
- Document the flow and the fail-closed save contract.
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.

[BUG] auto_nf12: a fully excluded non-final layer is saved as NF12 buffers under nn.Linear names -> reload yields NaN logits

1 participant