Skip to content

ROCm gfx1151: 2x faster GRPO rollouts (one-launch skinny decode linear + RL decode graphs) - #18874

Merged
danielhanchen merged 10 commits into
mainfrom
g20-amd-grpo-decode
Nov 23, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
g20-amd-grpo-decode

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

ROCm gfx1151: GRPO rollouts 2x faster (one-launch skinny decode linear + RL decode graphs)

GRPO on Strix Halo (gfx1151, Radeon 8060S) spent about 95% of every step in HF-generate rollouts, and those rollouts were slow because rocBLAS runs the decode GEMMs (M = 4 to 8 rows) with a 128x128 Tensile macro tile. Each 16-bit LoRA projection paid three such passes per token (base GEMM, X @ A.T, LoRA addmm_), about 588 GEMM launches per token on Qwen3-0.6B at 30 to 200 us each.

Changes

  1. unsloth/kernels/rocm_skinny_linear.py (new): a Triton kernel computing X @ W.T + s * (X @ A.T) @ B.T for up to 16 decode rows in one launch. It streams W once and accumulates the rank-r term in fp32 beside the base product, so the output is rounded once instead of three times. Split-K partials are summed in a fixed order, so results are deterministic and do not depend on the batch.
  2. fast_linear_forward (unsloth/kernels/utils.py) calls it for 16-bit decode steps (q_len == 1). It only does so on ROCm, outside torch.compile, without autograd, and for shapes measured faster than rocBLAS (K <= 3072 or N <= 1024). Anything else falls through to the existing path unchanged.
  3. unsloth/models/_decode_graphs.py: the RL decode-graph default (previously NVIDIA CUDA only) now also covers gfx1151 while the kernel is enabled. On that configuration, HIP graph replay was measured token for token equal to the eager step, GRPO losses were identical, and it was faster. Other HIP archs keep graphs off unless UNSLOTH_DECODE_CUDA_GRAPHS=1. Because plain model.generate() and Studio chat use the same default on non-Windows hosts, they also replay graphs on Linux gfx1151 (296.8 vs 260.4 tok/s, identical tokens); Windows keeps them off there, as on CUDA.

Gating: only torch.version.hip builds on gfx1151 (gcnArchName) load the kernel. UNSLOTH_ROCM_SKINNY_LINEAR=0 disables both the kernel and the new graphs default. =all enables the kernel on other gfx11 parts (unmeasured). CUDA builds never import Triton for this and take the same code path as before; the only addition is one module-level boolean check per decode linear.

Results (real gfx1151 AMD CI, same job, base = main f5dfe68, head = this branch)

jobs/grpo.py notebook preset (Qwen3-0.6B-Base, 16-bit LoRA r32, 4 generations x 256 tokens, HF generate), steady step time (median of steps 3 to 5):

Linux ROCm 7.13 Windows 11 ROCm 7.14
base, seed 3407 (A/A) 9020 / 8999 ms 10455 / 10437 ms
head, seed 3407 (A/A) 4284 / 4286 ms 5160 / 5172 ms
speedup 2.10x 2.02x
head, graphs forced off (A/A) 4674 / 4701 ms 6124 / 6134 ms
head, UNSLOTH_ROCM_SKINNY_LINEAR=0 9030 ms, metrics bit-identical to base 10464 ms, metrics bit-identical to base
seeds 3408 / 3409, base vs head 8656 / 8787 vs 4028 / 3988 ms 10586 / 10449 vs 5462 / 5088 ms

The A/A spread is under 0.3% in every arm. Peak allocated memory: base and head with graphs off 1.70 GB; head default 1.94 / 1.95 GB (the decode-graph pool and static buffers; the kernel itself adds nothing). For reference, the same job on a Colab L4 takes 3344 ms.

Decode microbench (Unsloth generate, Qwen3-0.6B-Base, LoRA r32 with nonzero B, greedy, 256 tokens):

