Skip to content

fix(amd): turn on PyTorch's fast ROCm attention kernels on import unsloth, and drop the installers' host-wide export - #8821

Merged
danielhanchen merged 36 commits into
unslothai:mainfrom
LeoBorcherding:fix/amd-aotriton-library-gate
Sep 15, 2026
Merged

danielhanchen merged 36 commits into
unslothai:mainfrom
LeoBorcherding:fix/amd-aotriton-library-gate

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

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 unsloth path 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

how Unsloth was started who sets it
import unsloth in a script, notebook or the CLI this PR, unsloth/__init__.py
the Studio backend, launched normally through run.py (which imports main) or directly with uvicorn main:app this PR, studio/backend/main.py. Spawned inference, training and diffusion workers inherit it
the Studio launcher itself, run.py, before any import #8323, an earlier write of the same value
the WSL installers' /etc/profile.d export removed here

Every 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), so import torch followed by import unsloth is still in time. That is the order studio/backend/core/training/trainer.py uses. 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 bare os.environ.setdefault with 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 reports 1 after import unsloth either way round and 0 when 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.

hardware changed by this PR what ran still needed
x86_64 Linux, torch 2.11.0+cu130, no AMD no, variable never read the 18 tests plus test_startup_defers_torch.py, test_rocm_support.py and test_collection_hygiene.py: 530 passed, 16 skipped. A real import of main.py reports 1 unset and 0 preset, with torch absent from sys.modules nothing
RX 9060 XT (gfx1200) yes nothing on this branch. The kernel numbers (67x memory, 22x time, fp16-rounding agreement) are from #8225 and #8323, same variable, measured at 4451f6a on that branch a training before/after on this branch. The card is between machines, and the R9700 can't stand in for it, see its row
gfx1200, Linux yes nothing should be run. Same torch code on both OSes, most reporters are on Linux
RX 7800 XT / 7700 XT / 7600 / 780M (gfx1101/1102/1103) yes nothing, no card here should be run. The 7800 XT is the most common reporter card
RDNA 3.5 laptop chips (gfx1150/1152/1153) yes nothing nice to have
Radeon AI PRO R9700 (gfx1201), Windows 11, ROCm 7.1, torch 2.11.0+rocm7.13.0 no aotriton_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) nothing. Confirms on a real card that an off-list chip ignores the variable
Strix Halo (gfx1151), Ubuntu 24.04 no, since AOTriton 0.12 forced-call run earlier in this thread, 08-21: same result off, on and unset nothing. This is the AMD CI runner, which is why CI can't see the fix
RX 7900 series (gfx1100), MI200/MI300 no nothing nothing. Off the list at every AOTriton version

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

The ROCm-on-WSL helper pin

install.sh pins the ROCm-on-WSL helper by SHA, and a non-checkout install (the normal curl ... | sh path) downloads the helper at that SHA rather than the copy in this branch. The pin used to name d3367edd, whose helper still carries export TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 at 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 and raw.githubusercontent.com/unslothai/unsloth/<sha>/... serves it (checked: HTTP 200, zero AOTRITON matches). 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_REF to 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.setdefault at 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.

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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Windows answered: the wheel ships AOTriton, and the variable is the only thing holding it shut

RX 9060 XT (gfx1200), Windows, torch 2.11.0+rocm7.13.0, hip 7.13.99004,
rocm-sdk-libraries-gfx120X-all 7.13.0.

The wheel carries the kernels:

torch/lib/aotriton_v2.dll
torch/lib/aotriton_v2.lib
torch/lib/aotriton.images/amd-gfx120x/

Torch's own flags claim the backends are on:

flash_sdp_enabled      True
mem_eff_sdp_enabled    True

They are not. With the variable unset, every forced-backend call fails:

dtype backend direction causal unset set to 1
fp16 flash fwd no No available kernel pass
fp16 flash bwd no No available kernel pass
fp16 mem-eff fwd no No available kernel pass
fp16 mem-eff bwd no No available kernel pass
fp16 flash fwd yes No available kernel pass
fp16 flash bwd yes No available kernel pass
fp16 mem-eff fwd yes No available kernel pass
fp16 mem-eff bwd yes No available kernel pass
bf16 all eight of the above No available kernel pass

