Skip to content

Studio on Windows AMD: diffusion LoRA training without a C++ compiler, and exact VAE attention at head dim 512 - #17953

Merged
danielhanchen merged 9 commits into
mainfrom
studio-amd-diffusion-lora
Nov 16, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
studio-amd-diffusion-lora

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Two Studio bugs on Windows with AMD ROCm (gfx1151, AMD's torch 2.11.0+rocm7.14.0), found while checking diffusion LoRA training on AMD:

  1. bf16 / auto LoRA training died on the first step. The DiT trainer compiles the transformer for bf16, and a compiled training graph needs a host C++ compiler on Windows; a stock install has none, so the step raised Compiler: cl is not found past dynamo's error suppression. auto picks bf16 on ROCm, so the default failed (FLUX.3 Klein Base and the FLUX.2 klein control alike). Training now runs eager with a warning when torch's own compiler lookup finds none.
  2. VAE attention at head dim 512 was computed wrong. AMD's Windows wheel accepts head dim 512 (the single-head VAE mid-block of SD, SDXL and FLUX.1/2/3) in its flash and efficient SDPA kernels and returns garbage: relative error 19 to 38 against math in fp32 and bf16, NaN through the default dispatch. Head dims 128 and 256 are correct. FLUX.3 Klein renders at 512 px came out as noise, and training latents were corrupted (Windows losses 1.2 to 1.4x the Linux ones on the same data and seed). On Windows ROCm a head wider than 256 now counts as having no fused kernel, so Studio's existing exact chunked-math path runs; the trainer's VAE goes through the same routing, and the VAE decode is never compiled there (a compiled decode would skip the routing).

Linux ROCm, NVIDIA (Windows and Linux), Mac and CPU are unchanged: every new branch is Windows-ROCm only, except the trainer's VAE routing, which follows inference's existing ROCm-only install.

Runs (AMD CI, gfx1151, base = main vs head = main + this change in the same job)

run base head
Windows: FLUX.3 Klein Base LoRA training, auto dies, Compiler: cl is not found 30 / 30 steps eager with the warning, 0.461 samples/s, 12.15 GB peak
Windows: Qwen-Image-2.1 LoRA training, auto dies trains eager, 0.263 samples/s, 15.56 GB
Windows: FLUX.3 Klein render 512 px, LPIPS vs the same render forced to math attention 0.875 (noise) 0.003
Windows: FLUX.3 Klein render 1024 px, same comparison mean abs diff 4.96 (faint band) 0.005
Windows: Qwen-Image-2.1 render (VAE head 768) correct bit-identical to base
Linux: FLUX.3 Klein and Qwen-Image-2.1 renders bit-identical to base
Windows: the new test files 4 of 11 fail 11 of 11 pass

On Linux gfx1151, Qwen-Image-2.1, FLUX.3 Klein Base and MiniMax-H3-Image LoRA training, reload into Studio, render with the adapter and export all worked before this change and still do.

Final head on Windows gfx1151 (base = main, head = this PR)

main this PR
FLUX.3 Klein Base training latents, largest relative difference vs a math-attention reference (4 images) 0.74 0.0 (bit-identical)
latent mean / std (reference 0.064 / 0.984) 0.134 / 1.185 0.064 / 0.984
FLUX.3 Klein 512 px render, LPIPS vs math twin 0.875 0.0029
bf16 training loss over 30 steps, Windows vs Linux on the same data and seed mean 1.036 vs 0.757 0.7572 vs 0.7567, per-step difference at most 0.23%

The trainer's VAE runs in fp32, which the half-precision math route skipped, so fp32 (and half with UNSLOTH_VAE_ATTN_HALF_MATH=0) wide heads now run explicit fp32 math; the preview VAE a warm conditioning cache loads is routed too; and Windows ROCm latent cache keys are salted so latents encoded before this fix are not reused.

Tests

  • New tests/test_diffusion_train_compile_toolchain.py: Windows ROCm without a compiler trains eager with the warning; with a compiler, on Linux, and on Windows CUDA the compile decision is unchanged.
  • New tests/test_diffusion_windows_rocm_wide_head.py: head 512 on Windows ROCm reports no fused kernel and runs the exact path; 128 / 256 and every other platform are unchanged; the decode compile gate is Windows-ROCm only.
  • Both fail with the fix reverted and pass here (14 tests locally, 11 on the Windows runner).

Not covered

  • MiniMax-H3-Image training on Windows: the runner has 68 GB of RAM, and the Linux run used about 92 GB of host memory.
  • The third commit (never compile the VAE decode on Windows ROCm) is unit-tested; the hardware runs used the first two.
  • Speed of the exact path on Windows was not isolated (base always ran first in the job, so warm-up dominates); it is the path Linux ROCm already takes at these head sizes.

…as no C++ compiler

A stock Windows install has no cl, so the bf16 (and auto) DiT trainer's torch.compile raised
'Compiler: cl is not found' at the first step and the run died (gfx1151 Windows 11, FLUX.2 klein
and FLUX.3 Klein). Ask torch's own compiler lookup before compiling and train eager with a warning.
…utes head dim 512

AMD's Windows torch 2.11.0+rocm7.14.0 on gfx1151 takes head dim 512 (the VAE's single-head attention)
in flash and efficient SDPA and returns garbage (relative error 19-38 against math, NaN through the
default dispatch); 128 and 256 are correct. Every Windows AMD VAE encode and decode was wrong: noise
renders, and LoRA training on corrupted latents. Count a Windows ROCm head wider than 256 as having no
fused kernel so the chunked math path runs, and route the DiT trainer's VAE through the same patch.
…on ROCm only

A compiled VAE decode skips the eager routing that keeps the head-512 attention off the fused
kernels that miscompute it on Windows ROCm, so never compile it there. The missing-C++-compiler
compile gate was measured on Windows ROCm only; leave Windows CUDA's compile untouched.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 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-16T10:45:55.641855Z 44a2a79 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: ef2a52169f

ℹ️ 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 on lines +121 to +122
if _windows_rocm_untrusted_head(q, torch):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Force math SDPA when rejecting Windows ROCm fused kernels

On Windows ROCm with an fp32 VAE, returning False here does not prevent the broken fused kernels from running: ChunkedVaeAttentionMode only uses explicit math when _half_math_call(q) is true, which excludes fp32. Otherwise it calls the original SDPA directly or passes that same function to chunked_sdpa, leaving fused dispatch enabled in both cases. This affects the training path added here because _load_pipe_without_transformer and _flux3_load_conditioners explicitly convert the VAE to fp32, so head-512 training latents still go through the kernels this change identifies as incorrect. Force the math backend (including within chunks) for rejected Windows ROCm heads; the same protection is needed when UNSLOTH_VAE_ATTN_HALF_MATH=0.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed: a Windows ROCm head the fused kernels miscompute (wider than 256) never reaches the stock SDPA dispatch now. fp32 calls (every trainer VAE) and half calls with UNSLOTH_VAE_ATTN_HALF_MATH=0 run explicit fp32 math, chunked under the same score budget; half calls with the switch on keep the half-precision math route. Tests test_windows_rocm_fp32_wide_head_never_reaches_the_stock_kernel, test_a_rejected_fp32_head_runs_explicit_math_not_the_default_dispatch and test_a_rejected_half_head_honours_the_half_math_switch fail before and pass after. The preview VAE a warm conditioning cache loads is routed too, and Windows ROCm latent cache keys are salted so latents encoded before the fix are not reused.

The head guard sent fp32 calls (every trainer VAE, fp32 inference VAEs) back to the stock
SDPA dispatch, which on Windows ROCm still picks the fused kernels that miscompute head 512.
Compute the math in fp32 instead, chunked under the same score budget.
… too

A warm cache skips the encode but still loads the VAE for training previews, whose decode
runs the same head-512 attention; only the cold path's VAE was routed.
…ot half

