Repository navigation
fix(amd): turn on PyTorch's fast ROCm attention kernels on import unsloth, and drop the installers' host-wide export - #8821
Conversation
On a ROCm build torch hides its AOTriton flash and mem-efficient SDPA kernels behind TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL, read once while loading its C++ extension. With the gate shut every sub-quadratic backend declines, SDPA falls through to MATH, and MATH materialises the full B x H x N x N score matrix, so peak memory grows with the square of the context. Finetuning pays that twice over: the scores are needed again for the backward pass. For a 32-head model in fp16 the score tensor alone is 1.07 GB at 4k tokens, 4.3 GB at 8k and 17.2 GB at 16k, before the softmax output. On a 16 GB card that is the difference between a 4-8k context and a 32k one. Nothing opened the gate on the library path. install.sh sets it only inside _persist_rocm_wsl_dropin(), which returns early unless librocdxg.so is present, so it fires on ROCm-on-WSL and nowhere else; install.ps1 never sets it. A user who pip installs unsloth on bare-metal Linux or Windows AMD, or runs a notebook, got the O(N^2) path. Set it at the top of unsloth/__init__.py, before anything can import torch. Any pre-existing value wins, including "0", which is the opt-out for someone who hits an AOTriton bug and wants the math fallback back. Set unconditionally because knowing the build means importing torch, and by then the value has already been read; non-ROCm torch never looks at a TORCH_ROCM_* variable. Complements unslothai#8323, which opens the same gate inside the Studio backend process. The two are separate copies on purpose: this one must stay importable with nothing but stdlib, and that one is vendored into a backend that never imports unsloth.
Windows answered: the wheel ships AOTriton, and the variable is the only thing holding it shutRX 9060 XT (gfx1200), Windows, The wheel carries the kernels: Torch's own flags claim the backends are on: They are not. With the variable unset, every forced-backend call fails:
16 of 16 fail unset, 16 of 16 pass set. Torch names the variable itself in the warning it emits on the way past: Accuracy against the math backend at that shape, fp16 causal: max abs diff Two things this pins down:
gfx1201 shares the On "experimental"The gating is AMD's, not a formality, and RDNA4 backward is the least-exercised path in it. Worth The comparison is not "experimental kernel versus safe kernel". It is "experimental kernel versus Anyone who hits trouble sets the variable to |
…works The variable was only ever exported by _persist_rocm_wsl_dropin, which is gated on librocdxg.so -- so WSL Strix Halo got it and every other ROCm host, Windows included, did not. install.ps1 now persists it to User scope on the confirmed ROCm branch, ahead of any process the user later starts, so a plain `import torch` script that never reaches unsloth is covered too. A pre-existing value wins, including "0", matching enable_rocm_aotriton_attention. The docstring claimed torch reads the variable once while loading its C++ extension, making the __init__ call an ordering race it had to win. It does not: torch reads it when it selects an SDPA backend. Setting it after `import torch` enables the kernels just as well, measured on gfx1200 with torch 2.11.0+rocm7.13.0, while unset and "0" both fail with "No available kernel". That claim was load-bearing for where this belongs, and it was wrong, so the measurements are recorded in the docstring. The __init__ call stays first regardless: the read point is a torch implementation detail, not a guarantee. Also drops the reference to unslothai#8323 opening the same gate in the Studio backend. That PR is still open, so no such gate exists.
_persist_rocm_wsl_dropin exports the variable, but it is gated on librocdxg.so, so only WSL Strix Halo ever reached it -- a native Linux ROCm install got nothing and fell to MATH SDPA exactly as Windows did. Persist it from the confirmed pip-ROCm-family branch instead, next to where install.ps1 now does. Skips when the WSL drop-in already wrote the variable, and when the user holds an opinion, including "0". Best-effort /etc/profile.d write mirroring the WSL helper: root writes directly, non-root sudo-tees, and neither path can abort the installer.
|
AOTriton attention on ROCm: measured impact Rig: AMD Radeon RX 9060 XT (gfx1200, 15.92 GB), ROCm 7.13, torch 2.11.0+rocm7.13.0, Windows. What the flag doesUnset or Kernel benchmarkSingle process, backends forced per call with
A Qwen3-0.6B shape (16 heads) tracks the same curve: 5.9× at 4096, 10.8× at 8192, up to 31× on memory. mem-efficient stays within a few percent of flash throughout, so either backend resolves it. Scaled by layer count, at B=2 / N=4096 attention alone costs 38.2 s per step under MATH against 3.7 s with flash. Above 4096 MATH does not run at all on a 16 GB card, which is the real ceiling here: ~4k context closed, 8k+ open. End-to-end training: null resultFull finetunes through Unsloth Studio did not show this. Including them so nobody rediscovers it.
Each pair processed a byte-identical token count. Don't read the first two rows as signal:
The informative runs died: both packed 4096 Llama runs and an 8192 run OOM'd, and that traced to the logits tensor (4096 × 128256 × 4 = 1.96 GiB, matching the reported 1.99 GiB), not attention. Separate issue. Short version: this matters for long context and packed sequences. Short-sequence finetuning won't see it. CaveatsSynthetic Q/K/V, not real activations. Kernel-level only, so end-to-end gain is diluted by MLP, projections and optimizer work. Single card, single ROCm/torch version, gfx1200. Forward-only at N=8192 measured 3559.8 ms for MATH, well off the N² trend and likely allocator pressure near the ceiling rather than compute, so I've left it out of the table. Request@danielhanchen could you run this on Strix Halo with a larger model and longer context? A 16 GB gfx1200 hits the MATH memory wall at 4096, right where the curve gets interesting, so I can measure the kernel in isolation but can't demonstrate the training-level win on this machine. Packing on, 8k or 16k, something 8B+ should settle it. Happy to reshape the benchmark script to whatever's most useful. |
|
Correction on the Strix Halo ask: gfx1151 needs a TheRock nightly ( Also worth linking: ROCm/ROCm#6034 is an independent gfx1151 campaign measuring SDPA at 44 ms → 2.3 ms from this same variable, and arguing it should be on by default. Same conclusion from a different direction. That issue does log bf16 instabilities on gfx1151 with AOTriton active, which is a fair argument for keeping the existing |
…uto-reroute A gfx*/rocm* pin via UNSLOTH_TORCH_INDEX_URL or UNSLOTH_TORCH_INDEX_FAMILY sets $TorchIndexPinned, which skips the auto-reroute block outright; $ROCmIndexUrl is resolved in the pinned branch below it instead. The persistence sat inside the auto-reroute, so those installs still got ROCm torch with the gate shut and fell back to MATH. Moved to the join point where both routes have resolved $ROCmIndexUrl. install.sh already hooks the final resolved index leaf, so the shell side was never affected. Regression tests pin both placements.
…nto fix/amd-aotriton-library-gate
|
Fixed the P2 and merged main. Head is The finding was right. The persistence lived inside the auto-reroute, which only runs when nothing is pinned, so a It now sits at the join point where both routes have settled
Added two tests that pin the placement rather than the behaviour, since the behaviour was always correct and only the location was wrong: the PowerShell call must follow the pinned-index routing and sit under the The main merge also brings in #9252, which is what was failing |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cca32b1a1d
ℹ️ 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".
| printf '%s\n' "$_aot_dropin" > /etc/profile.d/unsloth-rocm-aotriton.sh 2>/dev/null || true | ||
| elif command -v sudo >/dev/null 2>&1; then | ||
| printf '%s\n' "$_aot_dropin" | sudo tee /etc/profile.d/unsloth-rocm-aotriton.sh >/dev/null 2>&1 || true |
There was a problem hiding this comment.
Persist the gate outside login-only profiles
With the documented curl ... | sh installation, the export occurs in the child installer and cannot update the invoking shell, while /etc/profile.d is normally sourced only by login shells. Consequently, running a plain import torch afterward in the same terminal—or from an IDE/service that never starts a login shell—still lacks the gate, despite this helper specifically intending to cover code that does not import Unsloth. Persist this in an environment source used by those launches, such as the installed venv's activation/launcher path, or explicitly arrange for the new profile to be loaded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this. /etc/profile.d is the mechanism this repo already uses for this exact variable: _persist_rocm_wsl_dropin at install.sh:4128-4152 writes TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL the same way, and the new helper mirrors it deliberately, down to skipping its own drop-in when that one is present.
The gap named here is real but bounded to a plain import torch in the shell that invoked the installer, before the next login, and there it degrades to the MATH path that ships today rather than to anything incorrect. The two remedies suggested do not close it. A child installer cannot modify the environment of the shell that ran it, so arranging for the profile to be loaded is not available. And writing the variable into the venv activation script would only reach shells that source that script, not the IDE or service launches the item cites, since those invoke the venv interpreter directly and never run activate.
The library path is covered in-process by unsloth/init.py regardless of which shell started it.
|
Confirmed the variable is only set inside the WSL drop-in at install.sh:4132, so bare-metal and pip-only ROCm installs do land on the MATH path, and the gate in unsloth/init.py sits above every import that reaches torch. Note this overlaps #8922, which fixes the same gate, so one of the two should probably close. The Loaded-models indicator (cross-browser) job is red here and green on main, though it has been flaky lately, so worth a look. |
|
Re-checked against main: the variable is still set only inside the WSL drop-in at install.sh:4274, so pip and bare-metal ROCm installs do land on the MATH path, and both setdefault calls sit above every import that reaches torch. Since #8922 is a subset of this and still open, I will take this one and close that. |
|
This is the one PR of the seven that nobody had actually run, and its claim is a runtime behaviour claim, so I measured it on a real gfx1151 Strix Halo box on Linux/ROCm. Result: the defect reproduces at the base and is gone at the head. Real issue, real fix, and inert everywhere else. Details and evidence below. Before and afterBefore: on a ROCm machine whose architecture AOTriton flags as experimental, PyTorch refuses the flash and memory-efficient SDPA backends and silently falls back to MATH. The installers papered over this by writing a host-wide export into After: It is a real issue, measuredOn the runner, torch's own stderr at the base says it verbatim: gfx1151, hip 7.13.99004, torch 2.11.0+rocm7.13.0, identical GPU and build at both states:
So the base is not merely ineligible on paper. Both explicit-backend runs raise That last part mattered to me: opening a flag the vendor gates as experimental is only a fix if the kernels it unlocks are numerically sound. On this architecture they are. That is an arch-specific finding, not a general one. I wrote the criteria so that a base which does not show the defect produces VOID rather than a pass, precisely so this could not be a rubber stamp. It came back CONFIRMED on its own terms. Does it break non-AMDNo, and I checked this two independent ways rather than trusting one. By source. The env read sits inside By measurement on a B200. SDPA capability and output are byte-identical across the variable being unset, Twelve runs produced one loss array and one grad-norm array. The parameter-checksum spread within a single config (9e-6) equals the spread between configs, so the only variation present is ordinary non-determinism. CPU-only. In a genuinely CPU-only venv (torch 2.14.0+cpu, verified Across the OS and accelerator matrix. Studio's
What the hardware could not answer
One operational note for anyone else using the AMD pool: only one job may hold the GPU, so the first attempt at this run was evicted by a concurrently dispatched job and had to wait out the group. The measurement above is from the clean re-run. |
|
Follow-up with the Windows result I promised. Also CONFIRMED, on a real Windows 11 Pro gfx1151 box under PowerShell 5.1, and it closes the spawn-inheritance question, which was the Windows-specific risk.
|
| starting state | base, import unsloth |
head, import unsloth |
base, import main (Studio) |
head, import main |
|---|---|---|---|---|
| unset | unset | 1 |
unset | 1 |
"0" |
0 |
0 |
0 |
0 |
"1" |
1 |
1 |
1 |
1 |
An explicit "0" opt-out is preserved on Windows exactly as intended. Identical at the merge commit.
The value does reach spawned workers
This is the question that matters on Windows, since it spawns rather than forks, and an env var set in the parent is only useful if children inherit it. Measured in all three shapes Studio actually uses, at the head:
mp.get_context("spawn").Process, which is literally whatstudio/backend/core/training/training.pyuses (_CTX = mp.get_context("spawn"))subprocesswith noenv=, the sd-cpp and llama-server shapesubprocesswithenv=os.environ.copy()
All three children read 1. A preserved "0" also propagates as 0, so a worker is never forced to 1 after a user opts out.
Two non-vacuity checks, because "child reports the right value" is easy to fake: at the base with the variable pre-set to "1" in the job environment, all three children read 1, proving the reader can see a value at all; and a fourth deliberately scrubbed control child read unset in all 18 runs at every state, proving it is not fabricating one.
The deleted /etc/profile.d export was a no-op on Windows, verified
Not assumed. On the box, C:\etc\profile.d does not exist and the variable read unset in the Machine, User and Process scopes. In the tree, the only files naming it at base are install.sh and scripts/install_rocm_wsl_strixhalo.sh, both POSIX shell and WSL/Linux-only. A scan of every .ps1, .bat and .cmd in the checkout found zero references at base and at head. So nothing on the native Windows path ever set it, and removing it cannot regress Windows.
The PR's own guard tests ran here too: 15 passed, 3 skipped at head and merge.
What this box could not answer, stated plainly
Torch is not installed on the Windows runners (host.json reports torch: null). So whether opening the gate changes ROCm SDPA backend selection, and whether the AOTriton kernels are numerically correct, is unmeasurable on Windows and is answered only by the Linux/ROCm result in my earlier comment. The agent deliberately did not install a CPU wheel to fill the gap, which was the right call: that would have answered the question wrongly rather than not at all.
Also unanswered here:
- A full Studio backend start.
studio/backend/main.pyimports identically at base and head and stops at the same place for the same reason,ModuleNotFoundError: No module named 'jwt', because the Studio dependency set is not installed on these boxes. What is shown is that the gate lands above every third-party import and that head is no worse than base, not that the backend serves traffic. - Whether a ROCm-enabled torch exists for Windows at all on this pool is unmeasured.
- Docker is not installed on any of the four Windows runners, so a containerised Studio on Windows is unreachable from here.
- No NVIDIA, one GPU only, no Intel GPU, no Apple Silicon.
Between the two legs, the picture is complete for the platforms available: on Linux/ROCm the gate demonstrably unlocks working, numerically sound kernels and cuts default SDPA memory about 12x; on Windows it lands correctly, respects an opt-out, and reaches spawned workers. I am happy with this one.
|
@codex security review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
|
On the four red checks here: none of them are this PR. Recording the evidence so nobody has to re-derive it.
I ran the same test on a clean This PR touches five files and that is not one of them: The three So all four are pre-existing. The encoding one is a genuine small bug worth its own PR, since a |
|
Merged current The branches had drifted far enough that CI was testing a stale combination rather than the change. The clearest case:
Merged cleanly with no conflicts. Verified before pushing:
Two other red checks that were also main's rather than this branch's, for the record:
Still genuinely outstanding and not from this branch: |
|
Re-validated on current main (1e07231) with the branch merged: real gfx1151 Strix Halo hardware on Linux and Windows, an NVIDIA B200, a CPU-only torch, and the installer matrix. One comments-only commit pushed today. This is the branch I am keeping over #8323, which I have closed with the comparison. Before and afterBefore: on a ROCm build whose architecture AOTriton flags as experimental, torch refuses the flash and memory-efficient SDPA backends and falls back to MATH, whose peak memory grows with the square of the sequence. The installers papered over it with a host-wide export in After: Evidence on real gfx1151, Linux, torch 2.11.0+rocm7.13.0
Torch's own stderr at the base says it: Windows 11 gfx1151, PowerShell 5.1: from an unset start both entry points read Hosted runners: Does it change anything on NVIDIA, CPU or MacNo. PyTorch reads the variable only inside Second pass: the ROCm-on-WSL helper pin
Old installs and updatingA WSL host that already has the old Not tested hereOnly gfx1151 was measured; whether AOTriton's kernels are numerically sound on other experimental architectures is not established by this run. Torch is not installed on the Windows runners, so backend selection on Windows was not measured, only the value and its inheritance. No Intel XPU or Apple Silicon hardware. |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
…loth, and drop the installers' host-wide export (unslothai#8821) * fix(amd): open the ROCm AOTriton attention gate for library users too On a ROCm build torch hides its AOTriton flash and mem-efficient SDPA kernels behind TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL, read once while loading its C++ extension. With the gate shut every sub-quadratic backend declines, SDPA falls through to MATH, and MATH materialises the full B x H x N x N score matrix, so peak memory grows with the square of the context. Finetuning pays that twice over: the scores are needed again for the backward pass. For a 32-head model in fp16 the score tensor alone is 1.07 GB at 4k tokens, 4.3 GB at 8k and 17.2 GB at 16k, before the softmax output. On a 16 GB card that is the difference between a 4-8k context and a 32k one. Nothing opened the gate on the library path. install.sh sets it only inside _persist_rocm_wsl_dropin(), which returns early unless librocdxg.so is present, so it fires on ROCm-on-WSL and nowhere else; install.ps1 never sets it. A user who pip installs unsloth on bare-metal Linux or Windows AMD, or runs a notebook, got the O(N^2) path. Set it at the top of unsloth/__init__.py, before anything can import torch. Any pre-existing value wins, including "0", which is the opt-out for someone who hits an AOTriton bug and wants the math fallback back. Set unconditionally because knowing the build means importing torch, and by then the value has already been read; non-ROCm torch never looks at a TORCH_ROCM_* variable. Complements unslothai#8323, which opens the same gate inside the Studio backend process. The two are separate copies on purpose: this one must stay importable with nothing but stdlib, and that one is vendored into a backend that never imports unsloth. * Set the AOTriton gate from the Windows installer, and correct why it works The variable was only ever exported by _persist_rocm_wsl_dropin, which is gated on librocdxg.so -- so WSL Strix Halo got it and every other ROCm host, Windows included, did not. install.ps1 now persists it to User scope on the confirmed ROCm branch, ahead of any process the user later starts, so a plain `import torch` script that never reaches unsloth is covered too. A pre-existing value wins, including "0", matching enable_rocm_aotriton_attention. The docstring claimed torch reads the variable once while loading its C++ extension, making the __init__ call an ordering race it had to win. It does not: torch reads it when it selects an SDPA backend. Setting it after `import torch` enables the kernels just as well, measured on gfx1200 with torch 2.11.0+rocm7.13.0, while unset and "0" both fail with "No available kernel". That claim was load-bearing for where this belongs, and it was wrong, so the measurements are recorded in the docstring. The __init__ call stays first regardless: the read point is a torch implementation detail, not a guarantee. Also drops the reference to unslothai#8323 opening the same gate in the Studio backend. That PR is still open, so no such gate exists. * Open the AOTriton gate for native Linux ROCm, not just the WSL drop-in _persist_rocm_wsl_dropin exports the variable, but it is gated on librocdxg.so, so only WSL Strix Halo ever reached it -- a native Linux ROCm install got nothing and fell to MATH SDPA exactly as Windows did. Persist it from the confirmed pip-ROCm-family branch instead, next to where install.ps1 now does. Skips when the WSL drop-in already wrote the variable, and when the user holds an opinion, including "0". Best-effort /etc/profile.d write mirroring the WSL helper: root writes directly, non-root sudo-tees, and neither path can abort the installer. * Persist the AOTriton gate for pinned ROCm indexes too, not just the auto-reroute A gfx*/rocm* pin via UNSLOTH_TORCH_INDEX_URL or UNSLOTH_TORCH_INDEX_FAMILY sets $TorchIndexPinned, which skips the auto-reroute block outright; $ROCmIndexUrl is resolved in the pinned branch below it instead. The persistence sat inside the auto-reroute, so those installs still got ROCm torch with the gate shut and fell back to MATH. Moved to the join point where both routes have resolved $ROCmIndexUrl. install.sh already hooks the final resolved index leaf, so the shell side was never affected. Regression tests pin both placements. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Set the AOTriton process variable before the User-scope write * Skip the host-wide AOTriton drop-in when install.sh runs with --no-torch * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Shorten AOTriton comments * Remove the installer-created AOTriton gate on uninstall * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Compact AOTriton lifecycle tests * Keep the PATH backup when writing the AOTriton ownership marker * Keep the AOTriton ownership marker when its value cannot be cleared * Point the AOTriton opt-out at 0 instead of unsetting the variable * Write the AOTriton drop-in with an explicit 0644 mode * Narrow ROCm AOTriton enablement to Unsloth processes * Gate ROCm AOTriton to validated gfx1151 builds * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Replace the AOTriton allowlist with a plain setdefault * State the AOTriton opt-out scope in the Studio comment too * Scope the AOTriton comments and widen the persistence guard * Keep AOTriton enablement process-local * Tighten the comments this change adds for PR unslothai#8821 * Bump the WSL helper pin to the copy without the host-wide export for PR unslothai#8821 --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: oobabooga <[email protected]> Co-authored-by: danielhanchen <[email protected]>
…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.
Fixes #8819.
On some AMD cards PyTorch ships fast attention kernels (AOTriton) but leaves them switched off until an environment variable says otherwise. Nothing on the
pip install unslothpath set it, so a plain script or notebook finetuned on the slow fallback kernel, whose memory grows with the square of the context, and training pays that twice because the backward pass needs the scores again. Finetuning OOMs at a fraction of the context the card holds.This PR sets the variable for anything that imports Unsloth, and for the Studio backend process. It also stops the WSL installers writing it into
/etc/profile.d, where it changed every PyTorch process on the machine.Cards it changes: RX 9060 XT / 9060 (gfx1200), RX 7800 XT / 7700 XT (gfx1101), the RX 7600 family (gfx1102), Radeon 780M/760M (gfx1103) and the RDNA 3.5 laptop chips (gfx1150/1152/1153).
Cards it leaves alone: RX 9070 XT / 9070 / R9700 (gfx1201), the RX 7900 series (gfx1100), Strix Halo (gfx1151, since AOTriton 0.12), MI200/MI300, and anything NVIDIA or Apple. The fast kernels are already on there.
Where the variable gets set
import unslothin a script, notebook or the CLIunsloth/__init__.pyrun.py(which importsmain) or directly withuvicorn main:appstudio/backend/main.py. Spawned inference, training and diffusion workers inherit itrun.py, before any import/etc/profile.dexportEvery write is
setdefault, so whichever runs first wins and the rest do nothing. A value you already have wins, and"0"is the opt-out for anyone who hits an AOTriton bug.When torch reads it
Not at
import torch. PyTorch reads it into a function-local static the first time it probes ROCm attention support (sdp_utils.cpp, same from 2.8 through 2.11 and main), soimport torchfollowed byimport unslothis still in time. That is the orderstudio/backend/core/training/trainer.pyuses. An earlier revision skipped the write when torch was already imported, which excluded exactly those callers. The correction came from the #8922 thread (yzxcj797's independent fix for the same line); #8922 is closed in favour of this one.Why there is no card list
PyTorch only reads the variable after AOTriton has confirmed it has a kernel for this GPU and that the GPU is on AOTriton's "experimental" list. That list is compiled into the AOTriton binary inside the torch wheel (
v3src/util.cc): gfx1150 to 1153, 1101 to 1103, 1200 and 1250 at 0.11.2b; 0.12 dropped gfx1151; the older v2 tree lists a different set again. An earlier revision of this PR restricted the write to Linux, one torch version and gfx1151, and got it exactly backwards: on where a v3 wheel makes it inert, off on gfx1200, the card #8225 was measured on. PyTorch does the filtering; the variable just says yes where PyTorch asks.It never forces a backend. head_dim, dtype and mask constraints still decide, and models that don't resolve to SDPA (the gemma3 family prefers flex_attention; gpt_oss and deepseek_v4 are SDPA-excluded) are unaffected either way. Non-ROCm PyTorch never reads it.
This is a product decision: Unsloth opts its own processes into kernels AMD labels experimental. The measured alternative on the affected cards is the slow kernel.
Tests
18 in
tests/python/test_rocm_aotriton_gate.py, no GPU needed. The library and Studio statements run through the same cases: the variable turns on when unset, an already-imported torch doesn't skip the write,"0"and"1"survive under both import orders, the statement is a bareos.environ.setdefaultwith two literals so it can't import torch or grow a card list, it sits above each file's own torch import and above Studio's route and hardware imports, no installer or uninstaller persists it, and a fresh interpreter reports1afterimport unslotheither way round and0when preset. Four mutations (re-adding the guard, turning the line into a helper call, an installer persisting it, moving the Studio line below the route imports) each fail their named test.Test matrix
CI can't show this one. The org's hosted runners have no AMD GPU, and the AMD runner we do have is a Strix Halo (gfx1151), where this variable does nothing. So this table is the test report, not the green checks.
test_startup_defers_torch.py,test_rocm_support.pyandtest_collection_hygiene.py: 530 passed, 16 skipped. A real import ofmain.pyreports1unset and0preset, with torch absent fromsys.modules4451f6aon that branchaotriton_report.py, 2026-09-03: 8 of 8 forced cases pass with the variable at"0"and at"1", peak VRAM identical (1.13 GB at 16k)Proven: the placement and the opt-out, on hosted CI and a Linux box; and on the R9700, that a card off AOTriton's list ignores the variable. Not proven: nobody has run this branch on a card it changes, and nobody has run it on Linux with an AMD card.
Related
unsloth/__init__.pyline, filed independently, and where the read-timing correction was worked out. Closed in favour of this PRThe ROCm-on-WSL helper pin
install.shpins the ROCm-on-WSL helper by SHA, and a non-checkout install (the normalcurl ... | shpath) downloads the helper at that SHA rather than the copy in this branch. The pin used to named3367edd, whose helper still carriesexport TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1at line 265, so fresh WSL installs kept writing the host-wide opt-in this PR removes.The pin now names
b1d829182f8c490a326cf7690f156d2de06381f2, the commit on this branch that ships the helper without the export. That commit is reachable through this PR's refs andraw.githubusercontent.com/unslothai/unsloth/<sha>/...serves it (checked: HTTP 200, zeroAOTRITONmatches). Apart from that one deleted line, the helper at the new pin is byte-for-byte the copy on main.If a pin on a main-branch commit is preferred, bump
_ROCM_WSL_HELPER_REFto the merge commit after landing; the helper contract check (UNSLOTH_ROCM_WSL_HELPER_CONTRACT=2) is satisfied either way.Scope note: the pin only affects the host-wide export cleanup, not the fix itself. The gate is set in-process by
os.environ.setdefaultat import, measured working on real gfx1151 hardware on both Linux and Windows. The stale pin leaves that one install path where it already was rather than making it worse.