Skip to content

FP8 block dequant on gfx11 ROCm: ragged / rectangular e4m3fn blocks take the byte decoder - #14936

Merged
danielhanchen merged 2 commits into
mainfrom
fp8-hip-gfx11-byte-dequant
Oct 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fp8-hip-gfx11-byte-dequant

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On ROCm, block-FP8 weights whose tiles are ragged, or whose blocks are rectangular, still went through the chunked torch loop. #14450 moved these cases to the e4m3fn byte decoder on NVIDIA only. On gfx1151 (RDNA 3.5) that loop is 7.5x slower than the byte decoder, which is bit-identical to it for bf16 / fp32 output.

Change

  • gfx11 (RDNA3 / 3.5): the cases the torch loop took run _e4m3fn_bytes_dequant for bf16 / fp32 output. Those cases are ragged blocks, rectangular blocks, and even tiles when Triton has no fp8e4nv.
  • fp16 output keeps the torch loop. On gfx1151 both Triton kernels round fp16 differently from it.
  • Even tiles keep the fp8e4nv kernel.
  • CDNA, RDNA2, gfx12, gfx950 and unknown archs keep their current routes.
  • Kill switch: UNSLOTH_FP8_HIP_BYTES_DEQUANT=0 restores the old routes.
  • NVIDIA: routing is unchanged.

Results

gfx1151 (Radeon 8060S, torch 2.11 ROCm 7.13, Triton 3.6), main and this branch in the same job on the same runner:

shape main this PR
ragged 14336 x 4096, bf16 7.64 ms (torch loop) 1.02 ms (byte decoder)
q / up / down (even tiles) fp8e4nv kernel unchanged
  • Correctness: output is bit-equal to the torch loop.
  • Kill switch: restores main's routes. A/A on the unchanged up shape is within 0.6%.
  • FP8 tests on gfx1151: main has 121 passed / 15 failed, this branch 155 passed / 15 failed. The same 15 fail on main: fp16 parity on gfx1151.
  • NVIDIA, all FP8 test files (B200):
torch main this PR
2.10 707 passed 733 passed
2.14 659 passed 685 passed

The same 3 tests fail on main and here: test_explicit_and_automatic_dequantize_reload[False] and test_ragged_rows_match_block_reference[glm5_3|ling3].

Tests

  • test_rocm_routes / test_rocm_kill_switch_restores_old_routes: the routing table per gfx arch and Triton version.
  • test_real_rocm_device_takes_bytes_kernel_bit_exact: runs on real ROCm hardware.
  • The NVIDIA routing assertions are kept.

Not covered

  • AMD architectures: CDNA, RDNA2, gfx12 and gfx950 were not run. They keep their current route by construction.
  • Real checkpoint on AMD: none was run; the evidence is kernel-level plus tests.
  • Windows ROCm was not run.

…ake the byte decoder

On gfx1151 (RDNA 3.5) the cases the chunked torch loop takes (ragged or rectangular blocks, and
even tiles when Triton has no fp8e4nv) run the one-pass e4m3fn byte decoder instead, which is
bit-identical to the torch loop for bf16 / fp32 output. fp16 output keeps the torch loop, and
even tiles keep the fp8e4nv kernel. Other ROCm archs (CDNA, RDNA2, gfx12, gfx950) are unchanged.
UNSLOTH_FP8_HIP_BYTES_DEQUANT=0 restores the old routes. NVIDIA routing is unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T06:34:11.381240Z 9c7d194 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

Copy link
Copy Markdown

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

Reviewed commit: 9c7d1941e5

ℹ️ 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 ca4de9f into main Oct 23, 2026
3 of 29 checks passed
@danielhanchen
danielhanchen deleted the fp8-hip-gfx11-byte-dequant branch October 23, 2026 07:48
LeoBorcherding pushed a commit to LeoBorcherding/unsloth that referenced this pull request Oct 23, 2026
…hai#14947)

Comment-only follow-up to unslothai#14936: the final comment pass was committed
after the merge, so it landed here instead. No code changes
(`comment_tools.py check` confirms the AST is unchanged).

