Skip to content

test(fp4): pin the graph-safe bias gate on the FP4 wrapper - #3759

Merged
Qubitium merged 4 commits into
mainfrom
test/fp4-graph-gate-coverage
Nov 11, 2026
Merged

Qubitium merged 4 commits into
mainfrom
test/fp4-graph-gate-coverage

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

blocks: 3 fences: 6
p to #3753, which is already merged. #3753 added
bias_narrows_losslessly as the value-dependent gate that decides whether a
stored 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 #3753 review
(#pullrequestreview-5839675494)
reported two defects, both reproduced on 3fd1a2a74 and both fixed by the
merged PR:

Finding Reproduction on 3fd1a2a74 State on main
Checkpoint reload narrowed the new FP32 VPTQ bias FP16 reload: bias -65537 -> -inf, output -1 -> -inf; BF16 reload: bias -> -65536, output -> 0 Fixed: loader.py lists VPTQ bias in keep_in_fp32_modules and fp32_bf16_buffer_names
torch.equal broke CUDA Graph and fullgraph=True AcceleratorError: operation failed due to a previous error during capture; Unsupported: Data dependent operator Fixed: bias_narrows_losslessly returns the conservative wide answer while capturing or tracing

Both are real; main contains the fixes. No other open PR addresses them.

What this PR adds

FP4 coverage for the shared gate. TorchFP4Linear._epilogue_bias calls the
same bias_narrows_losslessly. The test builds the FP4 accelerator wrapper,
captures its forward in a torch.cuda.CUDAGraph, replays it, and traces it with
torch.compile(backend="eager", fullgraph=True).

The stored bias is 0.1, which is inexact in both FP16 and BF16, so both
parameterizations really take linear_wide_bias. The first version of this PR
used -65536, which BF16 represents exactly: the BF16 case returned
(bias.to(bfloat16), False) and ran the stock torchao F.linear, leaving the
gate untested for that dtype. Reverting _epilogue_bias to unconditional
narrowing 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 .data between 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 the
diagram shows that branch separately so a reader does not assume the
keep_in_fp32_modules lists 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 failure
Loading

Two 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 failure
Loading
flowchart 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 failure
Loading

Capturing 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) while
producing a bitwise identical result: 2.02 ms eager NVFP4 against 2.11 ms
wide on a 4096x4096 layer, 1.99 ms graph replay, and 7.5 MiB more
private-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 .data between replays against an FP64 oracle.

Mutation checks against this branch (FP16 / BF16):

Mutation Result
Remove the is_current_stream_capturing() short-circuit both fail: CUDA error: operation failed due to a previous error during capture
Remove the torch.compiler.is_compiling() short-circuit both fail: Unsupported: torch.* op returned non-Tensor
Revert _epilogue_bias to unconditional narrowing both fail, before and after the fixture change (BF16 previously passed)
Cache the gate answer on the module both fail: replay stops tracking .data writes

Five related suites were run on this branch:

Backend Result
NVIDIA CUDA 373 passed
AMD ROCm 278 passed, 95 skipped

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_kernel previously 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. That made the test fail intermittently in a full-suite run, so this
branch keeps the documented 2e-3 inference limit instead of asserting a bit
pattern 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 exercises
the portable dequantize-plus-linear_wide_bias branch, not the torchao NVFP4
path. The ROCm row is not evidence for a supported FP4 configuration.

Notes

  • No production code changes: this only adds regression coverage and the
    documentation diagrams for the mechanisms shipped in fix(fp4,vptq): keep stored bias wide through the linear epilogue #3753.
  • Eager execution still evaluates the live bias every call, so in-place
    .data writes remain visible; the conservative branch only applies while
    capturing or tracing.

`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 ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py seeds 787 globally), so the count varies with test order (I measured 4/16 to 12/16 across seeds). With rtol=0, atol=0 the assertion then mostly compares -inf == -inf and 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-59 describes only the FP8, GGUF or VPTQ keep_in_fp32_modules flow (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_bias branch 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.
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

All four points were valid. I reproduced each before changing anything, and fixed them in 7ec1bc54b.

The BF16 gap (blocking)

Confirmed exactly as described. bias_narrows_losslessly(-65536.0, torch.bfloat16) is True, so _epilogue_bias returned (bias.to(bfloat16), False) and the stock torchao F.linear ran; linear_wide_bias was never reached. Reverting _epilogue_bias to unconditional narrowing reproduced your mutation result: FP16 failed, BF16 passed.

The fixture now uses 0.1 and asserts the gate directly:

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 True

Re-running the same revert on the new fixture now fails both parameterizations, so the assertion is pinned rather than decorative.

Non-finite FP16 expectation

Also confirmed, and the count is seed-dependent as you suspected: with -65536 I measured 9 of 16 FP16 outputs as -inf, against your 6 of 16. With 0.1 the fixture yields 0 of 16 non-finite for both dtypes, and the test now asserts torch.isfinite(expected).all() and compares against an FP64 oracle built from module._native_weight().dequantize(x.dtype) instead of relying on -inf == -inf.

(-65537 does select the wide path for both dtypes, but as you noted its FP16 row stays partly -inf, so 0.1 is the better fixture.)

FP4 in the checkpoint diagram

Fixed. The diagram now branches to the FP4 decoder separately and states that models/base.py:3867-3871 registers the bias at its stored width when it builds TorchFP4Linear, so the keep_in_fp32_modules / fp32_bf16_buffer_names lists are explicitly the quantized-module path only.

ROCm applicability

Added to the PR body: FP4 is deliberately not advertised on ROCm (gptqmodel/quantization/dtype.py:519-526), so the HIP run exercises the portable dequantize-plus-linear_wide_bias branch rather than torchao NVFP4, and the ROCm row is not evidence for a supported FP4 configuration.

Re-validation after the changes

Check Result
Remove is_current_stream_capturing() short-circuit both parameterizations fail
Remove torch.compiler.is_compiling() short-circuit both parameterizations fail
Revert _epilogue_bias to unconditional narrowing both parameterizations fail (BF16 passed before this fix)
Full suite on NVIDIA CUDA 373 passed
Full suite on AMD ROCm 278 passed, 95 skipped

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.
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Re-checked the four claims against the pushed branch; all of them reproduce.

  • 0.1 is inexact in both FP16 and BF16, so both parameterizations take the wide epilogue (_epilogue_bias(...)[1] is True). Reverting _epilogue_bias to unconditional narrowing fails both, so the gate is pinned for BF16 as well as FP16.
  • With 0.1, 0 of 16 outputs are non-finite for either dtype, and the test now compares against an FP64 oracle from _native_weight().dequantize(x.dtype) instead of matching -inf against -inf. The non-finite count under the old -65536 fixture is seed-dependent; a nine-seed sweep on the new fixture stays bitwise exact with no non-finite values.
  • The checkpoint diagram branches to _build_fp4_forward_module and states the bias is registered at its stored width; the loader lists are scoped to the quantized-module path.
  • Both short-circuits are load-bearing: removing is_current_stream_capturing() or torch.compiler.is_compiling() fails both parameterizations, with the capture error and the Unsupported: torch.* op returned non-Tensor graph break respectively.

One correction pushed as fdf74b68e: the before/after table cited models/base.py:3795-3802 for the FP4 decoder, which is the TorchFP8Linear construction, and described "Before" as the state of main. The FP4 decoder is _build_fp4_forward_module (models/base.py:3831-3875, bias at 3871), and the narrowing it replaces was removed by #3753, so it never existed on main. The row now cites the decoder symbol and its bias line, and the header says "Before" means pre-#3753 code. The PR body used the same two-line reference; it now names the builder.

tests/kernels/test_linear_fp32_reduce.py passes on both the CUDA and HIP runs. No production code changed.

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.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 10, 2026 14:07
@Qubitium
Qubitium merged commit f68935b into main Nov 11, 2026
6 checks passed
@Qubitium
Qubitium deleted the test/fp4-graph-gate-coverage branch November 11, 2026 01:37
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