Skip to content

fix(amd): turn on PyTorch's fast ROCm attention kernels when Unsloth Studio/Desktop launches, so a 16 GB card stops asking for 66 GiB - #8323

Closed
LeoBorcherding wants to merge 16 commits into
unslothai:mainfrom
LeoBorcherding:fix/rocm-aotriton-attention
Closed

LeoBorcherding wants to merge 16 commits into
unslothai:mainfrom
LeoBorcherding:fix/rocm-aotriton-attention

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #8225.

On some AMD cards PyTorch ships fast attention kernels (AOTriton) but leaves them switched off until an environment variable says otherwise. Nothing in Studio set it, so attention ran on the slow fallback kernel, whose memory grows with the square of the token count. That is how a 3.4 GB video model on a 16 GB card ends up asking for 66 GiB. This PR sets the variable when Studio launches. Same output to within fp16 rounding, up to 67x less memory at attention.

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). On these, video stops asking for tens of GB at attention, high-res image generation needs less VRAM, chat on safetensors models takes long prompts about 22x faster, and training fits longer sequences.

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. GGUF models go through llama.cpp, not PyTorch, so nothing changes for them either.

How it works

The variable is TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. PyTorch only reads it after it has already confirmed AOTriton has a kernel for this GPU and that the GPU is on AOTriton's "experimental" list (sdp_utils.cpp). It reads it once, the first time attention runs, and keeps the answer for the life of the process. run.py sets it before torch is imported, so it is always in time, and main.py makes the same call for a backend started directly with uvicorn main:app.

That experimental list is compiled into the AOTriton binary inside the torch wheel (v3src/util.cc) and changes between releases (0.12 dropped gfx1151, for one), so this PR keeps no card list of its own. PyTorch does the filtering; the variable just says yes where PyTorch asks. It is set with setdefault, so a value you already have wins, and "0" is the opt-out if you ever hit an AOTriton bug. It does not pick a backend either: select_attention_backend still returns None on auto, speed_mode=off is still bit-for-bit, and #8233's "no fused kernel" warning correctly stops firing once the kernels are available.

#8821 sets the same variable for import unsloth, and in studio/backend/main.py, which run.py imports on every launch and uvicorn main:app runs directly, so it reaches Studio too. This PR's write in run.py is just the earliest one. #8821 also removes the host-wide export the WSL installers used to write. Every write is setdefault, so whichever runs first wins.

Measured

RX 9060 XT (gfx1200), Windows 11, torch 2.11.0+rocm7.13.0, at 4451f6a. Nothing above the variable has changed in the merges since.

shape math (slow) flash mem_efficient
chat, N=9408 D=64 387.2 ms, 12.14 GiB 17.3 ms, 0.18 GiB 24.6 ms, 0.20 GiB
video, N=33000 D=128 64.91 GiB (the failing allocation) 388.2 ms, 0.60 GiB 311.9 ms, 0.72 GiB

flash and mem_efficient agree with math to 1.221e-04, which is fp16 rounding. 66.54 GiB is exactly what math needs for about 33k tokens at D=128, so the allocation in the issue is the attention score matrix, not weights or the VAE.

Seven tests in studio/backend/tests/test_rocm_attention.py: the variable turns on when unset, any preset value including "0" survives, calling it twice is harmless, and the run.py and main.py ordering is pinned so nobody can move either call below a torch import later.

Test matrix

CI can't show this one. The org's hosted runners have no AMD GPU, the AMD runner we do have is a Strix Halo (gfx1151) which is not affected by this pr.

