Repository navigation
fix(fp8,foem): preserve packed save payloads and fix capture/block-boundary paths (#4037) - #4046
Merged
Merged
Conversation
…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
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.
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 #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.
offload_to_disk=True,save()aliased the METAweightbuffer of everyTorchFP8Linearfrom thedense source checkpoint, so the file held source weights next to the packed
weight_scale_inv. Saved absmax1.25instead of448.0; reloaded PPL8.16e38instead of2.67.auto_nf12. Thecapture-only native pass left a parameterless
AutoNF12HookedLinearin themodel tree and the next processor died in
next(module.parameters()).W[:, i2+1]after the inner loop ended, so the first column of every blockafter 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
TorchFP8Linearstores FP8 codes in a buffer namedweight(
gptqmodel/nn_modules/qlinear/fp8.py,_allocate_buffers) — the same leafname as the source checkpoint tensor.
Model.save()materialized every METAtensor from the lazy source before
get_state_dict_for_save()could resolvethe offload bundle:
gptqmodel/models/writer.py:2088alias_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:2124get_state_dict_for_save(...)(restore happens here)gptqmodel/utils/structure.pysync_all_meta/_copy_checkpoint_tensors_into_submodulewrite leaves by checkpoint nameflowchart 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:#ffebeeThe writer log line
Total direct tensors materialized from lazy checkpoint source: 242included all 168 FP8 linears.fp4.pyregisters the sameweightname, but its checkpoint source is the packed payload, so it is notaffected; the skip list still covers it if it ever declares
QUANT_TYPE.1.2 Forward-only AUTO_NF12 capture
NativeProcessor(GPTAQ, FOEM withalpha > 0) runs before the quantizer. Itsforward role called
_maybe_auto_dtype_cast_forward_module(
gptqmodel/models/base.py:3915), which installs a parameterlessAutoNF12HookedLinearand recordsauto_dtype_cast_source_spec. The densesource is restored only by a later
quant_sourcepass, which a capture-onlyprocessor never runs. The next processor then built
NamedModuleover thewrapper:
StopIterationatgptqmodel/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:#ffebeeNativeProcessordeclared its forward policy atgptqmodel/looper/native_processor.py:33-38with no way to say "do not pack".1.3 FOEM block boundary
gptqmodel/quantization/foem.py:370-371on the base commit:After the inner loop
i == count - 1, so the branch is unreachable; and thenext column is
i2, noti2 + 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_quantized_module_types()collects the classes actually present in the modelthat declare
QUANT_TYPE, so a plugin quantizer is covered without a hardcodedlist. The skip list is threaded through
sync_all_meta,materialize_submodule,_copy_checkpoint_tensors_into_submodule, and theparameter fallback.
_copy_checkpoint_tensors_into_submodulefilters by ownermodule path, so a skipped module's
weight,weight_scale_inv, andbiasareall 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:#e8f5e9ForwardConfig.allow_auto_dtype_castis the declarative switch:Trueforprocessors that later materialize a quantization source,
FalseforNativeProcessor.create_named_modulestranslates it into the existingauto_dtype_cast_forward_disabledstate key already honored for EoRA and forreplay 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:#e8f5e93. Before / after
writer.py:2088-2107skip_module_types=_quantized_module_types(model)on all three helpersstructure.pysync_all_meta/_copy_checkpoint_tensors_into_submodulenative_processor.py:33-38allow_auto_dtype_cast=Falsemodule_looper.pycreate_named_modulesfoem.py:370-371W[:, i2+1], unreachableW[:, i2]wheni2 < columns4. Failure and ambiguity contract
get_state_dict_for_saveraisesFileNotFoundError(fail-closed)StopIterationbeta=05. Change inventory
gptqmodel/models/writer.py_quantized_module_types, skip threading, docstringsgptqmodel/utils/structure.pyskip_module_typesonmaterialize_submodule/_copy_checkpoint_tensors_into_submodule, owner-path helpersgptqmodel/looper/loop_processor.pyForwardConfig.allow_auto_dtype_castgptqmodel/looper/native_processor.pygptqmodel/looper/module_looper.pygptqmodel/quantization/foem.pytests/test_fp8_save_offload.pytests/test_auto_dtype_cast.pytests/test_gptaq_foem_batch.pydocs/fp8-save-offload.md,README.md6. Tests / guarantees
test_fp8_save_offload.py::test_save_materialization_skips_packed_fp8_payloadweightfor the offload restore; the control run shows the source replacing ittest_fp8_save_offload.py::test_fp8_default_offload_save_round_trip_keeps_packed_codesq_proj.weightbytes equal the packed codes; source absmax< 10; reloaded PPL< 50test_fp8_save_offload.py::test_quantized_module_types_covers_fp8_payload_ownerQUANT_TYPEtest_auto_dtype_cast.py::test_forward_only_processor_keeps_dense_modules_in_the_treenn.Linearin the treetest_auto_dtype_cast.py::test_native_processor_forward_forbids_auto_dtype_castNativeProcessordeclares the policytest_gptaq_foem_batch.py::test_foem_block_boundary_beta_correction_is_blocksize_invariantbetareaches the first column of every block7. Validation
CUDA:
GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae(RTX 4090).ROCm:
HIP_VISIBLE_DEVICES=0(R9700).nvidia-smi --query-compute-appswaschecked before the timing-free runs.
Item 1, before (Qwen2.5-0.5B-Instruct,
METHOD.FP8, default offload):Item 1, after:
Item 2, before (default
auto_dtype_cast=auto_nf12): GPTAQ andFOEM(alpha=0.25) both
StopIterationatnamed_module.py:33. Withauto_dtype_cast=offGPTAQ quantizes OK (baseline). After: both quantize OKwith
auto_nf12.Item 3: synthetic 512-column linear,
group_size=-1,beta=0.2,bits=4:Commands and results:
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 -qpytest tests/test_offload_files.py -k "sync_all_meta or alias_all_from_turtle or alias_from_turtle or materialize" -qpytest tests/test_lazy_turtle_conversion_mapping.py -k sync_all_meta -qpytest tests/test_save_state_dict_buffer_collection.py tests/test_embedding_save_lifecycle.py tests/test_split_by_layer_save.py -qruff check gptqmodel docs/eora tests setup.pyFail-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-bytesmismatch, or
StopIteration). An ordinary 4-bit GPTQ save with default offloadstill round-trips
qweight/qzeros/scalesbyte-exactly (reloaded PPL 1.36 vsfp16 1.15 on a repetitive sanity text).
8. Reviewer notes
new quantizers that declare
QUANT_TYPEare covered.TorchFP4Linear(fp4.py) also registersweight, but its source checkpointpayload is the packed NVFP4 tensor, so the previous aliasing was a no-op
there. It has no
QUANT_TYPEtoday; the mechanism would cover it if added.branch implements the same rule, so executing the block-boundary form is the
smaller behavior change.
beta=0remains GPTQ-equivalent.group_size=128blocksize differences are floating-point summationorder 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 gridis fixed before the loop.