Skip to content

fix(w4a): stage the NVFP4 FP8 operand per forward instead of caching it - #3492

Merged
Qubitium merged 2 commits into
mainfrom
fix/nvfp4-e4m3-cache
Nov 3, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/nvfp4-e4m3-cache

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Problem

W4ANVFP4Linear.post_init() built a full-layer E4M3 plane from the native GPTQ
INT4 codes and kept it on the module as _weight_e4m3:

self._weight_e4m3 = centered.to(torch.float8_e4m3fn).contiguous()

That tensor is an expansion of the packed checkpoint (1 byte per weight,
one code per weight), not a packed layout, so it violates the repository
storage gate in AGENTS.md and
.agents/skills/gptqmodel-torch-oracle-numerics/SKILL.md.

It was also built unconditionally, even for a pure NVFP4 recipe whose MLP
boundaries never consume the FP8 lane. Combined with the packed _weight_both
planes, that doubled the extra resident weight bytes.

Note on scope: the sibling FP8 path was already fixed in #3459
(W4AFP8Linear._WEIGHT_CACHE_NAMES = ()). The same violation survived in the
NVFP4 subclass, which overrides post_init() and registers its own caches.

Measured

1024x256 module, before the fix:

tensor bytes note
qweight 131072 native INT4, 0.5 B/weight
_weight_e4m3 262144 expanded, 1 B/weight
_weight_both 262144 packed E2M1 x2, 1 B/weight (allowed)

extra / native = 4.0x. At 7B that is roughly +14 GB of standing device
memory for a plane a pure NVFP4 recipe never reads.

4096x4096 projection, after the fix:

before after
extra / native 4x (2 B/weight) 2x (1 B/weight)
7B standing extra ~+14 GB ~+7 GB
per-forward FP8 GEMM (rows=1) 37.5 us (resident operand) 56.9 us (staged)

The _weight_both E2M1 planes are kept: two 4-bit planes are 1 B/weight of
packed codes, which the storage rule permits. Only the E4M3 expansion is gone.

Change

  • Drop the _weight_e4m3 buffer, its cache registration, and its post_init
    construction.
  • _forward_fp8_operand() now materializes the operand through the inherited
    fp8_weight_operand() path, hands it to the GEMM, and drops the reference
    when the call returns (same contract as W4AFP8Linear).
  • post_init() builds only the packed E2M1 planes, then records the layout
    token and readiness so the inherited staging can validate the checkpoint.
  • forward() now rejects a stale packed cache after an in-place weight write,
    matching the FP8 lane's contract.
  • Docs and the three tests that pinned the old resident plane follow the new
    contract.

Validation

Per SKILL.md, both numerical and persistent-state gates.

Persistent state + numerics (CPU)

tests/kernels/test_w4a_cache_lifecycle.py: 52 passed. New cases:

  • test_nvfp4_post_init_retains_only_packed_planes - no _weight_e4m3 in
    _buffers / __dict__ / _WEIGHT_CACHE_NAMES; the representation-based
    scanner (size, not dtype or name) reports no expanded tensor; only packed
    planes remain. An independent E2M1 codebook decode reconstructs every
    centered INT4 code, so removing the E4M3 plane changed no weights.
  • test_nvfp4_fp8_operand_is_staged_per_forward - one fresh operand per call,
    weakref-collectable after the forward, buffers byte-identical, native
    state_dict unchanged.
  • test_nvfp4_fp8_operand_matches_independent_int4_decode - staged bytes equal
    an independent plain-shift INT4 decode cast to E4M3 (exact, no error).
  • test_nvfp4_forward_rejects_a_stale_packed_cache - in-place qweight write
    is rejected; invalidate_weight_layout() drops the packed planes.

CUDA (2x RTX 4090, SM 8.9, Torch 2.15.0+cu132, Triton 3.9.0)

W4A kernel suites (test_w4a_cache_lifecycle, test_w4a_nvfp4_gb10,
test_w4afp8_gb10, test_w4a_stream): 80 passed, 47 skipped.

Real Triton FP8 lane driven end to end on the modified path (2048x512,
bypassing the NVFP4 SM 12.1 gate so the FP8 attention lane actually runs):

  • fused unpack_int4_to_e4m3 operand is byte-identical to the Torch decode;
  • output is bf16 and satisfies the repository's existing Ada FP8 accumulator
    bound (max abs drift 7.75 against the FP32 oracle, bound PASS);
  • operand collectable after the forward; no _weight_e4m3 on the module.

ROCm (2x Radeon AI PRO R9700, gfx1200, Torch 2.16.0+rocm10.1)

New NVFP4 persistence/numeric cases: 8 passed.

Known limitation (not introduced here)

Native block-scaled FP4 GEMM cannot run on either host, so the NVFP4 forward()
itself is not exercised end to end:

  • RTX 4090: F.scaled_mm(..., BlockWise1x16, float4_e2m1fn_x2) ->
    CUBLAS_STATUS_NOT_SUPPORTED;
  • R9700: NotImplementedError: NVFP4 scaling not supported on ROCM.

W4ANVFP4Linear requires SM 12.1, so the hardware-gated NVFP4 tests skip. This
PR does not touch the FP4 GEMM, _weight_both construction, or
nvfp4_accumulate_group; the end-to-end NVFP4 regression still needs a GB10
run before merge.

Pre-existing ROCm failures in the same files (8 cases, NVIDIA-only Triton
kernels: PassManager::run failed / Unsupported DotOp) reproduce unchanged on
an unmodified checkout.

W4ANVFP4Linear.post_init() built a full-layer E4M3 plane (_weight_e4m3)
from the native GPTQ INT4 codes and kept it on the module between forwards.
That plane is an expansion of the packed checkpoint (1 B/weight, one code per
weight), not a packed layout, so it violates the repository storage gate. It
was built unconditionally even for pure NVFP4 recipes, which never consume the
FP8 lane. Together with the packed _weight_both planes it doubled the extra
resident weight bytes: 2 B/weight on top of the 0.5 B/weight qweight, i.e.
about 4x native, or roughly +14 GB at 7B.

The mixed FP8 attention lane now materializes the operand through the
inherited fp8_weight_operand() path inside _forward_fp8_operand(), passes it
straight to the GEMM, and drops it when the call returns. post_init() builds
only the packed E2M1 planes and records layout readiness so the inherited
staging can validate the checkpoint tensors. forward() rejects a stale packed
cache after an in-place weight write, matching the FP8 lane contract.

Measured on a 4096x4096 projection: extra resident weight bytes drop from
2 B/weight to 1 B/weight (4x -> 2x native; 7B: +14 GB -> +7 GB), and the
per-forward staging adds 19.4 us (1.52x) over a resident-operand FP8 GEMM.

Tests: CPU persistence tests assert no E4M3 plane is retained, the per-forward
operand is collectable after the call, only packed planes remain, and a stale
packed cache is rejected; an independent Torch INT4 decode pins the staged
bytes. Hardware-gated NVFP4 and mixed-stream tests follow the new contract.

Qubitium commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Reviewed commit dfc89176c3144f6a57b4b80c83ce07552b4b5052 and found one cache-consistency issue.

[P2] Keep packed NVFP4 cache validity separate from FP8 layout revalidation — w4a_nvfp4.py:167–171.

Setting _w4a_weights_ready = True enables the inherited fp8_weight_operand() path, but its _require_current_weights() method refreshes _w4a_layout_token after validating changed native weights without rebuilding _weight_both. Consequently, an in-place weight edit followed by a direct call to the public FP8 staging helper makes the new NVFP4 forward() freshness check accept stale packed planes.

Reproduced on CPU with a valid, initialized W4ANVFP4Linear:

module.qweight[0, 0] ^= 1
assert not module._weights_are_current()
operand = module.fp8_weight_operand()
assert module._weights_are_current()  # becomes True without rebuilding _weight_both

An independent decode then gives -7 for the updated native weight and staged FP8 operand, while the retained NVFP4 planes still reconstruct -8. The next forward() passes the stale-weight guard. On supported NVFP4 hardware, that allows the FP4 path to consume the old packed weights. This reproduction checks the cache state and guard on CPU; it does not claim an end-to-end GPU output measurement. At the parent commit, the same staging call raises because NVFP4 never marks the inherited FP8 readiness state initialized.

Please either keep a separate token for the packed planes or override NVFP4's staging validation to reject changed weights until post_init() rebuilds the cache. Add a regression covering weight mutation → FP8 operand staging → NVFP4 forward, asserting rejection or agreement between both weight representations.

Validation: 43 selected cache-lifecycle tests passed; the additional NVFP4/tiny-Llama test run had 8 passed and 55 skipped. Nine cache-lifecycle cases were deselected. git diff --check passed. Native NVFP4 execution remains unverified here because GB10/SM 12.1 hardware is unavailable.