Linux base Linux head Windows base Windows head
batch 4, tok/s 126.0 / 126.1 296.8 103.3 / 103.6 186.5 (221.6 with graphs)
batch 8, tok/s 242.0 574.4 201.7 364.1
GPU ms per token (batch 4) 29.8 10.8 n/a n/a

Per projection at M = 4 (us, rocBLAS three-GEMM LoRA sequence vs this kernel, Linux): q 118.6 vs 46.5, k/v 94.5 vs 30.5, o 175.9 vs 66.0, gate/up 156.5 vs 68.6, down 201.6 vs 44.2.

Correctness

  • Kernel vs fp64 reference, 14 projection shapes x M in {1, 4, 16}, bf16: the mean error is 0.76x of the rocBLAS sequence's or lower in every cell. Output is deterministic, and row 0 is bit-identical whether it is computed alone or in a batch.

  • Training-path logprobs (the forward GRPO trains on) are bit-identical between base and head. Only the decode (sampling) path changes.

  • Decode logprobs on the same 64 forced tokens: base and head differ by 0.025 (Linux) and 0.029 (Windows) mean absolute. The gap between decode and training logprobs, which is what GRPO's importance ratio sees, does not grow:

    Linux base Linux head Windows base Windows head
    mean abs logprob gap 0.0278 0.0271 0.0275 0.0292
    mean KL 1.21e-3 1.08e-3 1.17e-3 1.14e-3
  • Decode graphs on vs off: identical greedy tokens, identical forced-token logprobs, and identical GRPO losses, rewards and grad norms over 5 steps on both OSes.

  • GRPO rewards (5-step mean, 3 seeds): head minus base is +0.33, +0.43, +0.48 on Linux and -0.23, -0.25, -0.08 on Windows. That is inside one standard error of a 20-completion mean (about 0.45) with no consistent sign, and inside the seed-to-seed spread at base.

Tests

tests/test_rocm_skinny_linear.py (new) covers the config heuristic, routing rule, arch gate, kill switch and the fast_linear_forward hook placement, which run on CPU; a Triton-interpreter check of the kernel; and 41 gfx1151 GPU tests for accuracy, determinism, row independence, strided outputs and fallbacks. tests/test_decode_cuda_graphs_default.py gains a test for the ROCm default. On the gfx1151 runners all GPU tests pass on Linux and Windows. tests/test_decode_cuda_graphs_default.py and tests/test_lora_fold_generate.py pass at head on both OSes (47 / 47 fold tests).

Not covered

  • Other gfx11 parts (gfx1100 / 1101 / 1150), RDNA4 and MI300: not measured, so the kernel stays off there by default.
  • Models larger than the measured shapes: projections with K = 4096 and N >= 2560 measured slower than rocBLAS and are not routed.
  • Timings come from the shared-GPU lane (co-tenants possible); A/A pairs are given for every arm.

Update (review fixes)

Every input the kernel cannot take now falls back to the existing rocBLAS path instead of raising mid-decode:

  • LoRA A and B get the same plain-tensor checks as W (subclasses, wrappers, sparse W), a missing B or non-numeric scale falls back.
  • X's width must match W's K, and N, K and R must be at least 1; offsets that would overflow int32 are gated.
  • Mixed autocast dtypes, forward-mode AD and vmap / torch.func fall back.
  • out buffers that overlap an input or themselves, inference tensors outside inference mode and grad-requiring buffers fall back.
  • Bad tuning env values are validated, and a launch that fails to compile switches the kernel off.
  • Decode graphs default on under ROCm only when every visible GPU is gfx1151 (not just the current one at import).
  • The decode hook checks device and adapter trainability before reusing a cached LoRA cast.

The new per-call checks were first about 17 us per projection; the second commit makes them cheap again.

Tests: 15 new CPU tests (Triton interpreter) fail on the previous head and pass now; the 23 existing ones pass on both.

AMD CI gfx1151, same harness as before: greedy tokens, forced decode logprobs and kernel call counts are bit-identical to the previous round on Linux and Windows. GRPO steady step base A/A 9026 / 9042 ms -> 4288 ms on Linux (2.10x) and 10957 / 10973 ms -> 5342 ms on Windows (2.05x); decode tok/s at batch 4 125.7 -> 296.2 (Linux) and 98.9 -> 172.0 (Windows). GPU tests 141 / 137 pass, 0 fail.

gfx1151 recheck at the current head (Linux, shared GPU lane)

9c8176a a1970e1 a529be1 (head)
compiled variants per call site after 1 / 4 / 16 rows 3 1 1
cold first generate at 4 / 16 rows (s) 1.16 / 1.08 0.55 / 0.63
GRPO steady step (merge base 9028.8 ms) 4288.5 ms (2.105x) 4285.4 / 4291.1 ms 4281.4 ms
GPU tests 80 pass 81 pass 82 pass

Tokens, logits and forced-token decode logprobs are bit-identical across all three heads at 1, 4 and 16 rows, and GRPO losses, grad norms and rewards are identical across every run. The out= version bump in a529be1 costs nothing measurable (A/A spreads 0.20% / 0.29%).

gfx1151 Windows (shared lane), 9c8176a vs a1970e1

9c8176a a1970e1
compiled variants per call site after 1 / 4 / 16 rows 3 1
cold first generate at 4 / 16 rows (s) 2.59 / 1.71 0.82 / 0.98
GRPO steady step (merge base 10688 ms) 5257.9 ms (2.033x) 5253.0 ms (2.035x)
GPU tests 80 pass 81 pass

Tokens, logits and forced-token logprobs are bit-identical between the heads at every batch size, and greedy tokens match Linux.

…RL rollouts

rocBLAS runs the M <= 16 decode GEMMs with a 128x128 macro tile on gfx1151,
so each 16-bit decode projection paid three full tile passes (base GEMM,
X @ A.T, LoRA addmm). A Triton kernel streams W once and accumulates the
rank-r term in fp32 beside it, deterministic split-K. Gated to gfx1151 ROCm
outside torch.compile and autograd; UNSLOTH_ROCM_SKINNY_LINEAR=0 disables it,
=all enables it on other gfx11 parts. CUDA is untouched.
…by default

The skinny decode linear now takes K <= 3072 or N <= 1024 (every shape
measured faster than rocBLAS on gfx1151, Linux and Windows); K = 4096
projections with N >= 2560 keep rocBLAS.

With it, HIP graph replay of the decode step was token-identical to the
eager step and GRPO losses equal, and faster, so the RL decode-graph
default extends to gfx1151 while the skinny linear is enabled. Other HIP
archs stay off unless UNSLOTH_DECODE_CUDA_GRAPHS=1.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-23T05:30:26.529529Z 3dd1416 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: e0afc39e54

ℹ️ 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/rocm_skinny_linear.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 24258e72e0

ℹ️ 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".

…he kernel cannot take

Checks on the LoRA operands match W (plain dense tensors only, B and a scalar scale present), X's
width must equal W's K and N, K, R must be at least 1, the out buffer must not overlap any operand
or itself, be an inference tensor outside inference mode or require grad, and offsets must fit
int32. Forward-mode AD, torch.func transforms and a different autocast dtype keep the dispatched
ops. Unlaunchable UNSLOTH_ROCM_SKINNY_LINEAR_CONFIG values are ignored and a launch that fails to
compile turns the kernel off instead of raising mid-decode. The hook decides before the LoRA cast,
so other devices cast once and trainable adapters under grad keep the existing path. The gfx1151
decode-graph default now needs every visible GPU to be gfx1151.
…en gate

The eager decode runs the gate for every projection of every token: one pass of shape, stride and
pointer arithmetic instead of per-tensor helper calls, and the decode call launches without the
public entry point's validation. About 3 us per call over the previous gate on CPU instead of 17.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 9c8176a26e

ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: a1970e1c3d

ℹ️ 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".

…ily negated views

The kernel writes out through a raw pointer, so autograd never saw the
mutation: a buffer saved for backward could be overwritten under no_grad
and backward silently used the new values. Bump the version after a
successful write to a caller's buffer, as torch.matmul(out=...) does
(inference tensors have no counter).

Operands or outputs with the lazy negative bit set expose the un-negated
storage to the kernel; keep the dispatched path for them.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: a529be1078

ℹ️ 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".

…jection, keep quantized models eager by default

- skinny_decode_linear re-raises OOM (generate()'s graph-OOM recovery decides) and HIP launch / capture
  errors instead of returning None; only a kernel compile failure falls back, warns once and latches,
  now per device.
- fast_linear_forward reuses the LoRA cast it made for the kernel when the kernel rejects the call, so a
  rejected decode projection does one _fast_lora_weights lookup as before.
- The gfx1151 RL / generate graph default was measured with 16-bit projections only: quantized models
  there decode eagerly unless UNSLOTH_DECODE_CUDA_GRAPHS=1.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 3dd1416a94

ℹ️ 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 that referenced this pull request Nov 23, 2026
…he constexpr parameters (#19047)

## Summary

`Repo tests (CPU, rest)` fails on `main` since #18874:

```
tests/test_triton_fp_fusion.py::test_every_launch_requests_fp_fusion
E   AssertionError: Triton launches without enable_fp_fusion: ['rocm_skinny_linear.py:269:_skinny_linear_kernel', 'rocm_skinny_linear.py:302:_splitk_reduce_kernel']
tests/test_triton_constexpr_comments.py::test_every_constexpr_line_has_a_comment
E   AssertionError: tl.constexpr parameters without a comment:
E     unsloth/kernels/rocm_skinny_linear.py:66 _skinny_linear_kernel.HAS_LORA
...
```

## Root cause

The new kernel, not the guards. #18874 added
`unsloth/kernels/rocm_skinny_linear.py` without the two conventions
every other kernel follows:

- Triton 3.9.0 changes the `enable_fp_fusion` default to `False`, so a
launch that does not ask for it loses FMA contraction there: slower, and
numerically different from every other kernel. Both launches
(`_skinny_linear_kernel` and `_splitk_reduce_kernel`) relied on the
default.
- Its nine `tl.constexpr` parameters had no comment saying what they
are.

## Fix

`unsloth/kernels/rocm_skinny_linear.py` only:

- `enable_fp_fusion = True` on both launches. Triton 3.8 and earlier
already default to `True` (checked in 3.8.0's AMD and NVIDIA backend
options), so the compiled kernels do not change there; 3.9.0 defaults to
`False`, and this keeps them fused.
- A short comment on each `tl.constexpr` parameter.

## Testing

- `tests/test_triton_fp_fusion.py`,
`tests/test_triton_constexpr_comments.py`: pass (both failed on `main`).
- `tests/test_rocm_skinny_linear.py`: 34 passed; its 51 GPU cases skip
on this CPU host. The launch change only makes today's default explicit.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
## Summary

`Repo tests (CPU, rest-2)` fails on `main`:

```
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
E   AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['tests/test_inkling2_parallel.py:104: read_text()']
E   AssertionError: ... ['tests/test_rocm_skinny_linear.py:668: read_text()']
```

## Root cause

The new tests, not the guard. Two recent suites read a checked-in source
file with `read_text()` and no encoding, which on Windows decodes with
the locale code page:

| File | Added by |
|---|---|
| `tests/test_inkling2_parallel.py:104` (reads
`unsloth/models/loader.py`) | #18959 |
| `tests/test_rocm_skinny_linear.py:668` (reads
`unsloth/kernels/rocm_skinny_linear.py`) | #18874 |

## Fix

Pass `encoding = "utf-8"` on both reads. Tests only.

## Testing

- `tests/test_source_read_encoding.py`,
`tests/test_inkling2_parallel.py`, `tests/test_rocm_skinny_linear.py`:
60 passed, 51 skipped (GPU cases). The guard failed on `main` without
this change.
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