16 of 16 fail unset, 16 of 16 pass set. B=2 H=8 S=512 D=64.

Torch names the variable itself in the warning it emits on the way past:

Mem Efficient attention on Current AMD GPU is still experimental.
Enable it with TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1
  sdp_utils.cpp:384
Flash attention has been runtime disabled.
  sdp_utils_cpp.h:540

Accuracy against the math backend at that shape, fp16 causal: max abs diff 0.00195. Larger than
the 1.221e-04 measured at B=1 H=16 N=9408 D=64 in #8225, and expected to be: shorter sequences
and a different reduction order move fp16 rounding around. Both are noise, neither is a kernel
disagreement.

Two things this pins down:

  • Windows is in scope. Earlier I could not tell whether repo.amd.com/rocm/windows shipped the
    library at all.
  • flash_sdp_enabled() and mem_efficient_sdp_enabled() are not a usable probe on ROCm. They
    report the user-facing toggle, not whether a kernel exists. Anything checking AMD attention
    support has to attempt a call.

gfx1201 shares the amd-gfx120x image family so it should behave the same, but that is inference
from the directory name, not a measurement. Untested.

On "experimental"

The gating is AMD's, not a formality, and RDNA4 backward is the least-exercised path in it. Worth
stating plainly given this PR opens the gate by default.

The comparison is not "experimental kernel versus safe kernel". It is "experimental kernel versus
MATH", and MATH puts a 32-head fp16 model at 4.3 GB of attention scores at 8k tokens and 17.2 GB at
16k, which is an OOM on a 16 GB card before any weights are loaded. Against that, a 0.00195 fp16
delta on a path that passes forward and backward in both dtypes is the better default.

Anyone who hits trouble sets the variable to 0 and gets the old behaviour back; the helper never
overwrites an existing value. If AMD's own confidence in RDNA4 backward shifts, the default is one
line to flip.

…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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

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 does

TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL
  unset   flash: No available kernel    mem_efficient: No available kernel
  "0"     flash: No available kernel    mem_efficient: No available kernel
  "1"     flash: OK                     mem_efficient: OK

Unset or 0, torch declines every sub-quadratic backend and silently falls through to MATH, which materialises the full B × H × N × N score matrix. No warning. The kernels agree with MATH to max|Δ| = 1.221e-04 (2**-13, fp16 epsilon), so the gate is not buying accuracy.

Kernel benchmark

Single process, backends forced per call with torch.nn.attention.sdpa_kernel, so nothing but the kernel varies. bf16, causal, forward + backward, Llama-3.1-8B attention shape (32 heads, head_dim 128).

B N MATH flash speedup MATH peak flash peak memory
1 1024 18.6 ms 5.1 ms 3.6× 0.75 GiB 0.24 GiB 3.1×
1 2048 66.4 ms 11.5 ms 5.8× 2.35 GiB 0.34 GiB 7.0×
1 4096 486.2 ms 41.1 ms 11.8× 8.55 GiB 0.52 GiB 16.3×
1 8192 OOM 168.0 ms — — 0.90 GiB —
2 4096 1193.2 ms 116.3 ms 10.3× 16.96 GiB 0.90 GiB 18.8×
2 8192 OOM 329.1 ms — — 1.65 GiB —

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 result

Full finetunes through Unsloth Studio did not show this. Including them so nobody rediscovers it.

model seq cap tokens branch wall vs pair
Llama-3.1-8B 2048 61,806 aotriton 230.63 s −9.8%
Llama-3.1-8B 2048 61,806 main 253.29 s
Qwen3.5-4B 2048 64,058 aotriton 174.78 s −0.9%
Qwen3.5-4B 2048 64,058 main 176.27 s
Llama-3.1-8B 2048 44,537 main 227.11 s 1.2%
Llama-3.1-8B 2048 44,537 main 229.83 s

Each pair processed a byte-identical token count. Don't read the first two rows as signal:

  • The last pair is the control: main against main, same config, loss identical to 16 digits, still 1.2% apart. 9.8% on the 8B versus 0.9% on the 4B for the same change is an order of magnitude of disagreement, with the smaller inside the noise band.
  • Sequence length: packing: False meant real sequences averaged 186–267 tokens against a 2048 cap, where attention is a rounding error in the step.
  • Branch is not gate state: install.ps1 persists the variable, so main-branch processes inherit it too. I didn't log the value per run, so treat that column as branch only.

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.

Caveats

Synthetic 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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Correction on the Strix Halo ask: gfx1151 needs a TheRock nightly (https://rocm.nightlies.amd.com/v2/gfx1151/) for this to show anything. Stable ROCm wheels don't ship gfx1151 AOTriton kernels, so the flag is a no-op there and falls back to MATH regardless. For reference, our wheel here only carries aotriton.images/amd-gfx120x.

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 ="0" opt-out this PR preserves.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@unslothai unslothai deleted a comment from oobabooga Aug 19, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Fixed the P2 and merged main. Head is 46f5e2b.

The finding was right. The persistence lived inside the auto-reroute, which only runs when nothing is pinned, so a UNSLOTH_TORCH_INDEX_URL or UNSLOTH_TORCH_INDEX_FAMILY pointed at a gfx*/rocm* index sailed past it. Those installs still get ROCm torch from the pinned branch further down, just with the gate shut, which is precisely the case this PR is about.

It now sits at the join point where both routes have settled $ROCmIndexUrl, guarded on that variable so it only fires for ROCm. Nothing else moved: a pre-existing value still wins including "0", the User-scope write is still advisory, the process copy is still set.

install.sh is untouched and was never affected. It hangs off _is_pip_rocm_family_leaf "$_torch_index_leaf", which reads the final resolved index after every reroute and pin, so the pinned case was already covered there.

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 $ROCmIndexUrl guard, and the shell call must stay attached to the leaf classification instead of drifting into one reroute arm. Confirmed the first fails against the old install.ps1.

The main merge also brings in #9252, which is what was failing Security audit / pip scan-packages :: hf-stack here.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@codex review

@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: 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".

Comment thread install.sh Outdated
Comment on lines +4179 to +4181
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member

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.

@danielhanchen

Copy link
Copy Markdown
Member

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.

@danielhanchen

Copy link
Copy Markdown
Member

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 after

Before: 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 /etc/profile.d, which only applies to login shells, so it missed anyone launching from a desktop session, a service, or an IDE.

After: import unsloth sets TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 via os.environ.setdefault at the top of unsloth/__init__.py, before torch is imported, and the host-wide installer export is removed.

It is a real issue, measured

On the runner, torch's own stderr at the base says it verbatim:

[W914 07:56:30.727556101 sdp_utils.cpp:323] Warning: Flash Efficient attention on Current AMD GPU is still
experimental. Enable it with TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1.
[W914 07:56:30.727585130 sdp_utils.cpp:383] Warning: Mem Efficient attention on Current AMD GPU is still
experimental. Enable it with TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1.

gfx1151, hip 7.13.99004, torch 2.11.0+rocm7.13.0, identical GPU and build at both states:

observation base head merge
gate_after_import none 1 1
can_use_flash false true true
can_use_efficient false true true
flash_ran false (RuntimeError: No available kernel) true true
efficient_ran false (same) true true
flash_max_abs_diff_vs_math n/a 0.000977 0.000977
efficient_max_abs_diff_vs_math n/a 0.000977 0.000977
math_peak_gib 0.6524 0.6524 0.6524
default_peak_gib 0.6563 0.0548 0.0548
default_matches_math_exactly true false false

So the base is not merely ineligible on paper. Both explicit-backend runs raise No available kernel, and the default dispatch is bit-identical to the MATH reference, which is what a silent fallback looks like. With the gate open both backends really run, default peak memory drops from 0.6563 to 0.0548 GiB (about 12x), and the unlocked kernels agree with the fp16 math reference to 9.77e-4 against a 2e-2 tolerance, and stay finite.

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-AMD

No, and I checked this two independent ways rather than trusting one.

By source. The env read sits inside #if USE_ROCM in aten/src/ATen/native/transformers/cuda/sdp_utils.cpp, as a function-local static const bool, reached only when aotriton::isArchExperimentallySupported(stream) is true. A CUDA build never compiles that read. I checked this holds in both torch v2.8.0 and v2.11.0, so it is not a version-specific accident.

By measurement on a B200. SDPA capability and output are byte-identical across the variable being unset, "0" and "1". Then a real training loop rather than a capability query: a seeded 4-block transformer, 12 steps of SDPA forward, backward and AdamW, across 2 trees x 2 import modes x 3 repetitions:

distinct loss arrays across ALL configs      : 1
distinct grad-norm arrays across ALL configs : 1

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 torch.version.cuda is None and hip is None), import unsloth behaves identically to main. The gate is set and is inert, because a CPU build has no such read.

