Repository navigation
fix(fp8): resolve the W8A8 _scaled_mm contract outside forward (#5195) - #5257
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5195.
fix(fp8): resolve the W8A8
_scaled_mmcontract outsideforward(#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 ortorch.compile(fullgraph=True)either cached a context error as a hardwareverdict (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:torch.Generatorand ranbool(torch.allclose(...))— an opaqueobject and a host sync inside the traced/captured region;
except Exception: supported = Falsecached
Falsefor the whole process and logged a false hardwarediagnosis, even on sm_89 where the kernel is correct;
torch.compile(fullgraph=True), dynamo raisedUnsupported: 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 endAfter
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 endChanges (
gptqmodel/nn_modules/qlinear/fp8.py)_probe_must_wait()— true undertorch.compiler.is_compiling()ortorch.cuda.is_current_stream_capturing()._probe_fp8_codes()— deterministicn/16codes (exact in E4M3), so theprobe needs no
torch.Generator._probe_scaled_mm_row_scale()— returns a device bool tensor(
isclose(...).all()); nobool(), noallclose, no host sync._scaled_mm_row_scale_verdict() -> Optional[bool]— cached answer, orNonewhen this context cannot measure.Noneand OOM are never cached; akernel 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 Pythonconstant for dynamo) to force the answer;
offis the escape hatch for adevice with a broken row-wise kernel.
_warm_runtime_decisions()— eagerly measures the range bound and, forper-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— whilecapturing/tracing with an unmeasured bound, keep the exact wide path instead
of syncing.
__init__initialises the range-bound cache explicitly (it used to existonly 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)
True, 4.0e-2 vs FP32 oracleforwardcaptured){(False,0,fp16): False}sticky,_can_use_scaled_mmFalseafterwardsTrue, fast path availableRuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture...torch.compile(fullgraph=True)(inductor)Unsupported: An opaque object was created in the middle of the programTrueTrueset_activation_quant_method("per_token")then captureFalseTrueat opt-in → fast pathFalsecachedscale_adropped)FalsecachedLogs:
.scratch/red2_*.logand.scratch/green2_*.log; driver.scratch/repro_5195.py.Tests
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+ newfile: 127 passed, 6 skipped.
tests/test_fp8*.py(11 files, GPU): 109 passed, 1 skipped.177 skipped, 3 failed — the same 3 fail on a pristine
upstream/mainworktree (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 checkspassed.
Not verified here
float16output): no such GPU. The numericmismatch is simulated by dropping
scale_a, which the probe rejects._scaled_mmbehaviour (no AMD GPU); the code path is unchangedexcept that the measurement is now deferred outside capture.
GPTQModel.load(...)+m.optimize(fullgraph=True)on the issue'sQwen2.5-0.5B checkpoint (offline, checkpoint not cached). The regression
tests exercise the same
TorchFP8Linearpayload with the same row scales.backend="eager"for speed; the defaultinductor backend is covered by the
.scratch/repro_5195.pyruns above.