hardware changed by this PR what ran still needed
RX 9060 XT (gfx1200), Windows 11, torch 2.11.0+rocm7.13.0 yes the benchmarks above, at 4451f6a: math only with the variable off; flash and mem_efficient on, matching math to fp16 rounding a full video generation. Attention now fits, but weights, activations and VAE decode haven't been run on this card
gfx1200, Linux yes nothing should be run. Torch reads the variable in the same code on both OSes, so no reason to expect a difference, but 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. Same mechanism as gfx1200, different kernel builds
RDNA 3.5 laptop chips (gfx1150/1152/1153) yes nothing nice to have
Radeon AI PRO R9700 (gfx1201), Windows 11, ROCm 7.1 no aotriton_report.py, 2026-09-03: 8 of 8 forced cases pass with the variable at "0" and at "1", same peak VRAM 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 in the #8821 thread: 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, same reasoning the R9700 row confirmed
NVIDIA, Apple, CPU no, variable never read the 7 tests on hosted CI nothing

Solid: the gfx1200 numbers, and the off-list prediction holding on the R9700. Biggest gap: no end-to-end generation, and no Linux run on any card the PR changes.

…ing for 66 GiB

unslothai#8233 made the math-only fallback visible and drew the wrong conclusion from it. The
card is not missing a fused kernel: torch has one and hides it behind
TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. With the gate closed every sub-quadratic
backend declines, SDPA falls through to MATH, and peak VRAM grows with the SQUARE of
the token count -- unslothai#8225, a 3.4 GB Q4_K_M asking a 16 GB card for one 66.54 GiB
allocation.

Measured on an RX 9060 XT (gfx1200, torch 2.11.0+rocm7.13.0), B=1 H=16 N=9408 D=64:

    math            387.2 ms   peak 12.14 GiB
    flash            17.3 ms   peak  0.18 GiB   max|d| vs math = 1.221e-04
    mem_efficient    24.6 ms   peak  0.20 GiB   max|d| vs math = 1.221e-04

67x the memory and 22x the time for a result that agrees to 1.221e-04, which is 2**-13,
fp16 epsilon. The gate is not buying accuracy, it is only costing the kernel.

Opened in run.py before any import that can pull torch, because torch reads the var
once while loading its C++ extension and a later set is dead code. A pre-existing value
always wins, including "0", which is the opt-out for anyone who hits an AOTriton bug.

Set unconditionally rather than only on ROCm: knowing the build means importing torch,
and by then the read has happened. Non-ROCm torch never looks at a TORCH_ROCM_* var.

Not routed through select_attention_backend. This does not choose a backend, it changes
which backends exist, so auto still returns None and the speed_mode=off bit-identical
guarantee is untouched. unslothai#8233's warning is unchanged and now fires only where the card
really is math-only.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@wasimysaid

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4451f6a943

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

@LeoBorcherding LeoBorcherding changed the title fix(studio): unlock ROCm AOTriton attention so a 16 GB card stops asking for 66 GiB fix(amd): unlock ROCm AOTriton attention so a 16 GB card stops asking for 66 GiB Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed studio/backend/run.py never opened TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL before torch loads, so a Studio launch outside install.sh stays on the quadratic math path, and setting it early with the "0" opt-out preserved looks right. Could you take a look at the three Core jobs and the pip scan-packages hf-stack check, which are green on main but red here?

studio/ still ships on the 3.9 floor, where `env: dict | None = None` is
evaluated at def time and raises. tests/test_python39_compatibility.py
ratchets on the count, and this file took it from 35 to 36, which is what
turned the three Core jobs and Repo tests (CPU) red.

Before: 1 failed, 'studio\backend\utils\rocm_attention.py' named as the
sole addition. After: 8 passed in test_python39_compatibility.py, and the
6 tests in test_rocm_attention.py still pass.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Merged main (f766d41). Net diff is unchanged: the same three files, 108 lines.

The six red checks at 0c67b12 were all red on main's own pushes in the same hour (909d797 at 23:19 UTC on Aug 27 through a37165 at 04:38 on Aug 28: Repo tests (CPU), Backend CI Python 3.13, all three Core legs, and workflow-trigger lint). Main went green on trigger-lint and Backend CI at da25d06 (04:57). Run logs for that head have expired, so the comparison is by job name at matching times rather than by log line.

The Core failures at the Aug 14 head (5ec3221) were this PR's, not main's: tests/test_python39_compatibility.py ratchets the number of studio files that evaluate a PEP 604 union at def time, and rocm_attention.py had pushed it from 35 to 36. 0c67b12 deferred the annotations. Reproduced locally at 5ec3221 (1 failed, 7 passed); the same test passes at this head (8 passed).

pip scan-packages :: hf-stack scans the pip archives of the transformers / peft / accelerate stack, which this diff does not touch. It failed the same way on main's own push at aa3f3c2 on Aug 16. The workflow has since gained a pull_request paths filter that none of these three files match, so it no longer runs on this PR.

Run locally on the merged head, and on upstream/main (ec77cf6) as the control, Windows 11, Python 3.12:

step merged head upstream/main
studio/backend/tests/test_rocm_attention.py 6 passed file not on main
tests/test_python39_compatibility.py 8 passed not run
lint_backend_python_floor.py (vermin, one invocation) minimum 3.10, OK minimum 3.10, OK
lint_workflow_triggers.py OK, 42 files OK, 42 files
workflow guard suites + tests/security 65 failed, 1261 passed 65 failed, 1261 passed

The 65 are the same suites on both trees (release_desktop integrity and notarization, which need a Linux or mac host), so they are the box, not the change. The Backend CI Repo tests step and the Core legs need a full unsloth_zoo install and were not run here.

One hardware row added, and the body narrowed to match. On the Radeon AI PRO R9700 (gfx1201, Windows 11, ROCm 7.1, the same torch 2.11.0+rocm7.13.0 build the gfx1200 rows used), aotriton_report.py with the variable at "0" and at "1": 8 of 8 forced flash and mem-efficient cases pass either way, peak VRAM identical. gfx1201 is not on AOTriton's isArchExperimentallySupported list at 0.11.2b, 0.12b or main (v3src/util.cc); gfx1200 is. So the fix is real on the 9060 XT and inert on the 9070 series and R9700, and the body now says gfx1200 rather than gfx120x. The body also drops its claim that torch reads the variable at extension load: the torch source latches it at the first SDPA capability check, which the run.py placement satisfies either way.

@codex review

@LeoBorcherding LeoBorcherding changed the title fix(amd): unlock ROCm AOTriton attention so a 16 GB card stops asking for 66 GiB fix(amd): Studio opens the ROCm AOTriton attention gate, so a 16 GB card stops asking for 66 GiB Sep 4, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-09T08:33:56.127899Z 6b24785 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f766d4121f

ℹ️ 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 studio/backend/run.py Resolved
Comment thread studio/backend/utils/rocm_attention.py Resolved
Comment thread studio/backend/utils/rocm_attention.py Resolved
…torch latches it

uvicorn main:app never imports run.py, so main.py now makes the same stdlib-only call above its route and hardware imports, with a test pinning the order. The docstrings and the run.py comment no longer claim torch reads the variable at extension load: it is a function-local static latched at the first SDPA capability check. The 1.221e-04 agreement is one fp16 ulp at the output magnitude, not fp16 epsilon.
The stub-order guard treats every utils import before the stub installers as one that can reach torch. utils.rocm_attention imports only os and seeds an env var torch reads, the same shape as utils.cpu_threads, so it joins the allowlist next to it.
@LeoBorcherding LeoBorcherding changed the title fix(amd): Studio opens the ROCm AOTriton attention gate, so a 16 GB card stops asking for 66 GiB fix(amd): turn on PyTorch's fast ROCm attention kernels when Studio launches, so a 16 GB card stops asking for 66 GiB Sep 8, 2026
@LeoBorcherding LeoBorcherding changed the title fix(amd): turn on PyTorch's fast ROCm attention kernels when Studio launches, so a 16 GB card stops asking for 66 GiB fix(amd): turn on PyTorch's fast ROCm attention kernels when Unsloth Studio/Desktop launches, so a 16 GB card stops asking for 66 GiB Sep 9, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 6b24785: the three findings at f766d41, the stub-order allowlist, and a merge of main.

