Repository navigation
ROCm: use flash varlen for packed rows so hybrid packing is faster than padding - #18313
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…18343) ## Comment the BLOCK constexpr on the bf16 stochastic rounding kernels `tests/test_triton_constexpr_comments.py` fails on `main` since #18282. It shows up in `Repo tests (CPU, rest)` on unrelated PRs, for example #18312 and #18313: ``` E AssertionError: tl.constexpr parameters without a comment: E unsloth/optimizers/bf16_stochastic_rounding.py:60 _round_kernel.BLOCK E unsloth/optimizers/bf16_stochastic_rounding.py:83 _adamw_kernel.BLOCK ``` ### Cause That lint requires every `tl.constexpr` parameter of an Unsloth Triton kernel to sit on its own line with a comment saying what it is. It does this because each distinct constexpr value compiles a new kernel. #18282 added `_round_kernel` and `_adamw_kernel`, whose `BLOCK` constexpr has no comment. `_round_kernel` also takes it inline on the `def` line. ### Fix Both kernels now take `BLOCK` on its own line with a comment: `# elements per program, fixed at _BLOCK`. `_round_kernel`'s signature is split one parameter per line to match. No behaviour changes. The parameters and their order are unchanged, and every launch still passes `BLOCK = _BLOCK` (1024). ### Verification - `tests/test_triton_constexpr_comments.py`: fails on `main` on these two lines and passes with this change. - `tests/test_bf16_stochastic_rounding.py`: 13 passed, 2 skipped on CPU across the two files. - ruff is clean.
|
Verified on real gfx1151 (Linux and Windows 11), merge base vs head on the same runner, and pushed two test-only fixes (638534b).
Test fixes:
|
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…rlen runs there (unslothai#18362) Follow-up to unslothai#18313. Two tests in `tests/test_hf_packed_attention.py` fail on ROCm since unslothai#18313 turned torch's flash varlen on there (seen on gfx1151 Linux and Windows 11). Test-only change, no library code touched. - `test_rocm_keeps_windowed_rows_off_flash_attn` fakes `torch.version.hip` to test the flash-attn window gate. On a card where unslothai#18313's self-check now passes, packed rows take torch varlen instead and never reach the flash-attn backend the test checks, so both window cases failed (B200 with ROCm faked, and gfx1151 Linux). The test now pins torch varlen off (`_TORCH_VARLEN = [None]`), the case it was written for. Removing the window gate still makes it fail, so it keeps guarding that gate. - `test_int32_guard_splits_documents_instead_of_the_dense_fallback[torch-*]` now runs on ROCm and asserts bit equality between the split and whole-row results. AOTriton rounds one bf16 step (0.0078) differently per launch shape on Windows. CUDA keeps the exact comparison; ROCm uses the same tolerance as unslothai#18313's self-check. AMD CI (oobabooga/unsloth) Windows rerun 44340636929 with both changes: 117 passed, 0 failed in this file; without them it fails 4.
…kernel matches its real outputs (unslothai#18393) Follow-up to unslothai#18313. On ROCm, a compiled decoder block holding packed rows fails with `wrong number of dimensions3 for op: torch.ops.aten._flash_attention_forward.default`. **Cause.** The in-graph varlen probes (`_varlen_in_graph` in `unsloth/utils/hf_packed_attention.py`, `_packed_varlen_ok_eager` in `unsloth/utils/attention_dispatch.py`) only ran torch's flash varlen op eagerly. Inside a compiled graph the op's outputs are checked against its fake kernel, and on ROCm the real logsumexp has a different rank than the fake kernel declares. So every compiled block with packed rows failed: - block compile dropped the block and kept the stock forward ("block compile failed ... keeping the stock forward"), losing the compiled speed; - a path with no such recovery crashed at run time. CUDA's real and fake shapes match, so only a ROCm run shows it. **Fix.** Both probes also compare the real call's output and logsumexp shapes with the fake kernel's (under `FakeTensorMode`). On a mismatch the op is reported unusable inside the graph, and packed rows use the eager varlen wrapper, which works on ROCm. CUDA is unchanged: on B200 the probe still passes for head dims 64, 128 and 256 (`[(16, 4, 128), (4, 16)]` real and fake), and bf16 packed parity numbers are identical. **AMD gfx1151 Linux** (torch 2.11.0+rocm, transformers 5.23.0, tiny Qwen2.5-VL packed SFT), before run 44389058128, after run 44393091645: | Cell | Before | After | |---|---|---| | bf16 packed vs per-document parity | crash in `aten._flash_attention_forward` | passes (logit diff 4.9e-3, leak 0.0, negative control live) | | fp32 parity | passes | passes (logit 8.4e-7, grad rel 1.8e-6) | | packed SFT | trains, but "block compile failed" twice | trains, no block compile failures; packed rows still run in compiled blocks | | `tests/test_hf_packed_attention.py` | | 120 passed, 0 failed | **Tests.** Three CPU tests: the shape check passes when the logsumexp rank matches, fails when it differs, and the probe refuses the in-graph path when it fails.
…d instead of attending over the dense mask (unslothai#18435) ## Summary Follow-up to unslothai#18393. On ROCm builds where torch's flash varlen cannot run inside a compiled graph (its fake kernel declares a logsumexp of another rank, seen on gfx1151 with torch 2.11), packed rows in a compiled decoder block now leave the block and run the eager varlen wrapper. Before this change they stayed in the block and attended with SDPA over the dense `[T, T]` mask, while `HF_PACKED_ATTENTION_STATS["compiled"]` counted them as varlen. ## Root cause `_block_varlen_prepare` (`unsloth/utils/hf_packed_attention.py`) returned `(cu_seqlens, carrier)` without asking whether the varlen op can run in the graph. Inside the block, `_varlen_in_graph` then returned False, `_leaves_block` is always False on ROCm (it only targets slow cuDNN plans on CUDA), so the call ended at the wrapped `orig(...)`: dense SDPA inside the compiled block. Before unslothai#18393 that block failed to compile and the stock eager forward ran varlen, so on ROCm unslothai#18393 traded a graph break for dense attention (unslothai#18313 measured dense SDPA at 98.5 ms vs 11 ms for varlen at 2048 tokens). ## Fix On ROCm only, for fp16 / bf16 rows with head dim up to 256, `_block_varlen_prepare` asks `_varlen_in_graph` (the same cached probe the traced call uses). When it refuses, it returns `_LEAVE_BLOCK`, as the int32 overflow branch already does, so `_sdpa_packed_varlen` calls the eager wrapper (`torch.compiler.disable`), which runs torch's varlen op. These rows are no longer counted as `compiled`. CUDA builds, ROCm builds whose varlen traces, and fp32 rows keep the current route. ## Tests New `tests/test_hf_packed_attention_rocm_leave_block.py` (CPU, ROCm faked through `torch.version.hip`, probes stubbed): - ROCm with the in-graph probe refusing: `block_varlen_kwargs` returns `_LEAVE_BLOCK`, the compiled counter does not move, and a compiled call reaches the eager wrapper and torch's varlen once with no dense SDPA call. - CUDA (probe True or False), ROCm with the probe passing, and ROCm fp32 rows keep `(cu_seqlens, carrier)` and count as compiled. Both arms on CPU (`-o addopts= -m "not server and not native_mxc"`), each importing its own tree: | Arm | New test file | `tests/test_hf_packed_attention.py` + new file | |---|---|---| | main (merge base) | 1 failed (`_LEAVE_BLOCK` expected, got the tuple), 4 passed | 1 failed, 76 passed, 102 skipped | | this branch | 5 passed | 77 passed, 102 skipped | ## Not proven here - AMD gfx1151 timing and parity with this change (packed SFT step time vs unslothai#18313's varlen numbers) need a real run through the AMD CI. - The GPU-marked tests in `tests/test_hf_packed_attention.py` were skipped on this CPU host.
…heck out of Unsloth's attention (unslothai#18453) Addresses unslothai#18403 ## Problem On an RX 9060 XT (gfx1200, RDNA4), QLoRA training aborts on the first step with `HIP error: an illegal memory access`. The fault shows up in whatever kernel runs next: SwiGLU, fused CE, `fork_rng`, the decode graphs. With `AMD_SERIALIZE_KERNEL=3` the first failure is `hipErrorInvalidValue` from `F.scaled_dot_product_attention` in `_sdpa_packed_segments`. 2026.9.7 trains on the same machine. The reporters bisected it to unslothai#12740 and unslothai#14158. ## Root cause `unsloth/__init__.py:29` sets `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1` (since unslothai#8821, already in 2026.9.7). Torch then offers AOTriton's flash and memory-efficient kernels on every arch AOTriton only lists as experimental, which is all of RDNA. Until 2026.9.7, Unsloth's GQA training calls on ROCm never reached those kernels: packed and padding-free rows ran SDPA over a dense block mask with `enable_gqa=True`, and only math accepts that combination. - **unslothai#12740** (`5babb22c69`, 2026.10.1) runs each packed segment as its own causal call with K/V expanded on ROCm (`_sdpa_packed_segments`, `attention_dispatch.py:1117`). Torch picks AOTriton flash for that call. - **unslothai#14158** (`e6c95c292b`, 2026.10.7) expands K/V whenever `enable_gqa` would leave only math (`_sdpa_gqa_state_now`, `attention_dispatch.py:907`, used by the dense path at `:2133` and by the segment runs). On ROCm that sends masked calls to the AOTriton memory-efficient kernel. This is why `UNSLOTH_SDPA_PACKED_SEGMENTS=0` stopped helping from 2026.10.7 on. Both choices are right wherever the kernels work. On gfx1200 the reporters show they do not. Upstream has matching RDNA4 reports for these kernels: [pytorch#201476](pytorch/pytorch#201476) (gfx1201 memory-efficient SDPA wrong in fp32), [ROCm/TheRock#10001](ROCm/TheRock#10001) (gfx120X memory-efficient grads fail tolerance), and [ROCm/TheRock#10054](ROCm/TheRock#10054) (gfx1201 FLASH and EFFICIENT fail with `hipErrorInvalidImage`). ## Fix The new `unsloth/utils/rocm_sdpa_check.py` checks each AOTriton backend once per GPU: - **Isolation.** The check runs in a child process with `AMD_SERIALIZE_KERNEL=3`, because a fault poisons the HIP context. Flash and memory-efficient each get their own child, and the two run side by side. - **Shapes.** The child sends the GQA shapes Unsloth uses: per-segment strided views, expanded K/V, `enable_gqa`, and a boolean block mask. It covers fp16 and bf16, head dims 64 and 128, and segments of 1300, 748 and 37 tokens. - **Comparison.** Forward and backward are checked against an fp32 reference, with the same tolerance as the unslothai#18313 varlen self-check. - **Failure.** A backend fails if it errors, faults, hangs or disagrees with the reference. A failed backend is left out of every SDPA call in `attention_dispatch` on that GPU: packed segments, the dense path, decode, and the GQA probe that picks between `enable_gqa` and expanded K/V. The remaining backends run, down to math, which is what 2026.9.7 used. - **Output.** When a backend fails, a one-line message names the arch and the failing case. Scope: - CDNA (gfx9xx) is AOTriton's release target and skips the check. - CUDA builds are unchanged: the guard is a module constant that is False there. - If a caller has enabled only refused kernels (`sdpa_kernel([FLASH])`), its own policy is kept. - `UNSLOTH_ROCM_SDPA_CHECK=0` skips the check and trusts torch, which is the current behaviour. - `rocm_sdpa_verdict(device_index)` is exported from `attention_dispatch` so users can see what the check decided. ## Evidence **Flip test.** `tests/utils/test_rocm_sdpa_check.py` fakes ROCm on CPU tensors. | tree | result | |---|---| | main (55ef8bd) | 6 failed: packed segments x3, dense masked, decode, GQA probe all still run with the refused kernels enabled | | this branch | 14 passed | **Existing attention suites.** On CPU, `test_sdpa_packed_segments`, `test_attention_native_routing`, `test_attention_training_no_cudnn`, `test_attention_masks`, `test_attention_rerouted_sdpa`, mixed devices, fp32 routing, single row cache, eval backward and bidirectional: 215 passed, 27 skipped. On B200 with `-m "gpu or not gpu"`: 119 passed. **The child on a GPU whose kernels are correct (B200).** Flash and memory-efficient pass all 8 cases each, in 5.7 s wall. Two negative controls: - Scaling the kernel output by 1.05 fails every case, at 2.5x the bound. - A child that exits without a result refuses both backends. **AMD gfx1151, Linux, torch 2.11.0+rocm7.13.** Tiny Qwen3 with head dim 128 and 8/2 heads, the reporters' settings, run on main and on this branch: fp16, 4-bit LoRA, standard checkpointing, batch 2, padding-free, `train_on_responses_only`, about 2k-token rows. - **main:** trains, with or without `AMD_SERIALIZE_KERNEL=3`. - **this branch:** the check passes both backends, so routing and losses are identical to main (AOTriton flash, same six losses). - **this branch, check forced to fail:** every attention call goes to math. Logits match a math-only forward and training stays finite. On gfx1151 the check takes 3.1 s. A kernel matrix at the reporters' shape (32/8 heads, head dim 128, 2048 tokens, fp16 and bf16, forward and backward, `AMD_SERIALIZE_KERNEL=3`) shows flash and memory-efficient correct on every layout they accept (AMD CI run 44502291477). gfx1151 does not reproduce the gfx1200 fault, so this run shows two things: the fix costs nothing where the kernels work, and the refusal path works on real AMD hardware. It does not prove the fix on gfx1200. ## What gfx1200 users should check - On import plus the first attention call, look for the line `Unsloth: ROCm gfx1200 0: AOTriton ... attention failed a self-check`. - Check `from unsloth.utils.attention_dispatch import rocm_sdpa_verdict; print(rocm_sdpa_verdict(0))` after loading a model. - If the check passes and training still faults, please report the verdict. It means the failure needs a shape the check does not cover. ## Not covered - **gfx1200 itself.** No such card is reachable here. - **The HF attention path.** Models that do not go through `attention_dispatch` (`hf_packed_attention`, transformers' own sdpa integration) keep the current behaviour. - **Memory.** When both AOTriton backends are refused, attention runs on math. That costs (H, L, L) scores per segment, which is less than the dense (T, T) mask 2026.9.7 used, but more than the fused kernels.
…-check (unslothai#18611) Follow-up to unslothai#18313 and unslothai#17738. ## Why ROCm was opt-in unslothai#13383 made hybrid packing (Qwen3.5, Qwen3.5-MoE, Qwen3-Next, and the PLE layers from unslothai#14011) default-on for CUDA only. At the time `UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1` failed closed on gfx1151 because the boundary-aware causal conv was not allowed on HIP (unsloth-zoo unslothai#2503 fixed that), and once it worked, the full attention layers still ran SDPA over a dense `(T, T)` mask on ROCm, so packing was a wash (unslothai#17738). unslothai#18313 moved ROCm packed rows onto torch's flash varlen behind a one-time self-check, which removes that cost. ## Change With the variable unset, `_auto_hybrid_device_ok` now also accepts a ROCm GPU when the unslothai#18313 self-check (`hf_packed_attention._torch_varlen`) passes on that device. The check runs once per device (about 0.3 s on gfx1151) and is cached. Everything else is unchanged: - The same mixer kinds as CUDA (gated delta and PLE), and the existing exactness probe still runs before any packing. - A ROCm build whose flash varlen fails the self-check keeps the padded path, with the reason logged. - `=0` still turns packing off and `=1` still opts in Mamba2 / split QKV mixers and other devices. - CUDA is unchanged. The opt-in note from unslothai#17751 now says the path is "not on by default on this device" instead of naming CUDA only. ## gfx1151, Linux, torch 2.11.0+rocm7.13, transformers 5.5.4 Fake Qwen3.5-4B shaped model (real 4B layer sizes, 4 layers, random weights), LoRA r=16, `packing = True`, `max_length 2048`, batch 4, variable unset vs `=0`. Two runs per arm. | arm | packed | median useful tok/s | median s/step | first losses | |---|---|---|---|---| | main, unset | no (padded) | 1691 | 2.96 | 12.9115, 12.9003, 12.9244 | | main, `=0` | no | 1687 | 2.95 | 12.9115, 12.9003, 12.9244 | | this PR, unset | yes | 2417 | 3.38 | 12.9344, 12.8879, 12.9011 | | this PR, `=0` | no | 1699 | 2.97 | 12.9115, 12.9003, 12.9244 | Default ROCm runs now pack and train at about 1.42x the padded throughput. The packed losses are the same values unslothai#18313 measured for the opt-in path, and `=0` is unchanged. ## Tests `tests/utils/test_hybrid_packing_default.py` adds a case with a ROCm GPU weight where the self-check passes (default-on) and fails (padded, reported as an opt-in device). Reverting the change fails the passing case.
Fixes #17738
Problem
On ROCm, packed rows never reached a varlen attention kernel.
_torch_varlen()inunsloth/utils/hf_packed_attention.pyreturnedNonewhenevertorch.version.hipwas set, so every full attention layer of a packed row fell back to SDPA over a dense(T, T)block diagonal mask. For a hybrid model like Qwen3.5 withbatch_size 4 x max_length 2048, that is one 8192 x 8192 masked attention per layer, which cancels out the benefit of packing. This matches the report on gfx1151: half the steps, but each step nearly twice as slow.Fix
ROCm can now use torch's flash varlen (AOTriton) for packed rows, gated by a one-time numeric self-check per device:
_hip_varlen_matches()runs a GQA forward and backward over 3 documents (head dims 128 and 256, bf16) through both entry points Unsloth uses (varlen_attnin eager,aten._flash_attention_forwardinside compiled blocks) and compares the output and all three grads against an fp32 per-document reference. Any error or mismatch keeps the current dense mask path, so a broken build behaves exactly as today._hip_window_ok()), since ROCm flash backends list windows as work in progress. If it fails, windowed layers keep SDPA and windowless layers still use varlen.The verdict is cached per device, so repeated calls and repeated trainer setups are no-ops.
Results on gfx1151 (Strix Halo)
Training, Linux, torch 2.11.0+rocm7.13, transformers 5.5.4
Fake Qwen3.5-4B shaped model (real 4B layer sizes, 4 layers: 3 gated delta + 1 full attention, random weights), LoRA r=16,
max_length 2048,per_device_train_batch_size 4,UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1for the packed arms. Same data and seed in every arm. Useful tokens/s is the median over steps 3 to 12 of non-padding tokens per second; each cell lists separate runs from two jobs.On main, packing is a wash against padding (the report in #17738). With this PR, packed training is about 1.37x the padded useful tokens/s and about 1.39x main's packed run. Packed losses match main's packed losses within 3e-4 and grad norms match to 3 decimals. Every packed attention call took the varlen route (25 fast, 0 fallback). Padded runs are unchanged.
Attention kernels, forward plus backward
Max relative error of output and grads against an fp32 per document reference is within 7e-3 for flash varlen in every case below, the same as the dense mask path on main (bf16; fp16 within 6e-4).
Self-check
On both Linux and Windows 11 the self-check turns varlen on (plain and windowed) and costs 0.26 to 0.73 s once per device, plus 0.03 to 0.12 s for the window check. On main the route stays off on ROCm.
Tests
tests/test_hf_packed_attention.pyadds CPU tests withtorch.version.hipfaked: an exact varlen turns the route on, a varlen that leaks across documents or raises keeps it off, and a varlen that is only wrong with a window keeps windowed rows on SDPA while windowless rows still use varlen.