W4ANVFP4Linear marked the inherited FP8 readiness state after post_init so a
mixed attention lane could stage its E4M3 operand. That state is guarded by
_w4a_layout_token, and the inherited _require_current_weights() *refreshes*
that token after revalidating changed native weights. Nothing there rebuilds
_weight_both, so an in-place qweight edit followed by a direct call to the
public fp8_weight_operand() made the freshness check added in the previous
commit accept the previous packed planes:

    module.qweight[0, 0] ^= 1
    assert not module._weights_are_current()
    module.fp8_weight_operand()          # revalidates and rewrites the token
    assert module._weights_are_current() # True, _weight_both still stale

Reproduced on CPU: the independent decodes then disagree (-7 for the updated
native weight and the staged FP8 operand, -8 for the retained FP4 planes) while
the next forward() passes its stale-weight guard. On NVFP4 hardware that would
let the FP4 path consume the old packed weights.

W4AFP8Linear may revalidate on the fly because it derives nothing from the
weights: fp8_weight_operand() decodes the current qweight every call. This
class retains a packed plane built from those codes, so a changed native weight
must force a rebuild instead. Override _require_current_weights() to reject,
and have forward() share that check.

Tests: test_nvfp4_fp8_staging_cannot_launder_a_stale_packed_cache covers
weight mutation -> FP8 operand staging -> NVFP4 forward, asserting the token is
not refreshed, both lanes refuse, and post_init() restores agreement between
the native codes, the packed planes, and the staged FP8 operand. Verified the
case fails without this override. The E2M1 codebook decode moved to a shared
_decode_e2m1_planes() oracle helper.

53 passed (CPU), 81 passed / 47 skipped on 2x RTX 4090, 11 NVFP4 cases on ROCm.

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in 003768a58. The finding is correct: the staleness guard added in dfc89176c was defeatable.

Root cause. _w4a_weights_ready = True enabled the inherited fp8_weight_operand(), whose _require_current_weights() revalidates and then rewrites _w4a_layout_token to the current weights. That refresh is sound for W4AFP8Linear (it derives nothing from the weights), but here it made _weights_are_current() report the stale _weight_both planes as current.

Reproduced on CPU exactly as described, and the two representations disagreed afterwards:

after mutation: qweight[0,0] code = -7
after mutation: planes[0,0] code  = -8
weights_current before staging     = False
operand[0,0]                       = -7.0
weights_current AFTER staging      = True   <-- refreshed without rebuilding planes
NVFP4 forward guard passes?        = True

Fix. Override _require_current_weights() in W4ANVFP4Linear to reject changed native weights instead of revalidating them in place, and have forward() share that check. A changed native weight now forces post_init() to rebuild the packed planes. W4AFP8Linear keeps its on-the-fly revalidation, which stays correct for the FP8-only lane. Post-fix the same script raises at the staging call and the token is left stale.

Regression test. test_nvfp4_fp8_staging_cannot_launder_a_stale_packed_cache covers weight mutation -> FP8 operand staging -> NVFP4 forward: it asserts the token is not refreshed, that both _forward_fp8_operand() and forward() refuse, and that after post_init() the native codes, the independently decoded E2M1 planes, and the staged E4M3 operand all agree. Verified the case fails without the override (negative control). The E2M1 codebook decode was extracted to a shared _decode_e2m1_planes() oracle helper.

Validation. 53 passed (CPU, test_w4a_cache_lifecycle); 81 passed / 47 skipped on 2x RTX 4090 across the four W4A kernel suites; 11 NVFP4 cases passed on 2x Radeon AI PRO R9700 (gfx1200); ruff clean; git diff --check clean. Native NVFP4 execution is still unverified here (no SM 12.1 host), unchanged from before.

@Qubitium
Qubitium marked this pull request as ready for review November 3, 2026 09:22
@Qubitium
Qubitium merged commit 41f7ba8 into main Nov 3, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/nvfp4-e4m3-cache branch November 3, 2026 09:22
Qubitium added a commit that referenced this pull request Nov 4, 2026
…ilure (#3525)

* fix(tests,jit): repair false-green gates and report the real ninja failure

Five audited P0/P1 items; each was reproduced on hardware before changing it.

B1 test_intel_cpu_xpu.py: `setUp` was a @classmethod, so unittest passed the
class as `self` and `self.forward(self.torch_model, ...)` bound unbound:
6x `TypeError: forward() missing 1 required positional argument: 'x'`. Drop
the decorator; 8 passed on 2x RTX 4090 (was 6 failed / 2 passed).

B2 test_asymmetric_real_models.py: Machete is Hopper-only (SM90, and >=204800
bytes opt-in shared memory), but the cases only gated on
`torch.cuda.is_available()`, so all four failed on an SM89 4090. Gate on the
kernels' own runtime checks instead: `machete_runtime_error()`, plus
`marlin_runtime_error()` for Marlin, which is CUDA-only and also failed on
ROCm (where `torch.cuda.is_available()` is True). 2 passed / 4 skipped on the
4090 and on ROCm GPUs 2,3.

B3 test_selection.py asserted `GGUFCudaKernel not in candidates`, but #3434
added bits 1/2/3 to that kernel, so the assertion was stale and contradicted
the implementation. Verified against an independent Torch GGUF oracle on the
4090 that all routed qtypes agree: Q1_0 maxdiff 4.88e-4, IQ1_S/IQ1_M 1.95e-3,
Q2_K/Q2_0/IQ2_* <= 1.95e-3, Q4-Q8 <= 1.95e-3 (fp16, atol 8e-2). Update the
assertion to require the kernel only after Triton.

Found while validating B3: TQ1_0 and TQ2_0 have no GPU convert kernel, and
ggml-cuda hits `GGML_ASSERT(convert_func != nullptr)`, which aborts the whole
interpreter rather than raising. The CPU backend does support them, so add a
CUDA-only reject set (sharing the existing Q8_1/Q8_K CPU set) and raise
`NotImplementedError` before any graph is built. Add CUDA oracle coverage for
1-bit/2-bit and a CPU ternary regression test that pins the set split.

B4 utils/cpp.py surfaced `Ninja is required to load C++ extensions` verbatim
while the real cause was ninja living in `$CONDA_PREFIX/bin` with that bin
directory missing from PATH. Reproduced both ways on ExLlamaV2 (JIT fails
without the env bin on PATH, builds in 20s with it). Add ninja/cmake
resolution, versions, `$CONDA_PREFIX` PATH hint, and an actionable hint to the
JIT failure diagnostics.

B5 test_w4a_nvfp4_gb10.py asserted `_weight_e4m3.numel() == in*out`, encoding
the expanded-cache violation as expected behavior. Already fixed upstream by
#3492 (NVFP4 stages the E4M3 operand per forward); the audit ran a branch 22
commits behind origin/main and no change is needed here.

Validation: 197 passed / 48 skipped for the touched CUDA suites on 2x RTX
4090; 271 passed / 429 skipped for tests/test_gguf_all_formats.py with the
llama-cpp CUDA runtime present; ROCm (GPUs 2,3) shows the same skips and no
new failures. A pre-existing `test_load_defaults_to_all_extensions` failure
and two pre-existing ROCm selection failures also fail on unmodified main.

* fix(gguf): reject ternary qtypes in GGUFCudaKernel's constructor

`select_quant_linear` validates candidates by `bits` only, so it cannot see
the GGUF qtype. For TQ1_0/TQ2_0 it kept `GGUFCudaKernel` in the AUTO candidate
list; `GGUFTritonKernel` rejects those types in `__init__`, so
`create_quant_layer` fell through to `GGUFCudaKernel`, which constructed fine.
The existing guard lived in `quantized_matmul_cuda`, i.e. the first `forward`,
and `create_quant_layer` only retries the next AUTO candidate on a
`NotImplementedError` raised during construction. The result was no runtime
fallback at all: AUTO built the layer and then failed during inference, while
the class comment claimed GGUF_TORCH was the fallback.

Move the rejection into `GGUFCudaKernel.__init__`, matching the precedent in
`GGUFTritonKernel`, and keep the `quantized_matmul_cuda` check as defence in
depth. Verified on 2x RTX 4090 through the real loader entry point: AUTO now
resolves tq1_0/tq2_0 to `GGUFTorchLinear` and forward succeeds.

Update the explicit-constructor test to assert the constructor raises, and add
AUTO-path coverage that mirrors `create_quant_layer`: build candidates in
priority order, skip constructor rejections, and require the selection to land
on `GGUFTorchLinear` with a working forward. Asserting on the `multi_select`
candidate list would be wrong, since selection is bits-based and
`GGUFCudaKernel` legitimately remains a candidate.

* fix(tests): keep extension failures out of hardware skips

---------

Co-authored-by: Qubitium <[email protected]>
Qubitium added a commit that referenced this pull request Nov 16, 2026
…4361)

Eight free-threaded workers forwarding after clear_weight_cache() each entered _ensure_q_handle's slow path and built their own native q-matrix; seven leaked. Add a module-level rebuild lock with a double-checked fast path, and take the same lock in clear_weight_cache so a release cannot race a publish. Steady-state forwards keep the lock-free fast path.

This is the only finding from #4184 that is still an actionable small bug on current main; the others were already fixed by #4327/#3492 or need larger work and are deferred in the PR disposition table.
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.

2 participants