uvicorn main:app never imports run.py, so the launcher's call left a direct start on the math fallback. main.py now calls the same helper above the route and hardware imports, with a test pinning that order. #8821 puts a bare setdefault in the same file; a dry-run merge of the two branches is clean and both writes are idempotent.

The comment in run.py and the helper's docstring said torch reads the variable while loading its C++ extension. It latches it at its first SDPA capability check, so the deadline is the first attention call; both now say that, and the ordering test's docstring says why the launcher still sets it before any torch import (no reasoning about who probes first).

1.221e-04 was called fp16 epsilon. It is one fp16 ulp for outputs in [0.125, 0.25), where these peak; epsilon at 1.0 is 2**-10. The docstring now says that, and records the R9700 re-measurement: flash and mem-efficient differ from MATH by exactly one ulp at the output magnitude, and both sit as far from an fp64 reference as MATH does.

test_xformers_stub_diffusion_parity.py allowlists utils.rocm_attention alongside utils.cpu_threads as an import that legitimately precedes the Windows ROCm stubs.

Local, Windows 11, Python 3.12, on the merged head: test_rocm_attention.py 7 passed, test_python39_compatibility.py 8 passed, test_xformers_stub_diffusion_parity.py 22 passed 5 failed. The same 5 fail identically on a tree without this PR (the fp8/mxfp8 preflight and DiT refusal cases plus test_dense_quant_still_allowed_without_the_stub), so they are this box's missing deps, not the change.

@codex review

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

Copy link
Copy Markdown

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

Reviewed commit: 6b24785121

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 76131c0: the helper's docstrings cut to the why. The benchmark table and issue narrative live in the body. Comment-only, test_rocm_attention.py 7 passed and the py39 ratchet 8 passed on the new head.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed main only exports TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL from install.sh and the WSL script, so a Studio launch from elsewhere still lands on the quadratic math path, and the run.py plus main.py placement covers both entry points. This does opt our processes into kernels AMD still labels experimental on those arches, so could you confirm the three Core legs, which are green on main but red here, before I review?

@danielhanchen

Copy link
Copy Markdown
Member

Closing this in favour of #8821, which sets the same variable with the same setdefault semantics but covers more of the surface. Recording the comparison so the decision is reviewable.

What each PR reaches

entry point #8323 #8821
import unsloth (Core library, notebooks, pip installs) no yes, unsloth/__init__.py
Studio backend via run.py yes, run.py hook yes, via main.py: run.py imports main at line 2439 and imports no torch before it
Studio backend via uvicorn main:app yes, main.py hook yes, main.py line 21, 276 lines before the first import that can reach torch
Spawned workers (training, diffusion, inference, export) inherit inherit; every mp.get_context("spawn") and every Popen in studio/backend copies os.environ rather than replacing it
Removes the installers' host-wide /etc/profile.d export no yes

Your own description here says #8821 reaches Studio through main.py; the only thing this branch adds on top is an earlier write in run.py, and torch reads the variable lazily at the first SDPA capability check, not at import, so the earlier write changes nothing torch can observe.

Evidence that #8821 does the job

Measured on the self-hosted gfx1151 Strix Halo runner, Linux/ROCm, torch 2.11.0+rocm7.13.0: at the base both flash and mem-efficient SDPA raise No available kernel and the default dispatch is bit-identical to MATH; at #8821's head both run, agree with MATH to 9.8e-4, and default peak memory drops about 12x. On the Windows 11 gfx1151 boxes the value lands from both entry points, an explicit "0" survives, and all three spawn shapes Studio uses read the parent's value. On an NVIDIA B200 and in a CPU-only venv the change is inert.

Nothing here was wrong. The helper and its tests are a clean shape, and if you would like the utils/rocm_attention.py helper plus its ordering tests carried into #8821 as a follow-up, say so and I will port them. Thanks for the measurements on the RX 9060 XT; they are what made the case for opening the gate at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Studio video: Wan2.2-TI2V-5B requests 71 GB on a 16 GB card: SDPA falls back to the math kernel on ROCm gfx1200

3 participants