Skip to content

fix(fp8,foem): preserve packed save payloads and fix capture/block-boundary paths (#4037) - #4046

Merged
Qubitium merged 8 commits into
mainfrom
fix/issue-4037
Nov 14, 2026
Merged

Qubitium merged 8 commits into
mainfrom
fix/issue-4037

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4037

TL;DR

Three defects, one shared failure shape: a save/forward pass treated a packed
quantized payload as if it were a dense checkpoint tensor.

  1. FP8 save corruption (critical). With the default offload_to_disk=True,
    save() aliased the META weight buffer of every TorchFP8Linear from the
    dense source checkpoint, so the file held source weights next to the packed
    weight_scale_inv. Saved absmax 1.25 instead of 448.0; reloaded PPL
    8.16e38 instead of 2.67.
  2. GPTAQ / FOEM(alpha>0) crash under the default auto_nf12. The
    capture-only native pass left a parameterless AutoNF12HookedLinear in the
    model tree and the next processor died in next(module.parameters()).
  3. FOEM block-boundary correction was dead code. It targeted
    W[:, i2+1] after the inner loop ended, so the first column of every block
    after the first skipped beta.

Net: 4 commits, 6 files (+ docs page + README link), 5 new tests.

1. The problem

1.1 FP8 save: packed codes replaced by the source

TorchFP8Linear stores FP8 codes in a buffer named weight
(gptqmodel/nn_modules/qlinear/fp8.py, _allocate_buffers) — the same leaf
name as the source checkpoint tensor. Model.save() materialized every META
tensor from the lazy source before get_state_dict_for_save() could resolve
the offload bundle:

  • gptqmodel/models/writer.py:2088 alias_all_from_turtle_if_meta(...)
  • gptqmodel/models/writer.py:2092 _materialize_meta_layers_from_turtle(...)
  • gptqmodel/models/writer.py:2101 _materialize_remaining_meta_params_from_turtle(...)
  • gptqmodel/models/writer.py:2124 get_state_dict_for_save(...) (restore happens here)
  • gptqmodel/utils/structure.py sync_all_meta /
    _copy_checkpoint_tensors_into_submodule write leaves by checkpoint name
flowchart TD
    A["Model.save()"] --> B["alias_all_from_turtle_if_meta<br/>no skip list"]
    B --> C["FP8 META weight<br/>filled from dense source"]
    C --> D["get_state_dict_for_save"]
    D --> E{"tensor still META?"}
    E -- "no, source was materialized" --> F["saved: source weight<br/>next to packed scale"]
    F --> G["reload: scale mismatch<br/>PPL 8.16e38"]
    E -- yes --> H["saved: packed codes"]
    style F fill:#ffebee
    style G fill:#ffebee
Loading

The writer log line Total direct tensors materialized from lazy checkpoint source: 242 included all 168 FP8 linears. fp4.py registers the same
weight name, but its checkpoint source is the packed payload, so it is not
affected; the skip list still covers it if it ever declares QUANT_TYPE.

1.2 Forward-only AUTO_NF12 capture

NativeProcessor (GPTAQ, FOEM with alpha > 0) runs before the quantizer. Its
forward role called _maybe_auto_dtype_cast_forward_module
(gptqmodel/models/base.py:3915), which installs a parameterless
AutoNF12HookedLinear and records auto_dtype_cast_source_spec. The dense
source is restored only by a later quant_source pass, which a capture-only
processor never runs. The next processor then built NamedModule over the
wrapper: StopIteration at gptqmodel/looper/named_module.py:33.

flowchart LR
    N["NativeProcessor forward"] --> C["create_named_modules"]
    C --> P["AutoNF12HookedLinear<br/>parameterless, installed in tree"]
    P --> Q["GPTQProcessor NamedModule<br/>next(parameters())"]
    Q --> X["StopIteration"]
    style X fill:#ffebee
Loading

NativeProcessor declared its forward policy at
gptqmodel/looper/native_processor.py:33-38 with no way to say "do not pack".

1.3 FOEM block boundary

gptqmodel/quantization/foem.py:370-371 on the base commit:

if i+1 < count:
    W[:, i2+1] -= self.qcfg.foem.beta * (W[:, i2+1]-W_raw[:, i2+1])

After the inner loop i == count - 1, so the branch is unreachable; and the
next column is i2, not i2 + 1.

2. The new flow

2.1 Save ownership

flowchart TD
    A["Model.save()"] --> B{"load_quantized_model or<br/>EXL3 passthrough?"}
    B -- yes --> C["skip shell materialization"]
    B -- no --> D["_quantized_module_types(model)<br/>classes with QUANT_TYPE"]
    D --> E["alias_all_from_turtle_if_meta<br/>skip_module_types=..."]
    E --> F["_materialize_meta_layers_from_turtle<br/>skip_module_types=..."]
    F --> G["_materialize_remaining_meta_params_from_turtle<br/>skip_module_types=..."]
    G --> H["get_state_dict_for_save<br/>offload_root"]
    H --> I{"tensor still META?"}
    I -- yes --> J["_resolve_offload_entry<br/>packed codes from bundle"]
    I -- no --> K["live tensor"]
    J --> L["safetensors shard"]
    K --> L
    style C fill:#e8f5e9
    style J fill:#e8f5e9
    style K fill:#fff8e1
Loading

_quantized_module_types() collects the classes actually present in the model
that declare QUANT_TYPE, so a plugin quantizer is covered without a hardcoded
list. The skip list is threaded through sync_all_meta,
materialize_submodule, _copy_checkpoint_tensors_into_submodule, and the
parameter fallback. _copy_checkpoint_tensors_into_submodule filters by owner
module path, so a skipped module's weight, weight_scale_inv, and bias are
all left to the offload restore while dense neighbours materialize normally.

2.2 Forward-only capture

flowchart LR
    N["NativeProcessor forward<br/>allow_auto_dtype_cast=False"] --> C["create_named_modules"]
    C --> S["state: auto_dtype_cast_forward_disabled"]
    S --> M["_maybe_auto_dtype_cast_forward_module<br/>returns the dense module"]
    M --> T["model tree keeps dense source"]
    T --> Q["GPTQProcessor NamedModule<br/>next(parameters()).dtype"]
    style Q fill:#e8f5e9
Loading

ForwardConfig.allow_auto_dtype_cast is the declarative switch: True for
processors that later materialize a quantization source, False for
NativeProcessor. create_named_modules translates it into the existing
auto_dtype_cast_forward_disabled state key already honored for EoRA and for
replay of fully excluded layers.

2.3 FOEM block boundary

flowchart TD
    A["block i1 .. i2"] --> B["for i in block:<br/>quantize, update, correct column i+1"]
    B --> C{"i2 less than columns?"}
    C -- yes --> D["correct column i2<br/>before the next block"]
    C -- no --> E["last block, done"]
    D --> F["next block sees corrected first column"]
    style D fill:#e8f5e9
    style F fill:#e8f5e9
Loading

3. Before / after

Area Before After
writer.py:2088-2107 aliased every META tensor from the source skip_module_types=_quantized_module_types(model) on all three helpers
structure.py sync_all_meta / _copy_checkpoint_tensors_into_submodule wrote every leaf by checkpoint name filters tensors owned by a skipped module class
native_processor.py:33-38 default AUTO_NF12 packing allow_auto_dtype_cast=False
module_looper.py create_named_modules only EoRA disabled the cast any processor whose forward policy forbids it
foem.py:370-371 W[:, i2+1], unreachable W[:, i2] when i2 < columns

4. Failure and ambiguity contract

Situation Before After
Packed tensor META and in the offload bundle source weight written (silent corruption) packed codes written
Packed tensor META and missing from the bundle source weight written get_state_dict_for_save raises FileNotFoundError (fail-closed)
Packed tensor live (no offload) written as-is written as-is (skip list is a no-op)
Capture-only forward over a parameterless module StopIteration dense module stays in the tree; quantizer wraps it
FOEM beta=0 GPTQ-equivalent still GPTQ-equivalent

5. Change inventory

File +/- Purpose
gptqmodel/models/writer.py +47/-3 _quantized_module_types, skip threading, docstrings
gptqmodel/utils/structure.py +42/-0 skip_module_types on materialize_submodule / _copy_checkpoint_tensors_into_submodule, owner-path helpers
gptqmodel/looper/loop_processor.py +8/-0 ForwardConfig.allow_auto_dtype_cast
gptqmodel/looper/native_processor.py +5/-0 capture-only policy
gptqmodel/looper/module_looper.py +8/-0 translate the policy into the state key
gptqmodel/quantization/foem.py +8/-2 block-boundary correction
tests/test_fp8_save_offload.py new writer skip + FP8 round trip
tests/test_auto_dtype_cast.py +82 forward-only capture
tests/test_gptaq_foem_batch.py +44 FOEM blocksize invariance
docs/fp8-save-offload.md, README.md new/+5 reference page and link

6. Tests / guarantees

Test Invariant
test_fp8_save_offload.py::test_save_materialization_skips_packed_fp8_payload the writer skip tuple leaves a META FP8 weight for the offload restore; the control run shows the source replacing it
test_fp8_save_offload.py::test_fp8_default_offload_save_round_trip_keeps_packed_codes saved q_proj.weight bytes equal the packed codes; source absmax < 10; reloaded PPL < 50
test_fp8_save_offload.py::test_quantized_module_types_covers_fp8_payload_owner the skip list is derived from QUANT_TYPE
test_auto_dtype_cast.py::test_forward_only_processor_keeps_dense_modules_in_the_tree a capture-only forward leaves nn.Linear in the tree
test_auto_dtype_cast.py::test_native_processor_forward_forbids_auto_dtype_cast NativeProcessor declares the policy
test_gptaq_foem_batch.py::test_foem_block_boundary_beta_correction_is_blocksize_invariant FOEM beta reaches the first column of every block

7. Validation

CUDA: GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae (RTX 4090).
ROCm: HIP_VISIBLE_DEVICES=0 (R9700). nvidia-smi --query-compute-apps was
checked before the timing-free runs.

Item 1, before (Qwen2.5-0.5B-Instruct, METHOD.FP8, default offload):

in memory (offload bundle): weight absmax=448.0 scale_inv max=21716.0703125
saved: ...q_proj.weight float8_e4m3fn absmax=1.25
saved weight == in-memory packed codes: False
reloaded PPL = 816077216764108694193396281002946461696.0000

Item 1, after:

saved: ...q_proj.weight float8_e4m3fn absmax=448.0
saved weight == in-memory packed codes: True
saved scale == in-memory scale: True
reloaded PPL = 2.6707        (fp16 baseline 2.6947 on the same text)

Item 2, before (default auto_dtype_cast=auto_nf12): GPTAQ and
FOEM(alpha=0.25) both StopIteration at named_module.py:33. With
auto_dtype_cast=off GPTAQ quantizes OK (baseline). After: both quantize OK
with auto_nf12.

Item 3: synthetic 512-column linear, group_size=-1, beta=0.2, bits=4:

before: differing_weights=136 max_abs_diff=5.891e-3 loss128=0.230374 loss512=0.223945
after : differing_weights=0   max_abs_diff=0.000e+00 loss128=0.22394484 loss512=0.22394483

Commands and results:

Command CUDA ROCm
pytest tests/test_fp8_save_offload.py tests/test_fp8_packed_weight_lifecycle.py tests/test_fp8.py tests/test_gptaq_foem_batch.py tests/test_auto_dtype_cast.py tests/test_lazy_sync_packed_modules.py -q 87 passed 81 passed, 6 skipped (pre-existing "requires NVIDIA SM80")
pytest tests/test_offload_files.py -k "sync_all_meta or alias_all_from_turtle or alias_from_turtle or materialize" -q 20 passed —
pytest tests/test_lazy_turtle_conversion_mapping.py -k sync_all_meta -q 1 passed —
pytest tests/test_save_state_dict_buffer_collection.py tests/test_embedding_save_lifecycle.py tests/test_split_by_layer_save.py -q 14 passed, 3 skipped —
ruff check gptqmodel docs/eora tests setup.py All checks passed All checks passed

Fail-before was re-run for every new test by stashing the corresponding source
hunk; each failed with the expected assertion (max |dW| 5.89e-3, packed-bytes
mismatch, or StopIteration). An ordinary 4-bit GPTQ save with default offload
still round-trips qweight/qzeros/scales byte-exactly (reloaded PPL 1.36 vs
fp16 1.15 on a repetitive sanity text).

8. Reviewer notes

  • The skip list is derived from the model tree, not a hardcoded class tuple, so
    new quantizers that declare QUANT_TYPE are covered.
  • TorchFP4Linear (fp4.py) also registers weight, but its source checkpoint
    payload is the packed NVFP4 tensor, so the previous aliasing was a no-op
    there. It has no QUANT_TYPE today; the mechanism would cover it if added.
  • The FOEM fix keeps the correction instead of deleting it: the live in-block
    branch implements the same rule, so executing the block-boundary form is the
    smaller behavior change. beta=0 remains GPTQ-equivalent.
  • Remaining group_size=128 blocksize differences are floating-point summation
    order in the block-end aggregate (the grid is re-derived per group), not the
    missing correction; the regression test uses group_size=-1, where the grid
    is fixed before the loop.

…on (#4037)

TorchFP8Linear stores its packed codes in a buffer named `weight`, the same
leaf name as the dense source checkpoint tensor. The save path aliased every
META tensor from the lazy source before get_state_dict_for_save() could
restore the offload bundle, so with the default offload_to_disk=True the
packed weight was replaced by the source weight while weight_scale_inv stayed
packed. The saved checkpoint reloaded as garbage (PPL 8.16e38).

Pass the module classes present in the model that declare QUANT_TYPE as
skip_module_types through all three save-time materializers. Those modules'
tensors are left META and resolved from the offload bundle the quantizer
wrote; dense neighbours still materialize from the source as before.

Measured on Qwen2.5-0.5B-Instruct FP8, default offload: saved q_proj.weight
absmax 1.25 -> 448.0, bytes equal to the packed codes, reloaded PPL 8.16e38
-> 2.67 (fp16 baseline 2.69).
#4037)

NativeProcessor captures raw calibration inputs for GPTAQ and FOEM(alpha>0).
Its forward role ran _maybe_auto_dtype_cast_forward_module, which installs a
parameterless AutoNF12HookedLinear in the model tree and relies on a later
quant_source pass to restore the dense module. A capture-only pass never runs
that restore, so the next processor built NamedModule over the wrapper and
crashed in next(module.parameters()) (StopIteration, named_module.py:33).

Declare the policy on ForwardConfig as allow_auto_dtype_cast and set it False
on NativeProcessor. create_named_modules turns it into the existing
auto_dtype_cast_forward_disabled state key, so the capture forward consumes and
leaves the dense module the quantizer will wrap.

GPTAQ and FOEM(alpha>0) now quantize with the default auto_dtype_cast=auto_nf12
on Qwen2.5-0.5B-Instruct; both failed with StopIteration before the change and
still work with auto_dtype_cast=off.
…#4037)

FOEM pulls the next column back toward its raw value before that column is
quantized. The in-block form runs for columns i1+1..i2-1; the block-boundary
form targeted W[:, i2+1] after the inner loop had already ended
(i == count - 1), so it never executed. Every block after the first skipped
beta for its first column, which made the result depend on blocksize.

Apply the same correction to W[:, i2] when i2 < columns, after the block-end
aggregate update. Keeping the correction (rather than deleting it) preserves
the algorithm the live in-block branch already implements; beta=0 still
reduces to GPTQ.

Synthetic 512-column linear, group_size=-1, beta=0.2, bits=4: blocksize 128 vs
512 differed in 136 weights (max |dW| 5.89e-3, avg loss 0.230374 vs 0.223945)
and now differs in 0 weights (avg loss 0.22394484 vs 0.22394483).
…ycle (#4037)

Add docs/fp8-save-offload.md with the save-time materialization flow, the
offload-bundle ownership rule, the forward-only AUTO_NF12 boundary, and the
FOEM block-boundary correction. Link it from README.md next to the checkpoint
dtype preservation entry.
Use words instead of a raw `<` inside the Mermaid decision label so the
diagram renders on GitHub.
Link the reference page to PR #4046 so readers can find the rationale.
@Qubitium
Qubitium merged commit 9a53541 into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4037 branch November 14, 2026 18:32
Qubitium added a commit that referenced this pull request Nov 17, 2026
…4588)

The Metal kernel applies FOEM's beta correction only inside a group
(k + 1 < G). The host loop carried the next group forward without
correcting its first column, so the auto-selected MLX path kept the
pre-#4046 behaviour and diverged from the Torch path on Apple Silicon.

Apply the same boundary rule after the error propagation, before the next
group is quantized, and update the macOS-only Torch oracle the same way.
The Torch implementation is unchanged.

Add a Linux-runnable test that runs the MLX host loop against stand-in
MLX primitives with a recorder kernel and compares the next group's first
column to an independent float64 oracle.
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