The wide-head route took the half-precision math for every dtype, so UNSLOTH_VAE_ATTN_HALF_MATH=0
lost the fp32 upcast it promises. fp32 calls and half calls with the switch off now run math in
fp32 (what ROCm's math kernel upcasts to); half calls with the switch on keep the half math.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 515232c521

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 44a2a791c4

ℹ️ 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 added a commit that referenced this pull request Nov 16, 2026
…(rest red on main) (#17963)

## Summary

`(Python 3.13, rest)` is red on main (seen on the staging runs of #17953
and #17957, base `bf7f6e050d`):

```
studio/backend/tests/test_video_ltx25_te_hosted.py::test_a_rejected_hosted_file_refuses_the_dense_fallback_without_room
E   Expected regex: 'needs about 24 GB'
E   Actual message: '... quantizing the dense encoder at load needs about 23.9 GB of free memory (8.0 GB free).'
studio/backend/tests/test_video_ltx25_te_hosted.py::test_the_dense_fallback_room_check_prices_the_load_dtype[float32-30-True]
E   Expected regex: 'needs about 48 GB'
E   Actual message: '... needs about 47.8 GB of free memory (30.0 GB free).'
```

#17948 changed the LTX-2.5 dense text encoder refusal to print the need
to one decimal, so it can no longer read "needs about 24 GB ... (24 GB
free)" for a 24.3 GB need with 23.8 GB free. That is intended. It
updated the same assertion in
`test_video_hub_unreachable_cached_load.py` but not these two in
`test_video_ltx25_te_hosted.py`, which still pin the old whole-GB text.

## Change

Test only, `studio/backend/tests/test_video_ltx25_te_hosted.py`:

- The hosted-file refusal pins the full one-decimal text: `needs about
23.9 GB of free memory (8.0 GB free)`.
- The dtype pricing case derives the need from `LTX25_TE_BF16_GB` (a
float32 load needs twice the bf16 encoder) and pins both figures to one
decimal, so a change to the encoder size constant does not break it
again while a return to whole-GB rounding still does.

No product code changes; when a load is refused is unchanged.

## Testing

- `test_video_ltx25_te_hosted.py`: 18 passed. On main the two tests
above fail.
- Sabotage: printing the need with `:.0f` again (the pre-#17948
rounding) fails both tests.
@danielhanchen
danielhanchen merged commit 9850de8 into main Nov 16, 2026
@danielhanchen
danielhanchen deleted the studio-amd-diffusion-lora branch November 16, 2026 11:15
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…ncoding latents (#18560)

#17953 fixed wrong training latents on Windows ROCm: the VAE's
single-head attention (head dim 512) went through fused SDPA kernels
that return garbage at that width. The fix routed the VAE's attention
through the exact path inference uses
(`diffusion_vae_attn_chunked.install`), but only in the DiT trainer. The
SDXL LoRA trainer runs in its own training process, never installs the
wide-head guard, and encodes every training latent through `pipe.vae`,
so SDXL LoRA training on Windows ROCm still encoded its latents through
the broken kernels.

## Change

The SDXL trainer calls the same `install(vae)` right after the VAE moves
to its card, before any latent is encoded. `install` acts only on ROCm
torch (CUDA, MPS and CPU builds return without patching), so nothing
changes off ROCm. On ROCm Linux, the VAE takes the same routed path the
DiT trainers and inference already use.

## Tests


`test_the_sdxl_trainer_routes_its_vae_attention_before_encoding_latents`
runs a real 1-step SDXL LoRA training on the tiny SDXL pipeline with a
ROCm torch reported. It checks that the pipeline's AutoencoderKL is
patched and that every encoder forward runs after the patch. It fails on
main (nothing patched) and passes here.
`tests/test_diffusion_lora_trainer.py` and the SDXL cases in
`tests/test_diffusion_gc_budget_trainers.py`: 62 passed.

## On Windows gfx1151 (Strix Halo, torch 2.11.0+rocm7.14.0)

The SDXL trainer itself (1 step, tiny SDXL pipeline with the real SDXL
VAE swapped in, 256 px): the first training latents it encodes, against
a CPU fp32 encode of the same pixels.

| tree | VAE attention routed | relative L2 | max abs |
|---|---|---|---|
| main | no | 0.120 | 10.8 |
| this PR | yes (2 modules) | 7.8e-6 | 0.0011 |

On Linux gfx1151 (torch 2.11.0+rocm7.13.0), where the fused kernels are
correct at this width, main and this PR give the same latents (relative
L2 6.7e-6 against the CPU encode on both, the routed path on this PR).
danielhanchen added a commit that referenced this pull request Nov 20, 2026
… kept, nested-safe SDPA guard (#18582)

Three fixes to the Windows ROCm attention routing added in #17953 and
#17960, found in a recheck of the kernel PRs. Each is its own commit.

## 1. VAE decode compile is dropped only for wide-head VAEs

#17953 keeps the Windows ROCm VAE decode eager so a compiled decode
cannot skip the attention routing that keeps head dim 512 off the fused
SDPA kernels. But `_vae_decode_compile_allowed` returned False on the
platform alone, before looking at the VAE or the
`UNSLOTH_DIFFUSION_COMPILE_VAE` setting. A VAE with no attention head
wider than 256 (attention-free video VAEs, or a narrow AutoencoderKL)
lost decode compilation too, even when the env asked for it.

- `diffusion_vae_attn_chunked.py`: new `vae_has_untrusted_head(vae)`. It
walks the same attention modules the routing patches and reads each head
dim (`inner_dim // heads` on diffusers `Attention`). Any head wider than
256, any attention module whose head dim it cannot read (the single-head
blocks of Wan, Qwen-Image and HunyuanImage), and any VAE it cannot
inspect count as wide.
- `diffusion_speed.py`: on Windows ROCm `_vae_decode_compile_allowed`
returns False only when `vae_has_untrusted_head` is True. The check
still runs before the U-Net shortcut and the env override, so a
wide-head VAE never compiles past the routing there.

Studio's own AutoencoderKL and AutoencoderKLFlux2 VAEs have a
single-head mid-block at 512, so they stay eager on Windows ROCm exactly
as before.

## 2. fp64 stays fp64 in the wide-head math path

`fp32_math_sdpa` ran `.float()` on Q, K and V and cast only the result
back, so an fp64 call was silently reduced to fp32. With fp64 `[1, 1, 3,
512]` operands filled with `1e20`, stock SDPA returns finite output
while the routed path overflowed and returned NaN. It now upcasts only
fp16 and bf16; fp32 and fp64 run in their own precision. Half inputs
keep the existing fp32 upcast, so `UNSLOTH_VAE_ATTN_HALF_MATH=0` is
unchanged. Studio loads VAEs in fp16, bf16 or fp32, so this only matters
to code handing a double VAE to the routed attention.

## 3. The SDPA guard checks the device before the query shape

The Windows ROCm SDPA wrapper's `_wide_cuda_head` read `query.shape`
before checking the device. A strided NestedTensor raises
`NestedTensorImpl doesn't support sizes` on `.shape`, so a valid CPU
nested SDPA call failed inside the wrapper. It now returns False for any
non-CUDA query without touching the shape, judges a nested CUDA query by
`size(-1)`, and sends the call to the stock dispatch if even that
raises. Dense CUDA queries are judged as before.

## Tests

CPU only, Windows ROCm faked:

- `tests/test_diffusion_windows_rocm_wide_head.py`:
-
`test_windows_rocm_keeps_decode_compile_unless_the_vae_has_a_wide_head`,
with tiny real diffusers AutoencoderKL VAEs: the head-64 and
no-attention cases fail on main and pass here. The two head-512 cases
(with and without the env forcing compile) are still refused, passing on
both.
- `test_windows_rocm_fp64_wide_head_keeps_fp64_precision[1073741824|16]`
(unchunked and chunked): fail on main (NaN), pass here.
- The existing `test_vae_decode_compile_stays_eager_on_windows_rocm` (an
uninspectable `vae=object()` stays eager) passes on both.
- `tests/test_rocm_windows_wide_head_sdpa.py`:
`test_a_nested_cpu_query_reaches_the_stock_dispatch` and
`test_a_nested_cuda_query_is_judged_by_its_head[128-False|512-True]`
fail on main and pass here.

Base vs head over both files: 7 tests fixed, 31 unchanged, 0 failing on
this branch. Wider suite (`test_diffusion_vae_attn_chunked.py`,
`test_diffusion_speed.py`, `test_diffusion_vae_fused.py`,
`test_diffusion_vae_regional_compile.py`): no failures on main or here
apart from the new tests on main.

## Windows gfx1151 (AMD CI)

Real Windows ROCm (torch 2.11.0+rocm7.14.0, gfx1151), base = main, head
= this branch, two tiny AutoencoderKL VAEs (head dim 64 and 512) on the
real GPU:

| state | narrow VAE: U-Net / env forced | wide VAE: U-Net / env forced
| compiled narrow decode finite | rel L2 to eager |
|---|---|---|---|---|
| base | refused / refused | refused / refused | yes | 8.7e-7 |
| head | allowed / allowed | refused / refused | yes | 8.7e-7 |

CONFIRMED: main refuses decode compile for the narrow VAE, this branch
allows it, the compiled decode matches eager, and the head-512 VAE is
still refused.

## Not proven here

- The speed gain for an unaffected VAE was not measured.
- fp64 and nested CUDA tensors on a real Windows card were not run.
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