Repository navigation
test(fp4): pin the graph-safe bias gate on the FP4 wrapper - #3759
Conversation
`bias_narrows_losslessly` now short-circuits while a CUDA Graph is capturing or `torch.compile` is tracing, but only the VPTQ forward had capture/replay and fullgraph coverage. Both quantizers call the same helper, so exercise the FP4 accelerator wrapper with a stored FP32 `-65536` bias as well; without the escape hatch the capture fails with "operation failed due to a previous error during capture". Document the two new control flows, the checkpoint preservation lists and the capture/compile short-circuit, so the reference page matches the shipped decision path.
ZX-ModelCloud
left a comment
There was a problem hiding this comment.
Thanks. I verified both capture/compile escape hatches with mutation testing — they are genuinely pinned. There is one coverage gap that blocks the stated purpose of the PR.
Verified
| Mutation | Result |
|---|---|
Remove the is_current_stream_capturing() short-circuit in bias_narrows_losslessly |
both parameterizations fail: CUDA error: operation failed due to a previous error during capture |
Remove the torch.compiler.is_compiling() short-circuit |
both parameterizations fail: Unsupported: torch.* op returned non-Tensor |
Revert TorchFP4Linear._epilogue_bias to unconditional narrowing (pre-#3753) |
FP16 fails; BF16 still passes |
The reported suite counts reproduce: 373 passed on NVIDIA CUDA, and 278 passed / 95 skipped on AMD ROCm.
Blocking: the BF16 case never reaches the shared gate
bias_narrows_losslessly(-65536.0, torch.bfloat16) is True — BF16 represents that value exactly. _epilogue_bias therefore returns (bias.to(bfloat16), False) and the forward runs the stock torchao NVFP4 F.linear; linear_wide_bias is never called.
So the fixture at tests/kernels/test_linear_fp32_reduce.py:363 does not pin the gate for BF16, which is why the pre-#3753 revert above slips through, and why docs/low-precision-bias-epilogue.md:142 ("The same gate is shared by the FP4 accelerator wrapper, which reaches it with an FP32 -65536 bias") is only true for FP16.
A value inexact in both dtypes fixes this. Both -65537.0 and 0.1 select the wide path for FP16 and BF16, and I confirmed each keeps capture and fullgraph=True bitwise equal to eager. 0.1 is the better choice because it also keeps every FP16 output finite. Add an explicit assertion so the fixture cannot drift back:
# Exact in neither FP16 nor BF16, so both dtypes take the wide epilogue.
bias=torch.full((16,), 0.1, device="cuda", dtype=torch.float32),
...
assert module._epilogue_bias(x, module.bias)[1] is True(-65537.0 also selects the wide path for both dtypes, but its FP16 result is still partly -inf; 0.1 keeps both dtypes finite.)
Minor
- The FP16 expectation is partly non-finite. With the current fixture a direct run gives 6 of 16 FP16 outputs as
-inf; the fixture also does not pin its own RNG (conftest.pyseeds 787 globally), so the count varies with test order (I measured 4/16 to 12/16 across seeds). Withrtol=0, atol=0the assertion then mostly compares-inf == -infand does not validate finite arithmetic. The fixtures above remove this; alternatively pin a local seed and compare against an FP64 oracle as the neighbouring tests do. - The new checkpoint diagram omits the FP4 path.
docs/low-precision-bias-epilogue.md:49-59describes only theFP8, GGUF or VPTQkeep_in_fp32_modulesflow (models/loader.py:2364-2371). FP4 keeps its bias width in the decoder instead (models/base.py:3866-3871), and the page now covers FP4 as well, so a reader will assume FP4 is preserved by those loader lists. - ROCm applicability. FP4 is deliberately not advertised on ROCm (
gptqmodel/quantization/dtype.py:519-526), so on HIP this test exercises the portable dequantize-plus-linear_wide_biasbranch rather than the torchao NVFP4 path. Worth one sentence in the PR body so the ROCm row is not read as validating a supported FP4 configuration.
No production code changes are required; the test fixture and the doc wording are the whole fix.
`bias_narrows_losslessly(-65536.0, torch.bfloat16)` is `True`: BF16 holds that value exactly, so the BF16 parameterization returned `(bias.to(bfloat16), False)` and ran the stock torchao NVFP4 `F.linear`. `linear_wide_bias` was never called, and reverting `_epilogue_bias` to unconditional narrowing still passed it. Use `0.1`, which is inexact in both FP16 and BF16, assert that the wide epilogue is selected, and compare against an FP64 oracle. That also keeps every output finite: the old fixture returned `-inf` in part of the FP16 row, so the bitwise comparison was mostly asserting `-inf == -inf`. Document the FP4 checkpoint path separately, since it keeps the bias width in the decoder instead of the loader's preservation lists, and note that FP4 is not advertised on ROCm.
|
All four points were valid. I reproduced each before changing anything, and fixed them in The BF16 gap (blocking)Confirmed exactly as described. The fixture now uses bias=torch.full((16,), 0.1, device="cuda", dtype=torch.float32),
...
# Exact in neither FP16 nor BF16, so both dtypes take the wide epilogue.
assert module._epilogue_bias(x, module.bias)[1] is TrueRe-running the same revert on the new fixture now fails both parameterizations, so the assertion is pinned rather than decorative. Non-finite FP16 expectationAlso confirmed, and the count is seed-dependent as you suspected: with ( FP4 in the checkpoint diagramFixed. The diagram now branches to the FP4 decoder separately and states that ROCm applicabilityAdded to the PR body: FP4 is deliberately not advertised on ROCm ( Re-validation after the changes
No production code changed; the commit is test fixture, documentation, and PR-body wording only. |
The before/after table cited `models/base.py:3795-3802`, which is the `TorchFP8Linear` construction, and described "Before" as the state of `main`. The narrowing it describes was removed by PR #3753, so it never existed on `main`, and the FP4 decoder lives in `_build_fp4_forward_module` (`models/base.py:3831-3875`, bias at 3871). Cite the decoder symbol and its bias line, and state that "Before" is the pre-#3753 code for every row. The diagram paragraph now names the builder instead of two comment lines.
|
Re-checked the four claims against the pushed branch; all of them reproduce.
One correction pushed as
|
The FP4 capture/compile regression only replayed the bias value that was present at capture time, so a graph that baked in that value — or a forward that cached the representability answer, which `.data` writes do not bump a version counter for — would still have passed. Replay three `.data.fill_` values and compare each against an FP64 oracle, which is the FP4 counterpart of `test_vptq_bias_epilogue_captures_and_replays_live_values`. `test_vptq_cuda_representable_wide_bias_keeps_fused_kernel` compared the fused kernel against the FP64 oracle bitwise on unseeded activations. The kernel accumulates in FP32 (FP64 for BF16) and rounds once, so its partial-sum order differs from the oracle's; measured over 200 random draws per dtype the spread is at most 2 ULP and eager FP32 accumulation reproduces most draws exactly, which made the test fail intermittently in a full-suite run. Keep the documented `2e-3` inference limit instead of a bit pattern the kernel is not required to produce. Document that a captured or compiled layer with a representable FP32 bias stays on the wide epilogue while eager takes the cheap one. The result is bitwise identical; only the kernel changes, and the extra private-pool memory is recorded.
blocks: 3 fences: 6
p to #3753, which is already merged. #3753 added
bias_narrows_losslesslyas the value-dependent gate that decides whether astored FP32 bias may use the cheap narrow epilogue. That helper is shared by
FP4 and VPTQ, but the merged capture/compile regression only exercised the VPTQ
forward. This PR pins the same gate on the FP4 accelerator wrapper and records
the two new control flows in the reference page.
What was checked
PR #3753review(#pullrequestreview-5839675494)
reported two defects, both reproduced on
3fd1a2a74and both fixed by themerged PR:
3fd1a2a74main-65537->-inf, output-1->-inf; BF16 reload: bias ->-65536, output ->0loader.pylists VPTQ bias inkeep_in_fp32_modulesandfp32_bf16_buffer_namestorch.equalbroke CUDA Graph andfullgraph=TrueAcceleratorError: operation failed due to a previous error during capture;Unsupported: Data dependent operatorbias_narrows_losslesslyreturns the conservative wide answer while capturing or tracingBoth are real;
maincontains the fixes. No other open PR addresses them.What this PR adds
FP4 coverage for the shared gate.
TorchFP4Linear._epilogue_biascalls thesame
bias_narrows_losslessly. The test builds the FP4 accelerator wrapper,captures its forward in a
torch.cuda.CUDAGraph, replays it, and traces it withtorch.compile(backend="eager", fullgraph=True).The stored bias is
0.1, which is inexact in both FP16 and BF16, so bothparameterizations really take
linear_wide_bias. The first version of this PRused
-65536, which BF16 represents exactly: the BF16 case returned(bias.to(bfloat16), False)and ran the stock torchaoF.linear, leaving thegate untested for that dtype. Reverting
_epilogue_biasto unconditionalnarrowing failed FP16 but still passed BF16, which is what surfaced the gap.
The fixture now asserts that the wide epilogue is selected, and compares
against an FP64 oracle.
The replay also rewrites the bias through
.databetween replays..data.fill_does not bump a version counter, so a graph that baked in the captured value, or
a forward that cached the representability answer, would otherwise still pass.
Each rewrite is compared against the FP64 oracle; this is the FP4 counterpart of
test_vptq_bias_epilogue_captures_and_replays_live_values.Documentation of the two new flows. The reference page now draws the
checkpoint-preservation path and the representability-gate path, each with its
failure branch. FP4 keeps its bias width in the decoder
(
models/base.py:3871) rather than the loader's preservation lists, and thediagram shows that branch separately so a reader does not assume the
keep_in_fp32_moduleslists cover FP4.Flow
The shared epilogue, which FP4 and VPTQ both call:
flowchart TD A["Quantized linear forward"] --> B["Reconstruct temporary weight"] B --> C{"linear_needs_wide_bias: FP16/BF16 activation and wider stored bias?"} C -- "Yes" --> D["linear_wide_bias"] C -- "No" --> E["promote_bias: widen a narrower bias only"] E --> F{"_wants_fp32_reduce on NVIDIA CUDA?"} F -- "Yes" --> G["_CudaWideMatmul or torch.mm with FP32 output, bias in FP32"] F -- "No" --> H{"_fuse_bias_epilogue on CPU or HIP?"} H -- "Yes" --> I["torch.addmm with one epilogue"] H -- "No" --> J["F.linear with the promoted bias"] D --> K["Round once to the activation dtype"] G --> K I --> K J --> K K --> L["Release the temporary weight"] M["Old path: bias cast to activation dtype before the reduction"] --> N["-inf or a rounded partial sum"] classDef failure fill:#fce8e6,stroke:#a33,color:#111 class N failureTwo control flows decide whether the wide path is available at all:
flowchart TD A["Checkpoint load"] --> B["named_modules scan for bias names"] B --> C{"bias present and module is FP8, GGUF or VPTQ?"} C -- "No" --> P["FP4 decoder path"] C -- "Yes" --> E["keep_in_fp32_modules: FP16 load keeps FP32"] E --> F{"FP8, GGUF or VPTQ?"} F -- "Yes" --> G["fp32_bf16_buffer_names: re-read as FP32 after a BF16 load"] F -- "No" --> H["FP16 preservation only"] G --> I["Forward sees the stored FP32 value"] H --> I P --> Q{"_build_fp4_forward_module: checkpoint bias tensor?"} Q -- "Yes" --> R["register the bias at its stored width, no dtype cast"] Q -- "No" --> S["bias=None"] R --> I D["Accelerate narrows an unlisted buffer to the requested dtype"] --> J["Failure path: VPTQ bias -65537 becomes FP16 -inf or BF16 -65536"] classDef failure fill:#fce8e6,stroke:#a33,color:#111 class D,J failureflowchart TD A["bias_narrows_losslessly(bias, dtype)"] --> B{"bias.dtype == dtype?"} B -- "Yes" --> C["True: exact by construction"] B -- "No" --> D{"torch.compiler.is_compiling()?"} D -- "Yes" --> E["False: trace the wide epilogue"] D -- "No" --> F{"bias on cuda and stream capturing?"} F -- "Yes" --> E F -- "No" --> G["torch.equal on FP64 casts: read live values"] G --> H{"Values identical?"} H -- "Yes" --> C H -- "No" --> E classDef failure fill:#fce8e6,stroke:#a33,color:#111 class E failureCapturing or tracing cannot run the value check, so the gate stays wide. For a
bias that eager would prove exact, the captured layer therefore changes kernel
(torchao NVFP4 becomes a per-call dequantize plus
linear_wide_bias) whileproducing a bitwise identical result:
2.02 mseager NVFP4 against2.11 mswide on a 4096x4096 layer,
1.99 msgraph replay, and7.5 MiBmoreprivate-pool memory per captured layer.
Tests
The new FP4 case is parameterized over FP16 and BF16, checks the captured
graph against the pre-capture eager result bitwise, and rewrites the bias
through
.databetween replays against an FP64 oracle.Mutation checks against this branch (FP16 / BF16):
is_current_stream_capturing()short-circuitCUDA error: operation failed due to a previous error during capturetorch.compiler.is_compiling()short-circuitUnsupported: torch.* op returned non-Tensor_epilogue_biasto unconditional narrowing.datawritesFive related suites were run on this branch:
The skipped cases are the CUDA-only VPTQ fused-kernel tests, which are
excluded on HIP by their own guards.
test_vptq_cuda_representable_wide_bias_keeps_fused_kernelpreviously comparedthe fused kernel against the FP64 oracle bitwise on unseeded activations. The
kernel accumulates in FP32 (FP64 for BF16) and rounds once, so its partial-sum
order differs from the oracle's: measured over 200 random draws per dtype the
spread is at most 2 ULP, and eager FP32 accumulation reproduces most draws
exactly. That made the test fail intermittently in a full-suite run, so this
branch keeps the documented
2e-3inference limit instead of asserting a bitpattern the kernel is not required to produce; 15/15 standalone runs and the
full file now pass.
FP4 is deliberately not advertised on ROCm
(
gptqmodel/quantization/dtype.py:519-526), so on HIP the FP4 test exercisesthe portable dequantize-plus-
linear_wide_biasbranch, not the torchao NVFP4path. The ROCm row is not evidence for a supported FP4 configuration.
Notes
documentation diagrams for the mechanisms shipped in fix(fp4,vptq): keep stored bias wide through the linear epilogue #3753.
.datawrites remain visible; the conservative branch only applies whilecapturing or tracing.