Skip to content

Studio: widen stored fp8 / int8 weights without full float32 temporaries - #17068

Merged
danielhanchen merged 8 commits into
mainfrom
studio/fp8-dequant-fused
Nov 8, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio/fp8-dequant-fused

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Problem

The eager widen of a stored-fp8 or native int8 weight-only Linear (NativeWeightOnlyLinear._stored_weight) did codes.float(), then a second float32 product, then the cast. That is two full float32 matrices per layer per forward next to the compute-dtype result: 512 MiB of float32 scratch for a 4096 x 16384 layer, on every eager forward. It runs for:

  • fp8 files loaded with fp8 storage (under offload, or on a GPU without fp8 GEMMs);
  • native int8 weight-only layers;
  • the MPS table lookup.

The load-time single-file dequant (_dequant in the single-file quant loader) did the same on the host.

Fix

  • Eager _stored_weight widens with one Triton kernel on CUDA / ROCm. The kernel does an integer fp8 decode identical to fp8_bits_to_float32 (no fp8 type needed, so sm75 and ROCm work), one float32 multiply by the row scale, and one rounding to the output dtype. bf16 rounds to nearest even by integer ops.
  • Where Triton is absent (CPU, MPS, XPU, Windows without Triton), the widen runs in bounded row chunks written into the output. A layer whose old widen fits the scratch budget runs today's exact expression.
  • The compiled path (torch.compiler.is_compiling()) is unchanged byte for byte, since inductor already fuses it.
  • Under CUDA graph capture, the kernel is used only once that specialisation has run in eager (no JIT and no probe inside a capture).
  • The load-time _dequant with no ConvRot group is row-chunked into the output and charges output plus one chunk. ConvRot keeps the whole-layer path.

Kill switch: UNSLOTH_DIFFUSION_FP8_DEQUANT_FUSED=0 restores the old widen.

Evidence

CPU (studio/backend/tests/test_diffusion_fp8_dequant.py, 39 tests):

  • All 256 codes of e4m3fn, e5m2 and int8, times 11 scales (subnormal, signed-zero, overflow-to-inf), in bf16 / fp16 / fp32, are bit-identical to the old formula. NaN positions are equal and NaN bits match torch's own cast. This holds on the chunked path and on the Triton kernel under TRITON_INTERPRET=1.
  • Odd rows 1 / 17 / 1023 / 1024 / 1025 through forced small chunks match, and so does _dequant against both the old formula and the kill switch.
  • A dispatch trace on a 2048 x 4096 layer shows 2 full float32 matrices on the merge base and 0 on this branch.
  • torch.compile(fullgraph=True) gives the same single frame and op count with the switch on or off, on base and head.

Related suites (33 files): identical failing test IDs on the merge base and this branch (5, all pre-existing).

GPU results

One stored-fp8 Linear widen plus its matmul, merge base 22a024f against this branch, the same process and inputs. Exhaustive codes and real shapes are bit-identical in every cell (NaN bits included). Peak is the extra memory over the inputs and output. The int8 rows follow the fp8 rows on T4 and on every larger A100 layer. One exception: on A100 the 3072 x 3072 int8 layer measured 0.27 / 0.34 ms at 17 / 1024 tokens, against 0.19 / 0.26 ms on the merge base. That is a single run on a shared card.

GPU layer (out x in) tokens merge base ms this branch ms switch off ms merge base peak MiB this branch peak MiB
T4, fp16 4096 x 16384 17 6.25 1.72 6.30 640 128
T4, fp16 4096 x 16384 1024 11.02 7.74 11.02 640 137
T4, fp16 4096 x 16384 4096 27.18 24.03 27.68 640 160
T4, fp16 12288 x 3072 17 3.61 1.05 3.65 360 72
T4, fp16 12288 x 3072 4096 15.05 13.37 15.31 360 168
T4, fp16 3072 x 3072 4096 3.86 4.21 3.92 90 42
A100, bf16 4096 x 16384 17 1.09 0.38 1.10 640 128
A100, bf16 4096 x 16384 1024 1.59 0.89 1.65 640 137
A100, bf16 4096 x 16384 4096 3.01 2.34 3.01 640 160
A100, bf16 12288 x 3072 17 0.64 0.28 0.72 360 72
A100, bf16 12288 x 3072 4096 1.80 1.68 1.78 360 168
A100, bf16 3072 x 3072 4096 0.53 0.55 0.59 90 42

The peak falls 2.1x to 5x on every shape. Time drops wherever the widen is a visible share of the layer. The small 3072 x 3072 layer at 4096 tokens is within run-to-run spread on both GPUs.

AMD Radeon 8060S (gfx1151, ROCm 7.13, torch 2.11): all 50 new tests pass on the GPU, including the Triton kernel in fp16, bf16 and fp32. The related suites show NO_REGRESSION against the merge base; the 3 failures there fail on both.

Cross-OS: Linux and Windows pass.

The eager widen of a stored-fp8 or native int8 Linear built the float32 codes,
a second float32 product and then the compute-dtype weight: two full float32
matrices per layer per forward (512 MiB for a 4096 x 16384 layer). The load-time
single-file dequant did the same on the host.

Eager forwards now widen with one Triton kernel on CUDA / ROCm (integer fp8
decode, one float32 multiply, one rounding) or in bounded row chunks written
into the output elsewhere; both are bit-identical to the old result. Compiled
forwards are unchanged.

UNSLOTH_DIFFUSION_FP8_DEQUANT_FUSED=0 restores the old widen.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T03:22:44.443996Z f44c50d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Nov 8, 2026
danielhanchen added a commit that referenced this pull request Nov 8, 2026
…without MSVC (#17073)

## Summary

When a cross-platform run selects
`studio/backend/tests/test_diffusion_native_quant.py`, the Windows leg
fails both cases of one test. #17068 is a current example:

```
FAILED test_diffusion_native_quant.py::test_fp8_codes_layer_matches_the_dequant_formula_eager_and_compiled[float8_e4m3fn]
FAILED test_diffusion_native_quant.py::test_fp8_codes_layer_matches_the_dequant_formula_eager_and_compiled[float8_e5m2]
E   torch._inductor.exc.InductorError: InvalidCxxCompiler: Compiler: cl is not found.
```

The test is on main (from #14549). Its last step runs
`torch.compile(layer, fullgraph = True)` on CPU. Inductor's CPU backend
compiles C++ with MSVC on Windows, and the `windows-latest` runner does
not put `cl` on PATH. The failure is the runner's missing compiler, not
the layer. Every check before that step is platform-independent and
passes on Windows: the eager forward against the dequant formula, the
weight equality and the zero graph-break check.

## Change

`studio/backend/tests/test_diffusion_native_quant.py`, test only: on
Windows with no `cl` on PATH, the test skips just before the compiled
half, after the eager and graph-break checks have run. The skip reason
says why. On Linux, on macOS, and on Windows with MSVC available, the
test runs exactly as before.

## Testing

| | result |
|---|---|
| the test on Linux, this branch | 2 passed |
| the Windows leg of this PR's cross-platform run | the check for the
change |
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d36deef617

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +134 to +135
except Exception as exc: # noqa: BLE001 - no Triton / launch failure: chunked torch below
_triton_failed(exc)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Release the failed Triton output before allocating the fallback

When Triton is unavailable on a CUDA device or its first launch fails, the full-size tensor allocated before launch_triton() remains referenced by out during fallback. The chunked path allocates another full-size output before the assignment releases the first; the unchunked path retains it throughout the old widening expression. This unnecessarily increases peak VRAM on the supported no-Triton fallback and can cause an otherwise avoidable OOM. Release the failed output before falling back, or reuse it as the chunked destination.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: f44c50ddd6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
@danielhanchen
danielhanchen merged commit 57d5fff into main Nov 8, 2026
@danielhanchen
danielhanchen deleted the studio/fp8-dequant-fused branch November 8, 2026 06:53
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…ai#17133)

Follow-up to unslothai#17068.

## Problem

`dequant_rows` launched the int8 / stored-fp8 Triton widen and ran its
CUDA-graph capture probe without making the operand's GPU current.
Triton picks the launch device and stream from the current device, not
from the tensor arguments (`driver.active.get_current_device()` then
`get_current_stream(device)` in `JITFunction.run`:
[v3.2.0](https://github.com/triton-lang/triton/blob/v3.2.0/python/triton/runtime/jit.py#L568-L569),
[v3.7.1](https://github.com/triton-lang/triton/blob/v3.7.1/python/triton/runtime/jit.py#L713-L714)),
and `torch.cuda.is_current_stream_capturing()` also describes the
current device's stream. A layer on `cuda:1` called while `cuda:0` is
current (an external `device_map` / Accelerate placement, which moves
tensors without a device scope) therefore launches against the wrong
device and stream; a rejected launch is caught and sets the process-wide
`_TRITON_STATE["failed"]`, which turns the fused widen off for every
later layer. The packed nvfp4 launcher from unslothai#17067 already scopes its
launch this way.

## Fix

Both the eligibility check (capture probe included) and the launch now
run inside `torch.cuda.device(codes.device)` when the codes are on CUDA
(a null context otherwise, so the CPU / MPS paths are unchanged). The
widen only runs in eager (`_stored_weight` takes the pure torch path
under `torch.compiler.is_compiling()`), so nothing changes inside
compiled graphs.

## Tests

- `test_the_triton_capture_probe_and_launch_run_on_the_operands_device`
(CPU, device context and capture probe recorded): both see `cuda:1`
while the caller stays on `cuda:0`, and the caller's device is current
again afterwards.
- `test_the_triton_widen_of_a_layer_on_a_non_current_gpu` (needs two
GPUs): int8, e4m3 and e5m2 layers on `cuda:1` widen through Triton with
device 0 current, bitwise equal to the old formula, and the failure
latch stays clear.

| | `origin/main` | this branch |
|---|---|---|
| `tests/test_diffusion_fp8_dequant.py` (CPU) | 1 failed, 39 passed, 12
skipped | 40 passed, 12 skipped |

Two GPUs (Kaggle T4 x2, torch 2.11, triton 3.6), device 0 current, an
int8 and an e4m3 layer on `cuda:1`, `_stored_weight(torch.bfloat16)`:

| | `origin/main` | this branch |
|---|---|---|
| device current at the Triton launch | 0 | 1 |
| `_TRITON_STATE["failed"]` after one call | `ValueError('Pointer
argument (at 0) cannot be accessed from Triton (cpu tensor?)')` | None |
| result | exact (chunked torch fallback), fused widen now off for the
process | exact, through Triton |

`tests/test_diffusion_fp8_dequant.py` on that host (the two-GPU and
single-GPU Triton cases included): 52 passed.
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.

1 participant