`tests/test_fp8_pre_sm89_byte_dequant.py` and
`tests/test_fp8_pre_sm89_dequant_fallback.py` pass on torch 2.14 (B200).
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…ch (#14969)

## Summary

`tests/test_triton_fp_fusion.py::test_every_launch_requests_fp_fusion`
fails on main since #14936:

```
AssertionError: Triton launches without enable_fp_fusion: ['fp8.py:243:_e4m3fn_scale_dequant_kernel']
```

Triton 3.9 defaults `enable_fp_fusion` to False, so every launch in
`unsloth/kernels` passes `enable_fp_fusion = True` to keep one numeric
behaviour across Triton versions. The gfx11 e4m3fn byte decoder launch
added in #14936 does not.

## Change

Pass `enable_fp_fusion = True` to the `_e4m3fn_scale_dequant_kernel`
launch, as the other launches in `fp8.py` do. The kernel computes `x *
s` with no add, so there is nothing to fuse into an FMA and its output
is unchanged on every Triton version; this only brings the launch in
line with the guard.

## Testing

- `tests/test_triton_fp_fusion.py` on main: 1 failed. With this change:
4 passed.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
- loader._resolve_non_vlm_auto_model: name trust_remote_code like its sibling resolvers, so test_every_resolver_probe_forwards_the_trust_decision can see the trust decision reach every class probe (#14945).
- test_kill_switch_env_is_read_at_import: the fresh interpreter had no CUDA spoof, so on CPU CI import unsloth raised before the switch was read (#14936). Install the CI spoof when there is no GPU, and check both values.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
Four checks fail on `main` (fd924a5), so every open PR inherits them.
Each was reproduced on a clean `main` worktree and attributed. A fifth,
`test_every_resolver_probe_forwards_the_trust_decision`, was fixed on
`main` by #14990 in the meantime, so this PR takes that version.

| Check | Introduced by | Wrong side | Fix |
|---|---|---|---|
|
`studio/backend/tests/test_text_io_encoding.py::test_text_io_names_its_encoding[_xpu_triton_toolchain.py]`
| #14814 | Product | The `vswhere` call used `text=True` with no
encoding, so it decoded with the locale code page. A Visual Studio
install path with non-ASCII characters would garble. It now passes
`-utf8` to vswhere and decodes as UTF-8 (`errors="replace"`). |
|
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
| 0947723 | Test | `test_packed_fp32_cuda_parity` skipped on
`torch.cuda.is_available()`, which the CPU CI spoof answers True. It is
now gated on `has_real_cuda()`, same as the sibling attention tests. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_examples_never_print_a_hardcoded_model_id`
| #14914 | Test | #14914 deliberately renders the example with a
`YOUR_MODEL` placeholder when nothing is servable, instead of hiding it.
The test still asserted the old "no snippet" shape. |
|
`tests/test_fp8_pre_sm89_byte_dequant.py::test_kill_switch_env_is_read_at_import`
| #14936 | Test | The subprocess imports `unsloth` in a fresh
interpreter that has no conftest spoof, so on CPU CI the import raised
"cannot find any torch accelerator" before the switch was read. With no
GPU, the subprocess now applies `tests/_zoo_aggressive_cuda_spoof.py`,
the same pattern `test_qat_phone_deployment.py` uses. It now checks both
`0` and `1`. |

For the third check, the invariant is unchanged: no hardcoded
`unsloth/...` id and no `MODEL_FALLBACK`. The test now also pins the new
contract:
- the placeholder constant
- the `model ?? MODEL_PLACEHOLDER` call as the only `buildSnippets` call
site
- the no-model note rendering exactly when the placeholder is shown

## Verification

- On `main` before #14990: 4 failed in `tests/` and 1 failed in
`studio/backend/tests`.
- On this branch: `test_accelerator_skip_guards.py`,
`test_usage_examples_model_source_contract.py` and
`test_attention_packed_fp32_routing.py` give 48 passed, 1 skipped. With
the two new files and `test_audio_load_routing.py` added, the run gives
94 passed, 133 skipped. `test_text_io_encoding.py` and
`test_xpu_triton_toolchain_14807.py` give 904 passed.
- Sabotage check: hardcoding `_HIP_FP8_BYTES_DEQUANT = True` fails the
kill-switch test.
- Sabotage check: both edits below make the updated contract test fail.
  - Changing the placeholder to `"unsloth/Qwen3-4B"`.
  - Dropping the `model ? null :` gate on the note.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…thai#14992)

On gfx1151, block-FP8 dequant to fp16 is not bit-equal to the torch
reference (`_torch_blockwise_dequant`). bf16 output was already exact.

### Cause
- **Lowering:** ROCm Triton 3.6 lowers "fp32 multiply, then cast to
fp16" to `v_fma_mixlo_f16(a, b, +0)`. That turns -0.0 into +0.0, and the
product is not rounded the way the torch loop rounds it (fp32 first,
then fp16).
- **Kernels affected:** both block-dequant kernels, the e4m3fn byte
decoder (`_e4m3fn_bytes_dequant_kernel`) and the fp8e4nv
`weight_dequant_kernel`.
- **This is the gap unslothai#14936 left:** it moved the ragged / rectangular
gfx11 cases to the byte decoder for bf16 / fp32 only, and kept fp16 on
the torch loop for this reason.

### Change
- **ROCm:** on ROCm both kernels round the fp32 product to fp16 with an
integer round-to-nearest-even (`_f32_to_f16_rne`). It keeps subnormals
and the sign of zero, and no backend combine can fuse it.
- **NVIDIA:** the rounding sits behind an `EXACT_F16` constexpr, which
is off on NVIDIA. The generated PTX is identical to main for 48 configs:
both kernels, fp16 / bf16 / fp32 output, a few tile shapes, sm75 / 80 /
89 / 90 / 100 / 120, Triton 3.8. Debug line info is excluded from the
comparison.
- **Override:** `UNSLOTH_FP8_EXACT_F16_ROUND=0` / `1` forces it off /
on.
- **Shift clamp:** lanes that take the normal path never shift by a
negative count.

### Results
gfx1151 (Radeon 8060S), main (d954720) and this branch in the same job.
Tests: `test_fp8_pre_sm89_byte_dequant.py`,
`test_fp8_pre_sm89_dequant_fallback.py`,
`test_fp8_ragged_block_dequant.py`, `test_fp8_fp16_scale_rounding.py`
and the new `test_fp8_exact_f16_round.py`.

| | main | this PR |
|---|---|---|
| passed / failed / skipped | 181 / 15 / 4 | 195 / 9 / 6 |

- **Newly passing on this branch:**
- `test_bytes_kernel_matches_torch_fallback[out_dtype0-...]` (3 shapes);
  - `test_past_int32_offsets`;
  - `test_transposed_and_strided[shape0]` and `[shape2]`.
- **New test file:** all of its tests pass or skip on gfx1151.
- **Pre-existing failures:** the 9 remaining failures are the same tests
on main and here:
- `test_fallback_matches_the_triton_kernel_bit_for_bit` (6 cases),
`test_pre_sm89_forward_never_reaches_the_fp8_only_kernels` (2 cases) and
`test_fp8_block_linear_forward_backward_unchanged`.
- They simulate an NVIDIA capability with a
`torch.cuda.get_device_capability` monkeypatch, which ROCm routing does
not read. That is a test gating issue for a follow-up, not touched here.

NVIDIA (B200, torch 2.14):
- `test_fp8_exact_f16_round.py` (both kernels, exact path forced on and
off) and `test_triton_fp_fusion.py`: 14 passed.

### Tests
`tests/test_fp8_exact_f16_round.py`:
- **Rounding helper:** `_f32_to_f16_rne` is compared with torch's fp16
cast over every fp32 exponent. Inputs include exact halfway mantissas,
values one above and below, subnormals, both zeros, infinities and NaNs.
- **Both dequant kernels:** they are bit-equal to the torch loop for
fp16 output on every e4m3fn byte. Scales from 2^-40 to 2^10 cover fp16
subnormals and overflow. A non-vacuity check confirms the data contains
double-rounding ties.
- **Defaults:** bf16 / fp32 are untouched; ROCm defaults to the exact
path, and the env switch works.
- **Codegen:** an offline gfx1151 compile shows the fused
mixed-precision instructions are gone with the exact path.

### Not covered
- **AMD architectures:** CDNA, RDNA2, gfx12 and gfx950 were not run. The
exact path is on for ROCm in general, so those take it too.
- **Real checkpoint on AMD:** none was run; the evidence is kernel-level
plus tests.
- **Windows ROCm:** not run.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
lonexreb added a commit to lonexreb/unsloth that referenced this pull request Oct 31, 2026
…r too

_hip_bytes_dequant kept fp16 on the torch loop because the gfx1151 byte decoder rounded fp16 unlike that loop (unslothai#14936). unslothai#14992 made both dequant kernels round to fp16 with integer ops on ROCm, bit-equal to the loop and on by default there, but left this gate as it was, so ragged / rectangular block weights dequantised to fp16 on gfx11 still took the ~7x slower torch loop while bf16 / fp32 took the kernel. Gate fp16 on that rounding instead: with UNSLOTH_FP8_EXACT_F16_ROUND=0 the torch loop keeps the route.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 14, 2026
…r too (unslothai#15224)

## What

`_hip_bytes_dequant` in `unsloth/kernels/fp8.py` still refuses
`out_dtype = torch.float16`, with the comment "on gfx1151 the byte
decoder rounds fp16 differently from the torch loop". That was true when
unslothai#14936 moved the ragged / rectangular gfx11 cases to the byte decoder
for bf16 / fp32 only. unslothai#14992 then made both dequant kernels round to
fp16 with integer ops on ROCm, bit-equal to `_torch_blockwise_dequant`
(its `test_dequant_kernels_match_torch_loop_fp16[bytes-1]` pins that)
and on by default there (`_FP8_EXACT_F16_ROUND = torch.version.hip is
not None`), and described itself as closing the gap unslothai#14936 left. The
gate was not updated, so on gfx11 a block-FP8 weight dequantised to fp16
still takes the torch loop (~7x slower per unslothai#14936) while bf16 / fp32
take the kernel. Same outputs either way; this is the speed path the
rounding work was done for.

## How

Gate fp16 on the rounding that makes it exact instead of excluding it
outright:

```python
if out_dtype == torch.float16 and not _fp8_exact_f16_round(out_dtype):
    return False
return _HIP_FP8_BYTES_DEQUANT and _rocm_bytes_dequant_arch(device)
```

So the ROCm default and `UNSLOTH_FP8_EXACT_F16_ROUND=1` route fp16
through the byte decoder; `=0` (the plain cast ROCm Triton fuses into
`v_fma_mixlo_f16`) keeps the torch loop. bf16 / fp32 are unchanged, and
nothing changes on NVIDIA, where `torch.version.hip is None`
short-circuits before this gate.

## Verification

-
`tests/test_fp8_pre_sm89_byte_dequant.py::test_hip_bytes_dequant_takes_fp16_once_its_rounding_is_exact`
(new, CPU): with the arch probe and the HIP switch patched on, fp16
routes with bf16 under `=1` and falls back under `=0`.
- `test_rocm_routes`: the fp16 row now asserts the byte decoder under
`=1` and the torch loop under `=0` (it was pinned to the torch loop with
the stale rationale).

Lifted `_hip_bytes_dequant` + `_fp8_exact_f16_round` from main's file vs
this branch, `_FP8_EXACT_F16_ROUND = True` as on ROCm:

| `UNSLOTH_FP8_EXACT_F16_ROUND` | main, fp16 | this branch, fp16 | bf16
(both) |
|---|---|---|---|
| unset (ROCm default) | torch loop | byte decoder | byte decoder |
| `1` | torch loop | byte decoder | byte decoder |
| `0` | torch loop | torch loop | byte decoder |

No ROCm hardware here: the gfx11 fp16 bit-equality rests on unslothai#14992's own
test, and the GPU-gated route test ran only in CI. `ruff check`,
`enforce_kwargs_spacing.py` and the `ruff-format-with-kwargs` hook pass;
`fp8.py` parses under Python 3.9.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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