Skip to content

fix(fp8): resolve the W8A8 _scaled_mm contract outside forward (#5195) - #5257

Merged
Qubitium merged 1 commit into
mainfrom
fix/5195-fp8-probe-capture
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5195-fp8-probe-capture

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #5195.

fix(fp8): resolve the W8A8 _scaled_mm contract outside forward (#5195)

Root cause (one line)

A capability decision that needs a device→host read was made lazily from
forward
, so a cold first call inside CUDA-graph capture or
torch.compile(fullgraph=True) either cached a context error as a hardware
verdict (permanently losing the native W8A8 path) or failed to trace
(torch.Generator).

What broke

_scaled_mm_row_scale_supported() (#5178) was called by _can_use_scaled_mm()
from forward(). On a cold process cache the first per-token W8A8 forward:

  • created a torch.Generator and ran bool(torch.allclose(...)) — an opaque
    object and a host sync inside the traced/captured region;
  • on a capture, the D2H read raised, except Exception: supported = False
    cached False for the whole process and logged a false hardware
    diagnosis, even on sm_89 where the kernel is correct;
  • under torch.compile(fullgraph=True), dynamo raised
    Unsupported: An opaque object was created in the middle of the program.

A second lazy host read had the same problem: _decoded_weight_absmax_bound()
copied the scale to the host, so a genuinely cold first capture failed with
RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture... (reproduced; that is the exact error the issue reports).

Before

sequenceDiagram
    participant F as TorchFP8Linear.forward
    participant C as _can_use_scaled_mm
    participant P as _scaled_mm_row_scale_supported
    participant X as capture / dynamo context
    F->>C: per-token gate
    C->>P: cold cache?
    P->>X: torch.Generator + _scaled_mm + allclose (host read)
    alt CUDA-graph capture
        X-->>P: RuntimeError (D2H copy forbidden)
        P->>P: cache supported=False (process-wide)
        P-->>C: False
        C-->>F: dequant + matmul for the rest of the process
    else torch.compile(fullgraph=True)
        X-->>P: Unsupported: opaque object (Generator)
        P-->>F: trace fails
    end
Loading

After

sequenceDiagram
    participant L as post_init / set_activation_quant_method / _apply
    participant F as TorchFP8Linear.forward
    participant C as _can_use_scaled_mm
    participant P as _scaled_mm_row_scale_verdict
    L->>P: eager warm (plain eager code)
    P->>P: cache True/False (host read only here)
    F->>C: forward
    C->>P: one dict lookup
    alt answer cached
        P-->>C: True/False
    else capturing or tracing
        P-->>C: None (unknown — NOT cached)
        C-->>F: exact fallback for this call
    end
Loading

Changes (gptqmodel/nn_modules/qlinear/fp8.py)

  • _probe_must_wait() — true under torch.compiler.is_compiling() or
    torch.cuda.is_current_stream_capturing().
  • _probe_fp8_codes() — deterministic n/16 codes (exact in E4M3), so the
    probe needs no torch.Generator.
  • _probe_scaled_mm_row_scale() — returns a device bool tensor
    (isclose(...).all()); no bool(), no allclose, no host sync.
  • _scaled_mm_row_scale_verdict() -> Optional[bool] — cached answer, or
    None when this context cannot measure. None and OOM are never cached; a
    kernel rejection or a numeric mismatch is cached. The old bool API
    _scaled_mm_row_scale_supported() is kept.
  • GPTQMODEL_FP8_SCALED_MM=auto|on|off — parsed once at import (a Python
    constant for dynamo) to force the answer; off is the escape hatch for a
    device with a broken row-wise kernel.
  • _warm_runtime_decisions() — eagerly measures the range bound and, for
    per-token CUDA layers, the contract for every possible output dtype.
    Called from post_init(), set_activation_quant_method("per_token") and
    _apply().
  • _weights_fit_activation_dtype / _inverse_scales_are_nonzero — while
    capturing/tracing with an unmeasured bound, keep the exact wide path instead
    of syncing.
  • __init__ initialises the range-bound cache explicitly (it used to exist
    only after _apply/_load_from_state_dict).

Warm path is unchanged: the per-forward cost is still one dict lookup (plus one
attribute check in the range-bound helper).

Evidence (fresh process per case, RTX 4090 sm_89, torch 2.15.0+cu132)

Check pre-fix post-fix
eager first forward cache True, 4.0e-2 vs FP32 oracle same
cold capture (allocator warmed only, first forward captured) false warning, {(False,0,fp16): False} sticky, _can_use_scaled_mm False afterwards capture ok, 4.0e-2, cache True, fast path available
cold capture + cold range bound RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture... capture ok, 0.0 diff vs dense, cache still empty
cold torch.compile(fullgraph=True) (inductor) Unsupported: An opaque object was created in the middle of the program traces, 4.0e-2, cache True
cold compile, caches forcibly cleared trace fails traces dense (0.0 diff), cache empty, next eager call resolves True
set_activation_quant_method("per_token") then capture cache empty after opt-in → sticky False cache True at opt-in → fast path
unsupported kernel (raises) fallback, False cached same
wrong numeric contract (#5174 simulated: scale_a dropped) fallback, False cached same
warm eager / capture / compile ok ok (unchanged)

Logs: .scratch/red2_*.log and .scratch/green2_*.log; driver
.scratch/repro_5195.py.

Tests

  • New tests/kernels/test_fp8_probe_5195.py: 15 passed
    (11 of them fail on pre-fix upstream/main; the other 4 are warm-path/CPU
    controls).
  • tests/kernels/test_fp8_kernel.py + test_fp8_lean_decode_5146.py + new
    file: 127 passed, 6 skipped.
  • tests/test_fp8*.py (11 files, GPU): 109 passed, 1 skipped.
  • Compile family (9 files incl. protocol/levels/capability): 161 passed,
    177 skipped, 3 failed
    — the same 3 fail on a pristine upstream/main
    worktree (FP8 quantize removed in feat(fp8): make FP8 load-only and remove the invented gptqmodel_fp8 export #5242; two NF12 CPU cases).
  • uvx [email protected] check gptqmodel docs/eora tests setup.py: All checks
    passed
    .

Not verified here

The rowwise `_scaled_mm` capability probe ran from `_can_use_scaled_mm()`
inside `forward()`. On a cold process cache the first per-token forward
therefore created a `torch.Generator` (opaque to dynamo) and read its
verdict on the host: `torch.compile(fullgraph=True)` failed with
"An opaque object was created in the middle of the program", and inside a
CUDA-graph capture the failed measurement was cached as "unsupported" for
the rest of the process, permanently losing the native W8A8 path.

- measure the contract eagerly in `post_init()`,
  `set_activation_quant_method()` and `_apply()`;
- make the probe itself free of `torch.Generator` and host sync (device
  bool verdict, deterministic exact FP8 codes);
- treat an unmeasurable context (capture/tracing) and OOM as "unknown",
  never caching them; a kernel rejection or numeric mismatch is cached;
- add `GPTQMODEL_FP8_SCALED_MM=auto|on|off`;
- warm the lazy decoded-weight range bound eagerly too: its host read was
  the second reason a truly cold first capture failed;
- keep the exact wide path when a bound is unmeasured inside capture.

Regression tests: tests/kernels/test_fp8_probe_5195.py.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant