Skip to content

Studio ROCm: use the measured fastest GEMM solution table for diffusion denoisers on gfx1151 - #17299

Merged
danielhanchen merged 7 commits into
mainfrom
studio-rocm-tunableop-denoiser
Nov 9, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-rocm-tunableop-denoiser

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

On AMD Strix Halo (gfx1151), hipBLASLt's default solution for diffusion transformer GEMM shapes runs 17-38% slower than the fastest solution the same library ships. In a GEMM benchmark across Qwen-Image-2.1, FLUX.3 klein, LTX-2.5 and MiniMax-H3 shapes, the default reaches 21-24 TFLOPS and the best pick 32-35, with the same error against fp32.

torch's TunableOp can find that pick, but it costs 17-215 s per GEMM shape however small the budget: trying every candidate is the cost, not the timing iterations. That makes online tuning a poor default, so this PR ships the measured result instead:

  • New module core/inference/diffusion_rocm_tunableop.py, called from the ROCm branch of apply_speed_optims.
    • By default Studio loads a GEMM solution table measured on gfx1151 (core/inference/rocm_gemm_tables/*.csv, torch's own TunableOp result format).
    • TunableOp runs lookup-only: tuning stays off. GEMM shapes not in the table keep the default pick.
  • The table loads only when its library validators match this process exactly (torch, HIP, hipBLASLt, rocBLAS, GPU arch). Solution indices only mean something for the build that measured them.
    • Otherwise TunableOp stays off and nothing changes.
    • The shipped table matches the torch 2.11.0+rocm7.13.0 wheels Studio installs for gfx1151 from AMD's per-arch index.
  • The table covers the 1024x1024 denoiser GEMMs of Qwen-Image-2.1 and FLUX.3 klein: 25 shapes, generated on the runner by the opt-in tune mode below.
  • UNSLOTH_DIFFUSION_ROCM_TUNABLEOP=tune (opt-in) also tunes new shapes inside the denoiser and persists them under the compile cache.
    • It tunes only on steady calls: a call shaped like the previous one. A render's first call and a prefix-cache prefill never tune.
  • UNSLOTH_DIFFUSION_ROCM_TUNABLEOP=0 keeps the default pick everywhere. A user who sets any PYTORCH_TUNABLEOP_* variable keeps full control.
  • Scope:
    • ROCm torch only, measured archs only (gfx1151).
    • The off speed tier removes it.
    • NVIDIA, MPS and CPU never reach this code.
  • Packaging: pyproject.toml ships the table as package data.

Results (gfx1151, torch 2.11.0+rocm7.13.0, exclusive GPU, one job, main vs this PR; the first two rows ran twice per side)

1024x1024, 4 prompts per arm. s/step is the steady-state device time per denoiser step; s/image is the steady render.

model / mode main s/step (A/A) this PR s/step (A/A) s/step change steady s/image main / PR first render s main / PR peak device memory main / PR
Qwen-Image-2.1 bf16, 25 steps 3.541 / 3.536 2.839 / 2.820 -20.0% 90.2 / 73.2 94.5 / 94.3 44.2 / 44.2 GiB
FLUX.3 klein defaults, 16 steps 1.547 / 1.551 1.376 / 1.374 -11.2% 25.9 / 23.1 31.6 / 31.6 23.0 / 23.0 GiB
Qwen-Image-2.1 defaults (int8 W8A8) 3.218 3.214 0% 82.1 / 82.0 n/a (see below) 31.6 / 31.6 GiB
  • Spread: the A/A spread is 0.3% or less on every row, so both gains are far outside the noise.
  • First render and memory are unchanged. Nothing is tuned at runtime, and peak device memory, host RSS and the first render match main.
    • The int8 row's first render (114.3 s on main vs 92.4 s) is not comparable: it reflects compile-cache warmth from earlier arms, not this change.
    • For comparison, the tune mode that generated the table spent about 230-260 s extra on its first compiled render (Qwen-Image-2.1 340.9 s vs 83.7 s, FLUX.3 klein 263.1 s vs 31.3 s).
  • The table engaged on every PR arm ("25 shapes" in the log). With UNSLOTH_DIFFUSION_ROCM_TUNABLEOP=0, FLUX.3 klein ran 1.548 s/step and its output was bit-identical to main.
  • Quality: the A/A pairs on main are bit-identical.
    • Against main, LPIPS is 0-0.006 for Qwen-Image-2.1 bf16 and 0-0.026 for FLUX.3 klein (0 on the eager first image). A different GEMM solution changes the accumulation order only, and the images keep the same composition.
    • The int8 default has a few remaining bf16 GEMMs in the table, so its images shift by LPIPS 0.003-0.019 with no speed change.
  • Under the Auto speed tier, the first two images of a session run eager and see no change. Their GEMMs (bias epilogue) are not in the table. The gain starts with the compiled third image and every image after it.

Tests

studio/backend/tests/test_diffusion_rocm_tunableop.py (17 tests, fake torch.cuda.tunable, CPU):

  • default mode reads a matching table and never tunes;
  • a table from another build, or with a missing validator, is ignored and TunableOp stays off;
  • tune mode tunes only on steady denoiser calls and persists atomically, including across nested calls and exceptions;
  • the decline paths (kill switch, user-owned PYTORCH_TUNABLEOP_*, unmeasured arch, non-ROCm);
  • off removes it, and the speed layer never installs it on NVIDIA;
  • the shipped table is a valid torch result file with full validators;
  • the shipped table is listed as package data.

@danielhanchen danielhanchen self-assigned this Nov 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T18:52:44.605179Z 7171091 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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-09T18:36:15.863614Z
We couldn’t complete this review. Comment @codex review to try again.
99608f2 PR opened
ℹ️ 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: 99608f2d68

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

…red arch; drop it when a later load is on another arch

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

Round 2: @codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e96a9b262f

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 3 (comment-only pass since the last review): @codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7171091f28

ℹ️ 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
danielhanchen merged commit a784ee5 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the studio-rocm-tunableop-denoiser branch November 9, 2026 19:50
danielhanchen added a commit that referenced this pull request Nov 9, 2026
…ng, not a raw read (#17325)

## Summary

`(Python 3.13, a-f)` is red on `main` and on every PR based on it since
#17299 merged:

```
studio/backend/tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly
E   AssertionError: use core.inference.rocm_bf16.is_rocm_torch(torch): AMD SDK / Radeon wheels leave torch.version.hip unset. Raw reads: {'diffusion_rocm_tunableop.py': [128]}
```

#17299's `results_file()` folds `torch.version.hip` into the TunableOp
results filename. That is a label, not a gate: the gate in the same
module already goes through `is_rocm_torch(torch)`. The guard exempts
exactly this kind of read when it sits inside an f-string ("the read
labels a cache key with the build string; it gates nothing"). Here the
read sat in a plain tuple, so the guard flagged it.

The read now goes into an f-string, `hip = f"{getattr(torch.version,
'hip', None)}"`, before it is joined into the tag. The filename is
byte-for-byte the same, so existing tuned results stay valid. `getattr`
also avoids an `AttributeError` on a torch build whose `torch.version`
has no `hip` attribute.

## Changes

- `studio/backend/core/inference/diffusion_rocm_tunableop.py`:
`results_file()` reads the HIP build string inside an f-string.

## Testing

- `pytest tests/test_diffusion_rocm_tunableop.py
tests/test_diffusion_rocm_tag_detect.py`: 27 passed. On `main`,
`test_diffusion_rocm_tag_detect.py` fails (1 failed, 7 passed).
- The tag string is the same as before for both a ROCm build
(`gfx1151_2.10.0-rocm7.1_7.1.25424`) and a build without HIP
(`..._None`).
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 10, 2026
… unloads (unslothai#17340)

## Summary

Unloading a diffusion pipeline on ROCm (gfx1151) left
`torch.cuda.tunable` enabled for the rest of the process. Later GEMMs
outside diffusion kept consulting the diffusion solution table. This
change restores the TunableOp state once the last pipeline that enabled
it unloads.

## Root cause

unslothai#17299 added `diffusion_rocm_tunableop.py`. In the default lookup mode,
`_activate` calls `torch.cuda.tunable.enable(True)` process-wide and
`install_for_pipe` returns without registering anything that can be
undone later. Image and video unload call `restore_backend_flags`, but
`snapshot_backend_flags` does not capture TunableOp. The only
`uninstall` callers are a `speed=off` load and an ineligible-arch load,
and neither runs on unload. So after a normal load and unload, TunableOp
stays enabled and active.

## Fix

- `diffusion_rocm_tunableop`: `_activate` records `is_enabled()` before
enabling TunableOp. Each pipe that activates it gets an owner tag, set
on the pipe so the second-expert and named-DiT views share it.
`release(pipe)` drops that claim. The last release calls `uninstall`,
which now restores the recorded state rather than forcing `False`.
- `diffusion_speed.release_rocm_tunableop(pipe)`: a best-effort helper.
It does nothing if the module was never imported, which covers non-ROCm
hosts.
- The helper is called after `restore_backend_flags` in image
`_unload_locked`, in the image pre-commit failure rollback and in video
`_teardown_state_locked`.
- Image and video pipelines can be loaded at the same time. Unloading
one keeps TunableOp on while the other still holds a claim.
- If the user sets `PYTORCH_TUNABLEOP_*` themselves, Studio never
activates TunableOp or claims it, so their setting is left alone.

## Flip test

`studio/backend/tests/test_diffusion_rocm_tunableop_teardown.py` uses a
fake `torch.cuda.tunable` and runs on CPU only:
- `test_unload_restores_tunableop_only_after_the_last_pipeline`
- `test_unload_restores_a_previously_enabled_state`
- `test_user_owned_tunableop_is_left_alone`
- `test_image_and_video_teardown_release_tunableop` (AST check that both
teardown methods call the release)

On origin/main (ec6d160), all 4 fail. A probe on main also shows
`install_for_pipe` followed by `restore_backend_flags` (the current
unload path) leaves `enabled=True active=True`. With the fix, all 4
pass.

## Tests run

- `-o addopts= -m "not server and not native_mxc"` over every test file
that mentions tunableop, backend_flags, `_unload_locked` or
`_teardown_state_locked` (28 files): 2813 passed, 79 skipped, 1 failed.
The failure is
`test_diffusion_zimage_fused.py::test_model_unload_restores_the_process_global_patches`.
It also fails on origin/main, so it predates this change.
- `tests/test_refactor_guard.py`: 12 passed.
- The pre-push gate (stray files, AGPL header, ruff): pass.

## Not proven

- Not run on real ROCm hardware. The real `torch.cuda.tunable` state
change is only exercised through a fake.
- The video pre-commit rollback (`_rollback_precommit_globals`) does not
have access to the pipe, so it does not release. A failed video load
that already activated TunableOp still leaves it enabled until a later
`speed=off` load or the next unload.
- Other TunableOp settings (filename, max tuning duration and
iterations) are not restored. They have no effect while TunableOp is
disabled.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…mpile without a graph break (unslothai#18122)

Both changes remove a Python lock from code that a whole-model
`torch.compile` traces. On main each one makes a fullgraph compile fail
with `Unsupported context manager`, and a default compile drop the call
to eager.

1. **Windows ROCm wide-head SDPA guard (unslothai#17976).**
`studio/backend/core/_rocm_windows_sdpa.py` pins the math backend under
a `threading.Lock`. Studio installs its guard before unsloth's, and
unsloth's compile-safe guard (`unsloth/import_fixes.py`,
`_sdpa_math_only` under `allow_in_graph`) sees the shared marker and
keeps Studio's wrapper, so a compiled Gemma 4 global layer (head dim
512) on Windows ROCm reaches the lock. The pin now runs in an
`allow_in_graph` helper keyed by a string token, as in
`unsloth.import_fixes`.
2. **ROCm TunableOp tune hooks (unslothai#17299).** With
`UNSLOTH_DIFFUSION_ROCM_TUNABLEOP=tune`, forward hooks on the denoiser
root hold an `RLock` and flip the process-wide tuning switch. The max
tier compiles an SDXL U-Net whole (`Module.compile`, fullgraph), which
traces those hooks and fails at the first forward, with no eager
fallback. The hooks now return early under
`torch.compiler.is_compiling()`, so compiled calls only read the tuning
table and tuning stays with eager calls.

### GPU results on gfx1151 (Radeon 8060S), base (main 62d66cb) vs
this branch, same job and runner per fix

| fix | runner | check | base | this branch |
|---|---|---|---|---|
| wide-head guard | Windows 11, torch 2.11.0+rocm7.14.0 | bf16 head-512
causal attention, `fullgraph=True` with eager / aot_eager / inductor |
all three fail: `Unsupported context manager ... lock` | all three
compile, no break reasons |
| wide-head guard | same | compiled vs guarded eager output | n/a | rel
L2 0.0 / 0.0 / 2.6e-05; eager vs fp32 reference 0.00158 in both arms; no
fused attention kernel ran; backend flags restored |
| tune hooks | Linux, torch 2.11.0+rocm7.13.0 | small bf16 GEMM module,
hooks installed in tune mode, `fullgraph=True` with eager / aot_eager /
inductor | all three fail: `Unsupported context manager ... RLock` | all
three compile, rel L2 0.0 vs eager |
| tune hooks | same | `fullgraph=False` | 3 unsupported, 23 of 26 frames
compiled (module call dropped to eager) | 0 unsupported, 3 of 3 frames |
| tune hooks | same | eager tuning still runs | tuning switch on then
off, results file written | tuning switch on then off, TunableOp results
25 to 27, results file written (27 rows) |

### Tests

- `studio/backend/tests/test_rocm_windows_wide_head_sdpa.py`:
`test_guarded_wide_head_compiles_fullgraph[aot_eager|inductor]` compiles
the real Studio wrapper with `fullgraph=True`; fails on main. The
inductor case skips on Windows when MSVC (`cl`) is not on PATH, since
Inductor's CPU backend needs it.
- `studio/backend/tests/test_diffusion_rocm_tunableop.py`: new compile
test; fails on main.
- CPU (torch 2.14.1): base 2 failed / 9 passed and 1 failed / 19 passed;
this branch 31 passed across both files.
- gfx1151 runners: Windows suite base 9 passed, this branch 10 passed
and the inductor case failed with `Compiler: cl is not found` (the skip
above was added after that run); Linux TunableOp suite base 19 passed,
this branch 20 passed.

### Not covered

- The wide-head guard ran on Windows only and the TunableOp hooks on
Linux only; discrete RDNA / CDNA cards and multi-GPU hosts were not
tested.
- The full SDXL max-tier U-Net compile with tune mode was not run end to
end; the check used a small module with the same hooks.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…Cm 7.14 build (#18838)

Studio ships one hipBLASLt GEMM table for gfx1151
(`rocm_gemm_tables/gfx1151_torch2.11.0_hip713_...csv`, #17299).
TunableOp only reads a table whose validators match the running build
exactly, and that table was measured on the Linux build (torch
2.11.0+rocm7.13.0, hipBLASLt 100300-02d4f738fc). The Windows installer
pins torch 2.11.0+rocm7.14.0 from AMD's multi-arch index (HIP 714,
hipBLASLt 100401-cd957402), so on Windows the table never matched and
every denoiser GEMM ran on hipBLASLt's default pick.

## Change

Adds `gfx1151_torch2.11.0_hip714_qwenimage21_flux3klein_1024.csv`: the
same Qwen-Image-2.1 and FLUX.3 klein 1024x1024 shapes as the Linux
table, tuned on a Windows gfx1151 runner with Studio's own Windows
environment. There is no code change. The loader already picks a table
only on an exact validator match, so Linux and every other build keep
reading only their own table.

Per GEMM on the Windows runner (default pick vs the table's pick, median
of 30 timed calls):

| shape (m x n x k) | default ms | table ms | speedup |
|---|---|---|---|
| 24576 x 4096 x 4096 (FLUX.3 klein) | 35.88 | 28.20 | 1.27x |
| 4096 x 4096 x 12288 (FLUX.3 klein) | 23.10 | 16.91 | 1.37x |
| 12288 x 4096 x 4096 (FLUX.3 klein) | 18.46 | 14.21 | 1.30x |
| 4096 x 4096 x 4096 (FLUX.3 klein) | 6.55 | 5.11 | 1.28x |
| 3072 x 4096 x 9216 (Qwen-Image-2.1) | 9.58 | 7.92 | 1.21x |
| 18432 x 4096 x 3072 (Qwen-Image-2.1) | 17.64 | 17.12 | 1.03x |
| 3072 x 4096 x 3072 (Qwen-Image-2.1) | 3.05 | 2.87 | 1.06x |

The small shapes (modulation, text stream) gain 1.35-2.56x. One shape
(128 x 4096 x 3072) was slower with the tuned pick (0.73x), so it is
left out and keeps the default. The largest difference between the tuned
and default outputs is 3.8e-3 to 7.5e-3 of the output range, which is
bf16 summation order.

End to end on Windows (same job, main vs this branch): measured on one
Windows gfx1151 runner, main first then this branch in the same job,
1024x1024, 3 renders each (run 44978757641):

| model | main s/step | this branch s/step | speedup | main s/image |
this branch s/image | LPIPS branch vs main | peak allocated GiB main /
branch |
|---|---|---|---|---|---|---|---|
| FLUX.3 klein bf16 | 1.667-1.675 | 1.554-1.561 | 1.07x | 27.9-28.0 |
26.1-26.5 | 0.0025 | 24.01 / 24.08 |
| Qwen-Image-2.1 bf16 | 3.128-3.222 | 2.631-2.666 | 1.19x | 81.3-83.1 |
69.7-70.5 | 0.0011-0.0021 | 39.36 / 39.43 |

Main's first Qwen-Image render (5.57 s/step, 146.8 s, a cold start) is
left out of its range. For scale, two main renders of Qwen-Image differ
from each other by LPIPS 0.0015. Device memory is 48.0 GiB on main and
48.1 GiB here.

## Tests


`tests/test_diffusion_rocm_tunableop.py::test_windows_and_linux_gfx1151_builds_each_get_their_own_table`:
a host with the Windows validators selects only the new table, and a
host with the Linux validators selects only the Linux one. Fails on main
(no Windows table), passes here. The existing shipped-table tests (full
validators, four-column rows, package data glob) cover the new file too.
`tests/test_diffusion_rocm_tunableop.py`: 21 passed.

## Not proven here

- The table covers 1024x1024 Qwen-Image-2.1 and FLUX.3 klein shapes
only, plus the text-stream shapes for an 80-token prompt. Other
resolutions, other prompt lengths and the other families (Z-Image, Wan)
keep the default pick, as on Linux.
- Measured on one Windows gfx1151 box. Other RDNA cards on Windows have
a different arch and never read this table.
- A future Windows torch or ROCm bump changes the validators and the
table silently stops applying. It needs re-tuning with each pin change,
as the Linux table does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant