Skip to content

FP8 dequant: multiply per-tensor and rowwise scales in fp32 for fp16 output - #14677

Merged
danielhanchen merged 3 commits into
mainfrom
dh/s3-fp8-fp16-scale
Oct 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/s3-fp8-fp16-scale

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

#14495 made fast_dequantize follow the activation dtype, so the fp16 LoRA backward now asks
weight_dequant for fp16. The per-tensor and rowwise branches cast the fp32 scale to the output
dtype before multiplying. In fp16 a scale below 6.1e-5 becomes subnormal (zero below about 6e-8)
and one above 65504 becomes inf, and the product is rounded a second time. Representable weights
and the base-weight part of dX can therefore come out as 0 or inf.

Example, fp8 value 448 with scale 1e-8 (per-tensor, rowwise and transposed rowwise):

  • before: 0.0
  • after: 4.4703e-06 (the fp64 product rounded to fp16)

On a rowwise matrix with row amax 0.001, the relative error vs fp64 drops from 1.18e-2 to 2.58e-4
(bf16 gives 2.5e-3).

Change: non-bf16 dtypes multiply in fp32 and round once, as the block-scaled path already does.
bf16 keeps its previous expression and fp32 is unchanged bit for bit.

Tests: tests/test_fp8_fp16_scale_rounding.py (CPU) checks fp16 against the fp64 oracle for
per-tensor, rowwise and transposed layouts, and checks that bf16 and fp32 output is byte-identical
to the previous expression. 10 of its 16 cases fail before this change. The existing FP8 tests pass
on torch 2.13 and 2.14. Under torch.compile(fullgraph=True), weight_dequant still traces to one
graph with no breaks.

…output

weight_dequant cast the fp32 scale to the output dtype before multiplying. For fp16
(requested since #14495 for fp16 LoRA) a scale below 6.1e-5 goes subnormal or zero and
one above 65504 overflows, so representable weights became 0 or inf and the product was
rounded twice. Non-bf16 dtypes now multiply in fp32 and round once, matching the block
path. bf16 keeps its previous expression and fp32 is unchanged bit for bit.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T13:28:56.904156Z 68e3b60 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.

@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: 6f711b13f4

ℹ️ 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 thread unsloth/kernels/fp8.py Outdated
# scale goes subnormal below 6.1e-5 and overflows above 65504, zeroing or inf-ing the weight.
if dtype == torch.bfloat16:
return x.to(dtype) * s.to(dtype)
return (x.to(torch.float32) * s.to(torch.float32)).to(dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid full-size fp32 temporaries in eager dequantization

When this path runs eagerly, as it can in the LoRA_* custom-autograd backward paths, this expression materializes both a full-size fp32 copy of the FP8 weight and a full-size fp32 multiplication result before allocating the fp16 output. The previous fp16 path used half-sized intermediates, so a large projection can require hundreds of MiB to nearly a GiB of additional peak memory and turn otherwise viable training runs into OOMs; please perform the fp32 multiply and fp16 store in a fused kernel rather than through eager tensor temporaries.

Useful? React with 👍 / 👎.

Comment thread unsloth/kernels/fp8.py Outdated
# scale goes subnormal below 6.1e-5 and overflows above 65504, zeroing or inf-ing the weight.
if dtype == torch.bfloat16:
return x.to(dtype) * s.to(dtype)
return (x.to(torch.float32) * s.to(torch.float32)).to(dtype)

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 Preserve float64 dequantization precision

When a caller requests torch.float64, this unconditional fp32 intermediate silently reduces the precision that weight_dequant previously preserved. For example, FP8 value 416 with float32 scale 30.778846740722656 now returns 12804.0 in float64 rather than the exact float32-scale product 12804.000244140625, and sufficiently large scales can become inf even when the float64 result is finite. Restrict the new fp32-multiply path to fp16 output and retain dtype-native arithmetic for higher-precision outputs.

Useful? React with 👍 / 👎.

Multiplying in fp32 built full-size fp32 copies of the weight and of the product in the eager LoRA
backward. fp8 values are exact in fp16, so cast to fp16 and multiply by the fp32 scale into an fp16
out=: TensorIterator computes in fp32 per element and rounds once, same bits, same peak as before.
Under compile (dynamo refuses a strided out=) Inductor fuses the fp32 expression instead.

Every other dtype keeps its native expression, so fp64 no longer passes through fp32 and bf16,
fp32 and fp64 are byte-identical to main. Tests cover fp64 and the transposed fp16 layout.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 68e3b60b04

ℹ️ 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
danielhanchen merged commit 22f5633 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the dh/s3-fp8-fp16-scale branch October 22, 2026 15:43
TFSebben pushed a commit to TFSebben/unsloth that referenced this pull request Oct 22, 2026
…lothai#14791)

## Summary

Per-channel (rowwise) FP8 weights with 2 to 16 decode rows (batched
`generate`, GRPO HF rollouts) went to `fbgemm_fp8_linear`, whose
`scaled_mm` backend dequantizes the whole weight to 16 bits on every
call below 64 rows. This adds a multi-row variant of the existing
rowwise GEMV that reads each fp8 weight tile once for all rows: exact
upcast, fp32 dot accumulate, per-channel scale applied after the sum,
split K only where K is long or N narrow (deterministic two-pass reduce,
no atomics).

- 1 row keeps the existing GEMV, 17+ rows keep the GEMM paths.
- `M` is `do_not_specialize`, so one compiled kernel serves every batch
size from 2 to 16.
- Reached from the same callers as the 1-row GEMV: the
compressed-tensors FP8 forward
(`UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1`) and `fast_linear_forward`.
`UNSLOTH_FP8_GEMV_ROWS=0` restores the previous routing.

## End to end decode

`RedHatAI/Qwen3-1.7B-FP8-dynamic`,
`UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1`, greedy, 64 new tokens, torch
2.14.1. Main and this branch run from separate checkouts in separate
processes, interleaved main, branch, main, 3 rounds; tok/s is the
median, A/A is the largest main vs main gap within a round.

| GPU | batch | main tok/s | this PR tok/s | speedup | A/A |
|---|---|---|---|---|---|
| L4 | 1 | 23.0 | 23.3 | 1.01x | 1.08% |
| L4 | 4 | 60.3 | 88.7 | 1.47x | 1.54% |
| L4 | 8 | 120.4 | 177.0 | 1.47x | 1.65% |
| RTX PRO 6000 | 1 | 91.2 | 91.3 | 1.00x | 1.21% |
| RTX PRO 6000 | 4 | 236.9 | 342.7 | 1.45x | 1.26% |
| RTX PRO 6000 | 8 | 473.3 | 674.1 | 1.42x | 1.00% |

The new kernel ran 12348 times per 64-token batch-4 / batch-8 generate
and 0 times at batch 1. Greedy tokens differ from main at batch 4 / 8
(78 to 89% identical), since main dequantizes or quantizes the
activation while this keeps the activation exact; against an fp64 oracle
on B200 (84 cases, 60 of them routed to the new kernel), its mean abs
error is at or below main's in all 60.

## Kernel timing

Same per-channel quantized weights in both arms, bf16, decode rows `M`,
called the way the compressed-tensors forward calls it. Device time with
L2 flushed (median of 30), microseconds, main / this PR:

| N x K | L4 M=1 | L4 M=4 | L4 M=16 | L4 M=17 | PRO 6000 M=4 | PRO 6000
M=16 |
|---|---|---|---|---|---|---|
| 2048x6144 (Qwen3-1.7B down) | 28.7 / 27.6 | 221.7 / 43.0 | 226.3 /
62.5 | 228.4 / 228.4 | 36.9 / 16.4 | 45.0 / 18.4 |
| 6144x2048 (Qwen3-1.7B gate / up) | 75.8 / 75.8 | 188.9 / 76.8 | 193.5
/ 76.8 | 222.2 / 221.2 | 38.9 / 20.5 | 40.9 / 22.5 |
| 4096x4096 (Qwen3-8B q) | 98.3 / 98.3 | 266.2 / 104.4 | 270.8 / 104.4 |
262.7 / 265.2 | 44.0 / 26.6 | 46.1 / 26.6 |
| 12288x4096 (Qwen3-8B gate / up) | 281.6 / 281.6 | 1150.5 / 282.6 |
1153.0 / 284.7 | 1125.4 / 1126.4 | 151.6 / 61.4 | 153.6 / 61.4 |
| 4096x14336 (Llama 8B down) | 279.6 / 279.6 | 1275.4 / 292.9 | 1286.6 /
303.1 | 1316.4 / 1319.9 | 186.4 / 47.1 | 190.5 / 49.2 |

Across 20 shapes (Qwen3 0.6B to 8B, Llama 8B) at M = 2, 4, 8, 16:

| GPU | metric | this PR / main, median | range |
|---|---|---|---|
| L4 | device, L2 flushed | 0.41 | 0.19 to 0.67 |
| L4 | host, back to back calls | 0.43 | 0.06 to 0.67 |
| L4 | CUDA graph replay | 0.34 | 0.06 to 0.82 |
| RTX PRO 6000 | device, L2 flushed | 0.50 | 0.24 to 0.69 |
| RTX PRO 6000 | host, back to back calls | 0.52 | 0.15 to 0.85 |
| RTX PRO 6000 | CUDA graph replay | 0.41 | 0.10 to 0.80 |

M = 1 and M = 17 are within the A/A band of main on every shape (same
code path).

## Tests

Main and this PR from separate checkouts, `-m "not server and not
native_mxc"`:

| run | 28 existing FP8 test files | new `test_fp8_rowwise_gemv_rows.py`
|
|---|---|---|
| L4, torch 2.14.1 | same 4 failing IDs on main and here | 106 failed on
main, all pass here |
| RTX PRO 6000, torch 2.10.0 | same 4 failing IDs on main and here | 106
failed on main, all pass here |

The 4 failures on both sides are in `test_modelopt_fp8_loading.py` and
are pre-existing on main.

## torch.compile

HF `generate` at batch 1, 2, 4, 8, 16 (each batch 8 new tokens), counted
after the last batch:

| torch | GPU | graph breaks main / PR | recompiles main / PR | Dynamo
graphs main / PR | Triton variants (PR) |
|---|---|---|---|---|---|
| 2.14.1 | L4 | 0 / 0 | 0 / 0 | 16 / 12 | 1-row GEMV 2, rows GEMV 2,
reduce 0 |
| 2.10.0 | RTX PRO 6000 | 0 / 0 | 0 / 0 | 12 / 8 | 1-row GEMV 2, rows
GEMV 2, reduce 0 |

The rows kernel's variant count is the same after batch 2 as after batch
16. Fewer Dynamo graphs because the 2 to 16 row calls no longer go
through the compiled `fbgemm_fp8_linear` path.

## Not proven

- B200 timing: the exclusive B200 queue wait was over 30 minutes, so it
was dropped. The kernel correctness sweep from the branch work ran on
B200.
- Timing ran on torch 2.14.1 only; torch 2.10.0 has tests and the
compile census, not timing.
- AMD / ROCm, XPU and Blackwell with Triton 3.3 (rows calls keep the
GEMM there, gate unchanged) were not run.
- The split-K reduce kernel compiled 0 variants in the Qwen3-1.7B decode
census; its end to end use is covered by the unit tests only.
- Timing ran on the branch before it was merged with main `031a117757`;
main's only `fp8.py` change in between (unslothai#14677) is in the fp16
per-tensor / per-row `weight_dequant`, off the decode paths timed here.
Tests and the compile census above were re-run on the merged branch.
TFSebben pushed a commit to TFSebben/unsloth that referenced this pull request Oct 22, 2026
unslothai#14792)

## Summary

Block-FP8 decode (M <= 16 rows) launched `act_quant` and then the 16 x
128 tile w8a8 GEMM, which runs only N / 128 programs (32 for a 4096 wide
projection). This fuses the activation quantization into a narrow-N w8a8
kernel, one launch per linear:

- Quantizes the activation tile in-kernel with the same max / 448 scale
and e4m3 cast as `act_quant`.
- N tile and an optional deterministic split K are sized from the SM
count; `M` is not specialized, so batch 1 and batch 16 share one
compiled variant per shape.
- Without a grad to compute, `FP8BlockQuantLinear.forward` is called
directly, skipping the `autograd.Function` host cost.
- Larger M, the torchao / FBGEMM block routes, pre-sm89 devices and
`torch.compile` regions keep the previous path.
`UNSLOTH_FP8_BLOCK_SMALL_M=0` restores it.

## End to end decode

Greedy decode, 64 new tokens, torch 2.14.1. Main and this PR run from
separate checkouts in separate processes, interleaved main, PR, main, 3
rounds; tok/s is the median, A/A is the largest main vs main gap within
a round.

| GPU | model | batch | main tok/s | speedup | A/A |
|---|---|---|---|---|---|
| L4 | Qwen3-1.7B-FP8 | 1 / 4 / 8 | 14.2 / 57.4 / 114.2 | 1.25x / 1.26x
/ 1.26x | 0.8% / 1.8% / 1.4% |
| L4 | Qwen3-8B-FP8 | 1 / 4 / 8 | 10.8 / 43.9 / 87.1 | 1.26x / 1.25x /
1.25x | 2.2% / 1.6% / 3.2% |
| RTX PRO 6000 | Qwen3-1.7B-FP8 | 1 / 4 / 8 | 55.3 / 220.2 / 438.6 |
1.15x / 1.16x / 1.15x | 1.0% / 0.6% / 0.3% |
| RTX PRO 6000 | Qwen3-8B-FP8 | 1 / 4 / 8 | 42.7 / 170.1 / 338.0 | 1.15x
/ 1.15x / 1.15x | 0.3% / 0.7% / 0.7% |

A second RTX PRO 6000 session reproduced 1.15x to 1.16x. The fused
kernel ran 12348 times per 64-token Qwen3-1.7B generate (all 196
projections at each of the 63 decode steps); `act_quant` now runs only
for the prefill (196 calls, was 12544).

Accuracy: at split K 1 the output is bit-identical to main. Split K > 1
changes the fp32 summation order only; teacher-forced on the same token
stream (48 prompts x 64 steps, Qwen3-1.7B-FP8, B200), the mean abs logit
error against a dequantized bf16 copy is 0.1987 here vs 0.1967 on main,
paired difference 95% CI [-0.0044, +0.0080], with 22 rows better and 26
worse. Greedy text diverges from main after a few tokens for that
reason.

## Kernel timing

20 projection shapes (Qwen3 0.6B to 8B, Llama 8B), M = 1, 2, 4, 8, 16,
bf16, this PR / main:

| GPU | metric | median | range | worst shape |
|---|---|---|---|---|
| L4 | device, L2 flushed | 0.95 | 0.72 to 1.05 | 6144x2048, 1.03 to
1.05 |
| L4 | host, back to back calls | 0.58 | 0.54 to 1.01 | |
| L4 | CUDA graph replay, L2 hot | 1.07 | 0.73 to 2.05 | 6144x2048 M=16
|
| RTX PRO 6000 | device, L2 flushed | 0.76 | 0.58 to 1.06 | 9728x2560
M=8 |
| RTX PRO 6000 | host, back to back calls | 0.80 | 0.65 to 0.92 | |
| RTX PRO 6000 | CUDA graph replay, L2 hot | 0.85 | 0.50 to 2.47 |
9728x2560 M=16 |

Eager decode is bound by host launch cost at these sizes, which is where
the fused launch pays off. With the weight already in L2 and no launch
cost (CUDA graph replay of the same weight), the narrow-N split-K tiles
lose to the 128 x 128 GEMM on wide gate / up and long-K down projections
at M 8 to 16. The fused kernel is eager only, so `torch.compile` graphs
(including CUDA graphs from `reduce-overhead`) keep main's path; a
model's weights do not stay in L2 across a decode step either.

## Tests

Main and this PR from separate checkouts, `-m "not server and not
native_mxc"`:

| run | 28 existing FP8 test files | new
`tests/test_fp8_block_small_m.py` |
|---|---|---|
| L4, torch 2.14.1 | same 4 failing IDs on main and here | 69 failed on
main, all pass here |
| RTX PRO 6000, torch 2.10.0 | same 4 failing IDs on main and here | 69
failed on main, all pass here |

The 4 failures on both sides are in `test_modelopt_fp8_loading.py` and
are pre-existing on main.

## torch.compile

`Qwen/Qwen3-0.6B-FP8`, LoRA r 8: 3 training steps, then HF generate at
batch 1, 2, 4, 8, 16, then layer 0's `mlp` and `k_proj` under
`torch.compile` at decode batch 1 to 16 plus a prefill:

| torch | GPU | training graph breaks / recompiles | decode graph breaks
/ recompiles | compiled modules, breaks main / PR | Triton variants
after batch 16 (main -> PR) |
|---|---|---|---|---|---|
| 2.14.1 | L4 | 0 / 0 on both | 0 / 0 on both | 0 / 0 | w8a8 GEMM 14 ->
8, fused small-M 3 |
| 2.10.0 | RTX PRO 6000 | 0 / 0 on both | 0 / 0 on both | mlp 3 / 3
(pre-existing), k_proj 0 / 0 | w8a8 GEMM 14 -> 8, fused small-M 3 |

The fused kernel's 3 variants are one per (N, K) config and do not grow
from batch 1 to batch 16; the compiled modules match eager to 0.0078 max
abs (one bf16 ulp in the mlp output, torch 2.14) and exactly elsewhere.

## Not proven

- B200 timing: the exclusive B200 queue wait was over 30 minutes, so it
was dropped (the accuracy run above is from B200).
- CUDA graph replay of eager decode with weights resident in L2 is
slower on some shapes (table above); not measured end to end since
nothing in Unsloth captures this path.
- Timing ran on torch 2.14.1 only; torch 2.10.0 has tests and the
compile census.
- AMD / ROCm and XPU were not run (the route is gated to the Triton
block matmul).
- Timing ran on the branch before it was merged with main `031a117757`;
main's only `fp8.py` change in between (unslothai#14677) is in the fp16
per-tensor / per-row `weight_dequant`, off the decode paths timed here.
Tests and the compile census above were re-run on the merged branch.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 23, 2026
…es (unslothai#14886)

Per-tensor and rowwise FP8 weight dequant (`weight_dequant` with a
scalar or `(rows, 1)` scale) ran as two passes: `x.to(dtype)` writes a
16-bit copy, then a multiply reads it back and writes the result. Every
LoRA backward on FBGEMM / compressed-tensors rowwise FP8 checkpoints
dequantizes each frozen weight this way, as does `fast_dequantize` and
the dequant forward on GPUs without a working rowwise GEMM.

This PR adds `_e4m3fn_scale_dequant_kernel`: one Triton pass that reads
the e4m3fn bytes once and writes the output once (3 bytes per element
instead of 7).

## Same bits as before

- fp16 multiplies by the fp32 scale and rounds once, as unslothai#14677 does.
- bf16 / fp32 round the scale to the output dtype first, as `x.to(dtype)
* s.to(dtype)` does. An e4m3 value times a bf16 scale is exact in fp32,
so one rounding gives torch's result.
- The bytes are decoded with the existing `_e4m3fn_byte_to_float`
(unslothai#14408), so it also runs on GPUs below sm89 (T4).
- Transposed views keep the strides the torch expression returns.

## When it is used

Eager NVIDIA calls only, when all of these hold:

- the weight is e4m3fn and has more than 4M elements;
- the output is fp16 / bf16 / fp32, with an fp32 / bf16 / fp16 scale;
- neither the weight nor the scale needs a gradient, and a transposed
view is a dense transpose.

Everything else keeps the current torch path:

- compiled regions (Inductor already fuses the expression);
- ROCm, e5m2 weights, float64;
- smaller weights. At or below 4M elements the call is launch-bound on
A100 and newer, and the torch path is no slower there.

## Speed

Colab, torch 2.11 / Triton 3.6, CUDA events, median of 5, A/A spread of
the base mostly under 5%. Times are base -> this PR in microseconds for
the rowwise layout; all layouts (rowwise, transposed rowwise,
per-tensor) are within a few percent of each other.

| shape | dtype | T4 | L4 | A100 |
|---|---|---|---|---|
| 2048 x 6144 | bf16 | 629 -> 192 (3.3x) | 298 -> 48 (6.2x) | 132 -> 43
(3.1x) |
| 2048 x 6144 | fp16 | 715 -> 190 (3.8x) | 350 -> 46 (7.6x) | 155 -> 44
(3.6x) |
| 4096 x 4096 | bf16 | 844 -> 249 (3.4x) | 480 -> 82 (5.9x) | 172 -> 45
(3.8x) |
| 4096 x 4096 | fp16 | 965 -> 253 (3.8x) | 537 -> 74 (7.3x) | 204 -> 45
(4.5x) |
| 14336 x 4096 | bf16 | 2971 -> 873 (3.4x) | 1763 -> 766 (2.3x) | 565 ->
146 (3.9x) |
| 14336 x 4096 | fp16 | 3439 -> 880 (3.9x) | 1850 -> 766 (2.4x) | 686 ->
146 (4.7x) |

At 4M elements (2048 x 2048, 1024 x 4096), T4 still gains 3.3-5.5x. On
A100 the result ranged from 0.78x to 1.44x there, because both versions
are launch-bound. Hence the size gate.

## Tests

`tests/test_fp8_scale_dequant_one_pass.py`:

- Bit patterns are compared against the torch expression for every byte
value (NaN, both zeros, subnormals) in each of these cases:
  - output fp16 / bf16 / fp32;
  - scale fp32 / bf16;
- rowwise, transposed rowwise, per-tensor, and transposed per-tensor
layouts.
- fp16 at extreme scales (1e-8, 1e5) still rounds once.
- e5m2 weights, float64 scales, a weight or scale that requires grad, a
transposed view whose transpose is not dense, and compiled regions keep
the torch path.
- A 2048 x 2048 weight stays on the torch path, and a 2049 x 2048 weight
takes the kernel.

Results on B200:

| torch | main | this PR |
|---|---|---|
| 2.10 | 32 of the 36 new tests fail (kernel never used) | 36 passed |
| 2.14 | 32 of the 36 new tests fail (kernel never used) | 36 passed |

Every `tests/test_fp8_*.py` file, plus
`test_compressed_tensors_fp8_kernel_route.py` and
`test_fp8linear_high_precision_weight.py`, was also run on B200. For
this run the size gate was off, so the kernel served every per-tensor /
rowwise call in those tests.

- main and this branch fail the same 3 test IDs on torch 2.10 and 2.14:
`test_fp8_dequant_save_policy.py::test_explicit_and_automatic_dequantize_reload[False]`
and
`test_fp8_ragged_block_dequant.py::test_ragged_rows_match_block_reference[glm5_3|ling3]`.
These fail on main too.
- Everything else passes: torch 2.14 658 passed, torch 2.10 707 passed.

## End to end

LoRA r 16 on all linear layers of `RedHatAI/Qwen3-1.7B-FP8-dynamic`
(compressed-tensors per-channel FP8), batch 4 x 512, torch 2.10, B200:

- Each training step makes 196 dequant calls; 84 of them take the new
kernel (the three 6144 x 2048 MLP weights in each of the 28 layers). The
other calls are below the size gate.
- Every kernel output was compared with the torch expression inside the
training run: 0 mismatches in 252 calls, in both bf16 and fp16.
- Losses match main within run-to-run noise (bf16 max difference 0.0044
against 0.0048 between two main runs; fp16 is noisier on both sides).

## Not covered

- No end-to-end step time: the end-to-end run was on a shared GPU, so
only correctness is claimed from it.
- H100 / B200 timing was not run on a dedicated card.
- ROCm is unchanged (`torch.version.hip` keeps the torch path).
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
…othai#15354)

## Problem

`_scale_mul` (used by `weight_dequant` for per-tensor and rowwise FP8
scales) rounds fp16 output once by calling `torch.mul(x16, s_fp32, out =
...)`, added in unslothai#14677 to stop fp16 scales underflowing / overflowing.
`out=` ops have no autograd, so when the weight or the scale requires
grad and grad mode is on, eager dequantization now raises:

```
RuntimeError: mul(): functions with out=... arguments don't support automatic differentiation, but one of the arguments requires grad.
```

Before unslothai#14677 the same call backpropagated. Under `torch.compile` the
code already takes the differentiable fp32 expression, so eager and
compiled disagreed. Frozen-base LoRA is unaffected (neither input
requires grad); the failure needs a trainable FP8 weight or scale.

## Fix

A trainable weight or scale (grad mode on) takes the same fp32
expression the compiled path uses, `(x.float() * s.float()).to(fp16)`,
which rounds once and gives the same bits as the `out=` path. Frozen
inputs keep the `out=` path (no fp32 temporary).

## Tests


`tests/test_fp8_fp16_scale_rounding.py::test_fp16_dequant_keeps_autograd_for_trainable_inputs`
(per-tensor and rowwise scale, trainable scale or weight): output equals
the fp64 oracle rounded to fp16, backward runs, and the scale gradient
is the sum of the weights it covers. On main all 4 cases raise the error
above; with this change they pass. `test_fp8_fp16_scale_rounding.py`,
`test_fp8_exact_f16_round.py`, `test_fp8_fp16_lora_dtype.py` on CPU: 27
passed, 17 skipped (GPU-only).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant