Repository navigation
fix(w4a): stop caching the E4M3 weight expansion - #3459
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Existing TorchLinear callers now fail during decoding, while lifecycle tests permit prohibited caches, undercount staging memory, and omit cast and device-round-trip coverage.
5 open issues
Resolve decoder helpers on W4AFP8Linear for generic callers · New Avoid per-group CUDA staging and unpacking launch overhead · New Integer and E4M3 cache bypasses evade storage validation · New Restore dtype, encoding, and device-round-trip lifecycle coverage · New Transient-memory estimate omits live INT32 intermediates · New
What changed in this PR
This PR replaces resident expanded FP8 weight caches with per-forward staging in W4A inference, while preserving native GPTQ checkpoint storage and packed NVFP4 operands.
Changes:
- Builds temporary E4M3 operands for plain and pre-encoded FP8 inputs.
- Adds initialization readiness tracking and defers FP4 kernel imports until needed.
- Updates lifecycle tests, independent numerical checks, and storage documentation.
Native GPU validation and decode-latency measurements remain pending.
| File | Description |
|---|---|
tests/models/test_w4a_tiny_llama_lifecycle.py |
Updates mixed-precision model storage assertions. |
tests/kernels/test_w4afp8_gb10.py |
Checks temporary FP8 operands and unchanged checkpoint contents. |
tests/kernels/test_w4a_stream.py |
Uses per-call operands in sharded-device checks. |
tests/kernels/test_w4a_nvfp4_gb10.py |
Checks transient FP8 operands alongside packed FP4 state. |
tests/kernels/test_w4a_cache_lifecycle.py |
Adds CPU lifecycle, operand-release, storage, and oracle checks. |
gptqmodel/nn_modules/qlinear/w4a_nvfp4.py |
Updates FP8 dispatch while retaining packed FP4 operands. |
gptqmodel/nn_modules/qlinear/w4a_floatx.py |
Replaces the FP8 cache with grouped per-forward staging. |
docs/gptq-w4a-accuracy-notes.md |
Revises the weight-staging and persistence description. |
Review effort: Max
72ea129 to
2a4e028
Compare
c289aca to
7ab55b8
Compare
W4AFP8Linear.post_init() built a full-layer E4M3 tensor (_weight_e4m3) from the native GPTQ INT4 codes and kept it on the module between forwards. That violates the repository storage gate: an E4M3 plane derived from INT4 codes is an expanded weight cache (1 byte/weight on top of the packed qweight), not a packed layout, and it survived every inference call. W4AFP8Linear now materializes the E4M3 operand inside forward() from the native INT4 codes, passes it straight to the GEMM, and drops the reference when the call returns. post_init() validates the layout and records readiness without building any tensor. forward() rejects a stale layout instead of decoding it. Two costs had to be removed to keep this from being a pure regression. The per-128-row-group decode is gone. It issued roughly seven Torch dispatches per group, so a K=8192 projection queued ~448 kernels per token; on RTX 4090 the loop was CPU-launch-bound at ~4.3 us per launch with the device idle. The loop cost is flat in the layer payload, 535 us for a 16-group layer and 2.30 ms for the 64-group K=8192 layer, which made it 10-14x a whole-layer decode on the smaller projections. Decoding the layer in one shot is byte-identical with a handful of launches. The decode also no longer goes through int32. A packed word is 32 bits holding eight nibbles, so shifting and masking the int32 values materialized a 4 B/weight plane for each step and moved ~337 MiB per K=8192 layer at the 4090's ~940 GB/s effective bandwidth. That is a bandwidth cost, not a launch cost, so it scales with the weight count. _unpack_int4_codes() now reads the same words through a uint8 view, which keeps every intermediate at 1 B/weight (~157 MiB per K=8192 layer). Measured on a quiet RTX 4090 with both forms interleaved in one process: 2048x8192 374.7 us -> 175.1 us (2.14x) and 8192x2048 374.6 us -> 175.3 us (2.14x), byte-identical output, and the transient staging peak falls from 8 B/weight to 5. Validation moved off the decode path. _check_native_weight_layout() runs torch.equal plus an all-reduce, both of which synchronize the device, so calling it on the decode path cost a GPU sync per token (measured on RTX 4090: 69-78 us for the check against 39-47 us for the identical decode on the small and mid projections). Readiness is now keyed on the qweight/qzeros/g_idx version counters (_weights_are_current). _centered_int4_codes() is a classmethod usable on any GPTQ module, so the existing TorchLinear checkpoint audits keep working; qzeros packs its nibbles along the output axis, unlike qweight, so it keeps the shift form there. Scope is FP8/SM 8.9+ only; NVFP4 needs SM 12.1 and keeps its existing resident staging in this PR. Tests: rewrite tests/kernels/test_w4a_cache_lifecycle.py around the persistent-state contract. It drives the real forward dispatch on CPU with kernel stand-ins, then scans buffers/parameters/__dict__ by representation (size, not dtype or attribute name) and asserts the per-forward operand is collectable after gc. Three negative controls prove the scanner still catches a full-layer INT8/INT16 plane, an E4M3 plane parked under a packed-cache name, and does not flag the native checkpoint or the packed FP4 layout. Numeric checks use an independent Torch oracle that unpacks the qweight words itself. New tests pin the byte-level unpack against the int32 shift oracle over random words and check the low-nibble-first ordering at every position. Validated on 2x RTX 4090 (SM 8.9), Triton 3.9.0: 48 passed / 6 skipped across test_w4afp8_gb10, test_w4a_stream and test_w4a_cache_lifecycle. Per-token cost at Llama-3.2-1B shapes (16 layers) remains above the resident-cache baseline (18.7 ms vs 6.7 ms, 2.8x), because staging still has to read the packed weights and write E4M3 on every step. The trade is deliberate: the packed checkpoint stays the only resident copy, and a Llama-3.2-1B deployment drops 973 MB of standing device memory. Closing the latency gap needs a single fused Triton kernel that reads qweight and writes E4M3 directly; plain Torch dispatch cannot reach it.
7ab55b8 to
1c20501
Compare
`_centered_int4_codes()` called `self._unpack_int4_codes(...)`, but the
documented cross-module entry point is
`W4AFP8Linear._centered_int4_codes(torch_linear_module)`: the method is
invoked on the class with a foreign GPTQ module as `self`. A
`TorchLinear` has no `_unpack_int4_codes`, so every checkpoint audit path
(`w4a_weight_replay_audit.py`, `w4a_nvfp4_weight_qad.py`,
`w4a_nvfp4_scale_qad.py`, `w4a_nvfp4_scale_reconstruct.py`) raised
`AttributeError` instead of decoding.
Move the unpacker to module scope as `unpack_int4_codes()` and call it
directly. `W4AFP8Linear._unpack_int4_codes` stays as a thin class-level
alias so existing callers keep working.
Reproduced before the fix on CPU:
AttributeError: 'TorchLinear' object has no attribute '_unpack_int4_codes'
Tests: parametrize the cross-module path
(`test_centered_codes_works_on_foreign_gptq_module`), which asserts a
`TorchLinear` has no helper of its own and pins the decoded codes against
the int32 shift oracle. 61 passed / 46 skipped on 2x RTX 4090.
|
@copilot review |
Review found one actionable issue: inference tensors have no version counter, so an in-place |
github-code-quality flagged `assert peak_delta != 2 * 65536 or peak_delta >= floor` as vacuous, because the assertion on the preceding line already requires `peak_delta >= floor`. That was correct: with the measured peak at exactly 163840 B, the right operand of the `or` can never be false. Its suggested replacement, `assert peak_delta != 2 * 65536`, is vacuous for the same reason -- `peak_delta >= 163840` already implies it is not 131072 -- so it would have removed the redundancy without adding any constraint. Replace both with an upper bound instead. The lower bound alone cannot detect a staging path that regresses to the old int32 form or that starts leaking the operand past the call; comparing against the superseded 65536 B constant cannot detect anything at all. One allocator block of slack (K * N) covers rounding. Verified the new bound is not vacuous by swapping the unpacker back to the int32 shift form: peak goes 163840 B (5.00 B/weight) -> 262656 B (8.02 B/weight), which the upper bound rejects. 49 passed / 6 skipped on 2x RTX 4090.
Copilot's review found that inference tensors have no version counter, so
an in-place `qzeros` write performed under `torch.inference_mode()` leaves
`_weight_layout_token()` unchanged and `forward()` keeps assuming zero
point 8. It also noted `W4AFP8Linear` exposes no explicit invalidation
path for that case.
Confirmed on CPU before the fix. Anything built inside `inference_mode()`
has `is_inference() == True` and a token of `(ptr, None)`, so filling
`qzeros` with 0 leaves the token byte-identical:
zero points still 8? False
token UNCHANGED? True
weights_current: True <- stale layout accepted
FORWARD ACCEPTED STALE LAYOUT
That is worse than the review's wording: `forward()` does not merely keep
assuming zero point 8, it returns an incorrect result without raising.
`.agents/skills/gptqmodel-torch-oracle-numerics/SKILL.md` requires the
explicit-clear contract for exactly this case: "Exercise the shared
explicit-clear contract for inference tensors without version counters."
The only invalidation entry point was the private
`_invalidate_weight_cache()`, so the contract was unreachable for callers.
Additions:
- `invalidate_weight_layout()`: public hook that drops readiness and makes
`forward()` raise until `post_init()` runs again.
- `_layout_token_is_observable()`: true only when every layout-defining
tensor tracks in-place writes.
- `_warn_unobservable_layout()`: one-shot warning naming the explicit hook.
The unobservable case is not revalidated per forward on purpose. Doing so
would put `torch.equal` plus the all-reduce back on the decode path, which
is the GPU sync this PR removes; a warning once per module plus the public
hook keeps the decode path clean.
Tests: `test_invalidate_weight_layout_forces_revalidation` pins the public
hook, `test_inference_tensor_layout_is_reported_as_unobservable` records
the blind spot and proves in-place `qzeros` writes leave the token
unchanged, and `test_observable_layout_is_reported_for_normal_construction`
keeps the normal path unflagged.
Verified the warning fires once across five forwards on an inference-tensor
module and never on a normally constructed one. 64 passed / 46 skipped on
2x RTX 4090; ruff clean.
|
Confirmed, fixed in Also reachable without unusual user code — building the module inside The skill already requires this contract ("explicit-clear contract for inference tensors without version counters"), but only the private
I did not revalidate per forward: that would restore the Tests: blind spot recorded (in-place @Qubitium could you re-review? Head is
|
land the fused kernel |
OK |
Per-forward weight staging was the remaining cost of not caching an E4M3
plane: the Torch decode has to materialize intermediate planes that the
fused path never allocates at all.
Add `w4a_triton.unpack_int4_to_e4m3`. It reads the packed int32 words,
extracts the eight nibbles per word with register shifts, and writes E4M3
directly into a caller-owned buffer, so the decode is one kernel and the
only allocation is the operand the GEMM consumes. `fp8_weight_operand`
uses it whenever the packed words are int32 on CUDA; the Torch decode
stays for CPU/meta weights and remains the reference the kernel is
pinned against.
Byte identity is asserted on four random shapes plus the all-zero and
all-ones words, and the staging peak test now bounds the fused path at
1 B/weight instead of the 5 B/weight the Torch decode needs.
Measured on a quiet RTX 4090, CUDA events around a loop of calls, all
three paths in one process and interleaved:
pure decode, no GEMM 2048x2048 2048x8192
Torch decode 46.7 us 175.8 us
fused 13.5 us 13.6 us
speedup 3.47x 12.90x
forward, per token x16 layers x 7 projections
resident E4M3 plane (main) 4.85 ms
Torch staging per forward 15.21 ms
fused staging per forward 6.37 ms
The fused path is 2.39x faster than the per-forward Torch staging it
replaces; it still pays 1.31x over the resident plane main keeps, which
is the price of not persisting an expansion of the packed weights.
|
Fused kernel landed in
RTX 4090, CUDA events around a loop of calls, all three paths interleaved in one process, idle GPU:
Compliant path is now 1.31x the illegal resident cache, down from 3.14x. Pure decode, no GEMM: 2048x8192 175.8 us -> 13.6 us (12.9x); 8192x2048 176.1 us -> 13.5 us (13.0x). Transient peak 5.00 -> 1.00 B/weight (allocator-sampled). Byte-identical to the Torch oracle on 4 random shapes plus all-zero/all-ones words. Tests: @Qubitium could you re-review? Head is
|
|
@copilot review |
Re-reviewed the latest head. The inference-tensor blind spot is addressed by |
* fix(w4a): revalidate the packed layout in NVFP4 post_init W4ANVFP4Linear.post_init calls PackableQuantLinear.post_init directly and stages its own operand caches, so it never ran the native-layout checks that moved into _check_native_weight_layout in #3459. A desc_act group map or a non-symmetric zero point was decoded silently into the FP8/FP4 operands. Restore the shared validation before _centered_int4_codes, matching the checks the old decode used to perform, and cover both rejections on CPU. * fix(w4a): truthful qzero format bookkeeping on pack/load paths + drop stale operand caches on re-init - hf_pack_layer: mark raw-packer output as the v2 (logical zero point) layout it actually produces, and only convert to the v1 checkpoint convention (stored zp-1) for kernels that require the v2 runtime layout, matching pack_module. Previously a gptq_v2 request added one to already-v2 words and a gptq request skipped the needed v1 conversion, so NVFP4 post_init rejected freshly packed layers. - loader: mark GPTQQuantLinear modules format=2 after loading a native GPTQ_V2 checkpoint; the flag previously kept its format=1 default even though no v1->v2 conversion ran, so format-aware decoders read every zero point one high. - W4AFP8Linear/W4ANVFP4Linear post_init: invalidate staged operand caches before validating, so a failed re-post_init leaves forward() unusable instead of serving operands from a stale layout. - W4AFP8Linear: mark format=2 in pack_block/pack_gpu/pack_original like pack() already did, covering the pack_module entry points that bypass pack(). - Tests: NVFP4 hf_pack_layer regression for both checkpoint flavors, failed re-post_init cache-clearing coverage, and updated reuse/ pack-parity expectations for the corrected format bookkeeping. * fix(gptq): per-field v1<->v2 qzero shifts and post-init format restore Review follow-ups: - convert_gptq_v1_to_v2/v2_to_v1_format_module: use the field-aware _correct/_revert helpers for bits 2/4/8 (and int32 INT3); a packed-word +-1 borrows/carries across fields, corrupting zero points at field boundaries. - hf_pack_layer(post_init=True): restore the v2 runtime layout after a v1-checkpoint pack so flag-blind decoders read logical zero points. - GPTQQuantLinear._load_from_state_dict: restore _qzeros_format from the declared checkpoint format so state_dict round-trips keep the v2 domain. - W4AFP8Linear pack_block/pack_gpu: forward positional args (block_in, workers) so pack() no longer raises TypeError. - BitBLAS repack_from_gptq: shift zp-1 fields to logical zero points when repacking a v2-requiring source still in the v1 checkpoint domain. - tests: field-boundary conversion coverage for bits 2/4/8, default-format post_init forward regression, NVFP4 state_dict round-trip; drop asserts that required expanded operand caches to persist (forward is CUDA-gated, post_init revalidation is the CPU-usable signal).

W4AFP8: stop keeping an E4M3 weight expansion resident
Problem
W4AFP8Linear.post_init()decoded the whole layer of INT4 into E4M3 and kept it on the module:That is a weight expansion rebuilt from the INT4 codes, not a packed layout, and it survived every forward.
AGENTS.mdforbids this and namespersistent=Falseas no exemption.On a 2048x8192 layer (16.7M weights):
qweight+qzeros+scales+g_idx)_weight_e4m3(resident onmain)For Llama-3.2-1B that is 973 MB of device memory held for the whole session.
Fix
forward()materializes the E4M3 operand, hands it to the GEMM, and drops it. The module keeps only a readiness flag (_WEIGHT_CACHE_NAMESis now empty).w4a_triton.unpack_int4_to_e4m3reads the packed int32 words, extracts the eight nibbles per word with register shifts, and writes E4M3 straight into a caller-owned buffer. No intermediate plane is ever allocated. The plain-Torch decode stays as the CPU/meta fallback and as the oracle the kernel is pinned against._check_native_weight_layout()runstorch.equalplus an all-reduce, both of which synchronize the device, and it used to run once per token. It now runs inpost_init();forward()keys staleness on tensor version counters and raises instead of decoding an unvalidated layout.Result
RTX 4090, CUDA events around a loop of calls, all three paths interleaved in one process, both GPUs idle:
main: resident E4M3 plane (illegal)So the compliant path costs 1.31x the illegal resident cache instead of 3.14x, and 973 MB of resident memory goes to zero.
Pure decode, no GEMM:
Per-projection forward (resident / Torch / fused):
Transient peak per forward, sampled from the caching allocator on an 8192x2048 layer: 1.00 B/weight (the operand alone). The superseded Torch decode needs 5.00 B/weight.
The fused decode is byte-identical to the Torch oracle: asserted on four random shapes plus the all-zero and all-ones words.
Other bugs fixed along the way
Cross-module decode raised
AttributeError._centered_int4_codes()calledself._unpack_int4_codes(...), but its documented use passes a different module asself— all four audit scripts callW4AFP8Linear._centered_int4_codes(torch_linear), andTorchLinearhas no such method. The unpacker is now module-level (unpack_int4_codes()) with a class-level alias kept, plus a cross-module regression test.Inference tensors made in-place weight writes undetectable. Tensors built inside
torch.inference_mode()have no version counter, so a(ptr, None)token can never change and a mutatedqzeroswent undetected. Added:invalidate_weight_layout()— public hook;forward()raises untilpost_init()reruns_layout_token_is_observable()— true only when every layout-defining tensor tracks in-place writes_warn_unobservable_layout()— one-shot warning naming the hookThe unobservable case is deliberately not revalidated per forward: that would put the
torch.equal/all-reduce sync back on the decode path.Scope: FP8 only (SM 8.9+)
NVFP4 needs SM 12.1 and cannot be exercised on this hardware, so its files are byte-identical to
mainand this PR carries no NVFP4 change.W4ANVFP4Linearstill keeps_weight_e4m3/_weight_both/_unit_weight_scalesresident, which still violates the same rule. It is recorded here as a known remaining violation that needs its own SM 12.1 PR, not claimed as fixed.Verification
2x RTX 4090 (SM 8.9), Triton 3.9.0, torch 2.15.0+cu132, every timing on idle GPUs.
test_w4afp8_gb10test_w4a_streamtest_w4a_cache_lifecycletest_w4a_activation_policytest_w4a_nvfp4_gb10(unchanged,mainbehavior)ruff checkon touched filesThe storage-contract tests judge by representation, not by name:
__dict__(3 levels into containers) by byte size, so integer tensors are caughtweakref+gc.collect()inference_mode,method=["to","cast"], device round-trip, andpack/loadAccuracy: E4M3 represents every centered INT4 code in
[-8, 7]exactly, and the fused kernel is byte-identical to the Torch decode, so the operand introduces no error of its own. Tests assert the arithmetic error against the decoded codes is== 0.0and the residual against the FP32 oracle stays within half an ulp of the model dtype — only the mandatory single output rounding. Those tests use an Ada-specific bounded criterion rather than strict equality on SM 8.9; see the comment intest_w4afp8_gb10.py(the 4090 fixed-point accumulator truncates against the largest term of the same instruction, a hardware property rather than a kernel defect).Before merge
bbe3ae8d2(mainis the direct parent; no conflicts)_weight_e4m3no longer exists onW4AFP8Linear