Across the OS and accelerator matrix. Studio's hardware.py across 20 [Linux, Windows, WSL, macOS] x [NVIDIA, AMD, XPU, CPU, MLX] personas in fresh interpreters: GPU summary unchanged in every cell, and no non-AMD persona probed AMD tooling. The 49-cell installer matrix: identical to main in all 49 cells.

setdefault is the right call and I want to flag it as deliberate: a user who has explicitly exported TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=0 to avoid these kernels keeps that setting. The opt-out survives.

What the hardware could not answer

  • Only gfx1151 was measured. Whether AOTriton flags any other architecture experimental, and whether its kernels are numerically sound there, is not established by this run. The mechanism is general; the numerical result is not.
  • Windows is not covered by this job. Whether the variable set in the parent reaches Studio's spawned workers matters more on Windows, which spawns rather than forks. I have a Windows run in flight and will follow up here with what it says.
  • NVIDIA, multi-GPU, Intel XPU and Apple MLX were covered by simulation and by the B200 control above, not by this AMD job.

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.

@danielhanchen

Copy link
Copy Markdown
Member

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.

setdefault behaves, and the opt-out survives

Each cell is a fresh interpreter, reading the value after the import:

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 what studio/backend/core/training/training.py uses (_CTX = mp.get_context("spawn"))
  • subprocess with no env=, the sd-cpp and llama-server shape
  • subprocess with env=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.py imports 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.

@unslothai unslothai deleted a comment from oobabooga Sep 14, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 2cbccd7e36

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

On the four red checks here: none of them are this PR. Recording the evidence so nobody has to re-derive it.

Repo tests (CPU, rest) fails on one assertion:

FAILED tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform
default encoding ... ['tests/version_compat/test_bitsandbytes_pinned_symbols.py:288: read_text()']
1 failed, 7060 passed, 204 skipped

I ran the same test on a clean main checkout at 289e0df and it fails there too, naming the identical file and line:

FAILED tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
['tests/version_compat/test_bitsandbytes_pinned_symbols.py:288: read_text()']
1 failed, 15 passed

This PR touches five files and that is not one of them:

install.sh
scripts/install_rocm_wsl_strixhalo.sh
studio/backend/main.py
tests/python/test_rocm_aotriton_gate.py
unsloth/__init__.py

The three Core jobs fail inside unsloth_zoo @ main - full pytest (CPU) on allocator configuration (PYTORCH_ALLOC_CONF / PYTORCH_CUDA_ALLOC_CONF all None). The same workflow is failure on main itself (run 34820611889), and nothing here reaches unsloth_zoo.

So all four are pre-existing. The encoding one is a genuine small bug worth its own PR, since a read_text() without encoding = "utf-8" does break on Windows the moment that file gains a non-ASCII byte, which is exactly what the test says. I have not fixed it here because it is unrelated to this change and would muddy the diff.

@danielhanchen

Copy link
Copy Markdown
Member

Merged current main (a6cf596) into this branch, and took over driving it.

The branches had drifted far enough that CI was testing a stale combination rather than the change. The clearest case: tests/sh/test_setup_staged_root.sh failed 4 assertions in CI while passing locally on every tree here, because main had changed the sidecar-removal code and grown the test from 34 assertions to 36, while the branch still carried the 34-assertion version. Old test, new code.

tree assertions result
main a6cf596 36 pass
this branch's old base 289e0df 34 pass
the CI merge commit 34 4 failed

Merged cleanly with no conflicts. Verified before pushing:

  • 65 of 65 shell installer suites pass, zero failures
  • the PR's own suites pass

Two other red checks that were also main's rather than this branch's, for the record:

  • Repo tests (CPU, studio) failed on test_uv_cache_discipline and test_studio_smokes_do_not_trigger_on_the_training_library. main gained the test requiring uv-cache-restore before studio-update-smoke.yml gained the action; the workflow side landed in b58ea42. It clears on a re-run against fixed main, which I confirmed.
  • The three Core jobs fail inside unsloth_zoo @ main on allocator configuration, and that workflow is red on main itself.

Still genuinely outstanding and not from this branch: tests/test_source_read_encoding.py flags tests/version_compat/test_bitsandbytes_pinned_symbols.py:288 for a read_text() with no encoding = "utf-8". It reproduces on a clean main checkout, same file and line. Worth its own small PR since it breaks on Windows the moment that file gains a non-ASCII byte.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

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 after

Before: 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 /etc/profile.d, which only login shells read.

After: import unsloth and Studio's main.py set TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 through setdefault before torch is imported, and the installers no longer write the export.

Evidence on real gfx1151, Linux, torch 2.11.0+rocm7.13.0

observation base head
gate after import unsloth unset 1
can_use_flash / can_use_efficient false / false true / true
flash ran no, No available kernel yes
efficient ran no yes
flash and efficient max abs diff vs MATH n/a 2.4e-4
default dispatch bit-identical to MATH true false
default peak memory 0.0781 GiB 0.0371 GiB

Torch's own stderr at the base says it: Flash Efficient attention on Current AMD GPU is still experimental. Enable it with TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1. The criteria return VOID when the base does not show the defect; this came back CONFIRMED.

Windows 11 gfx1151, PowerShell 5.1: from an unset start both entry points read 1 at the head and stay unset at the base; an explicit 0 survives at both; and all three spawn shapes Studio uses (multiprocessing spawn context, subprocess without env, subprocess with a copied env) read the parent's value, with a scrubbed control child reading unset in every state. CONFIRMED.

Hosted runners: ubuntu-latest, macos-15 and windows-latest all green on the branch's own tests (test_rocm_aotriton_gate.py, the Studio import tests).

Does it change anything on NVIDIA, CPU or Mac

No. PyTorch reads the variable only inside #if USE_ROCM in sdp_utils.cpp, into a function-local static const bool, after aotriton::isArchExperimentallySupported says yes; the string does not occur in any of the twelve shared libraries of a CUDA build. Measured on a B200 with torch 2.12.1+cu130: SDPA capability flags and outputs are byte-identical across main, this branch and the combined AMD tree, with the variable unset, 0 and 1. A 12-step LoRA run on Qwen2.5-0.5B differs across trees by less than the same-configuration repeat noise. In a CPU-only venv import unsloth behaves identically to main. The installer matrix is byte-identical to main in all 183 cells.

Second pass: the ROCm-on-WSL helper pin

install.sh fetches the ROCm-on-WSL helper at a pinned SHA on a non-checkout install. The pin named d3367edd, whose helper still carries the host-wide export TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1, so a fresh curl | sh WSL install kept writing the line this branch deletes. The pin now names b1d829182, the commit on this branch with the export removed; raw.githubusercontent.com/unslothai/unsloth/<sha>/... serves it (HTTP 200, no AOTRITON match), and apart from that one line the helper there is byte-for-byte the copy on main. The PR description is updated to match. Bump it again to the merge commit after landing if a main-only pin is preferred; the helper contract check passes either way.

Old installs and updating

A WSL host that already has the old /etc/profile.d/unsloth-rocm-wsl.sh keeps exporting the same value the library now sets by default, so nothing changes for it; the installer never rewrites an existing drop-in and only scripts/uninstall.sh removes it. A user who wants the kernels off exports 0 before launching, which wins at both levels.

Not tested here

Only 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 53b5e1b102

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 15, 2026
@danielhanchen
danielhanchen merged commit 164d154 into unslothai:main Sep 15, 2026
89 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
u064241 pushed a commit to u064241/unsloth that referenced this pull request Nov 19, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

4 participants