Skip to content

Studio: contiguous q/k/v for long-sequence diffusion LoRA training on gfx1151 - #18966

Merged
danielhanchen merged 4 commits into
mainfrom
studio-rocm-train-contiguous-qkv
Nov 23, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-rocm-train-contiguous-qkv

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

On gfx1151 (Strix Halo, Radeon 8060S), diffusers' native attention backend hands SDPA permuted [B, S, H, D] views of q, k and v. AOTriton's kernels are tuned for dense [B, H, S, D], and the strided call gets slower than copying once a sequence passes a few thousand tokens. Studio already copies k/v for inference on gfx1151 (install_rocm_contiguous_kv), but nothing in the training path installed it, so every DiT LoRA step paid the strided forward and backward.

This PR extends the same native-backend wrapper to training:

  • install_rocm_contiguous_qkv_training() (core/inference/diffusion_attention.py) registers the gfx1151 cards of a training process. While grad is on, attention calls whose q and k are both at least ROCM_CONTIGUOUS_QKV_TRAIN_MIN_TOKENS (2,560) long get contiguous q, k and v. Short sequences, short cross-attention (a 512-token text key), no-grad sample renders and every other GPU keep the current path.
  • _apply_perf_flags installs it for every diffusion trainer and _restore_perf_flags removes it, so in-process callers see no lasting change. The U-Net trainer does not go through the dispatcher, so nothing changes there.
  • The ROCm check goes through is_rocm_torch (tag-only AMD SDK wheels included) and the arch through _props_gfx_arch. Only gfx1151 is covered, since it is the only arch measured.
  • Kill switch: UNSLOTH_DIFFUSION_ROCM_TRAIN_CONTIGUOUS_QKV=0. A positive integer moves the token floor.
  • The inference k/v gate and its own switch (UNSLOTH_DIFFUSION_ROCM_CONTIGUOUS_KV) are unchanged. The wrapper is now built by one shared _contiguous_native so the two gates share a single registry entry.

Why q/k/v and why 2,560 tokens

Attention fwd+bwd on gfx1151, 24 heads x 128, bf16, torch 2.11.0+rocm7.13, interleaved rounds, median ms:

tokens strided (today) k/v copied q/k/v copied q/k/v vs today
1,024 6.00 6.32 6.51 0.92x
1,536 12.98 13.84 13.58 0.96x
2,048 23.35 25.23 23.63 0.99x
2,304 33.22 34.31 31.09 1.07x
2,560 42.66 43.55 38.41 1.11x
3,072 61.99 62.10 56.70 1.09x
4,096 131.78 129.70 106.04 1.24x
4,608 170.18 166.18 136.91 1.24x
8,192 630.71 585.50 458.01 1.38x

The k/v-only copy (the inference recipe) gains at most 1.08x in training and loses below 3,072 tokens, so training copies q as well. In a torch.compile(dynamic=True) projection block (linear, unflatten, attention, out projection, fwd+bwd) the q/k/v copy is 1.07x at 2,560, 1.17x at 4,096 and 1.18x at 4,608, 2% slower at 1,024 and 1.02x to 1.03x at 1,536 to 2,048. All variants were bitwise equal to the strided path, outputs and gradients, both eager and compiled.

End-to-end LoRA training on gfx1151

FLUX.2 klein base 4B, bf16 base, LoRA rank 16, 20 steps, compile auto (regional compile engaged in every arm), 8 public images. Each arm runs through run_diffusion_training_process in a fresh process. Arms are interleaved in three rotated rounds (base, head, kill switch) on one runner; the compile-off row is a separate job (base, head, base). Base is origin/main 2bdf891. s/step is the median from step 3.

cell tokens base s/step (3 runs, spread) head s/step kill switch s/step head speedup peak alloc base / head hook engaged
1024x1024 4,608 6.994 (0.41%) 6.163 (0.30%) 6.990 1.135x 20.28 / 20.82 GB yes
768x768 2,816 3.394 (0.22%) 3.204 (0.30%) 3.392 1.059x 15.54 / 15.87 GB yes
512x512 1,536 1.460 (0.33%) 1.455 (0.30%) 1.461 1.003x (inside noise) 12.18 / 12.18 GB no (below floor)
1024x1024, compile off 4,608 7.594 (2 runs, 0.32%) 6.951 not run 1.093x 23.11 / 23.78 GB yes, 1,569 copies
  • Compile: 0 graph breaks and 3 unique graphs in every arm, base and head alike. No new recompiles.
  • Engagement: 15 traced copies per head run at 1024 and 768 (5 traces, q, k and v each), 0 at 512 and 0 in every base and kill-switch run. With compile off the copy runs eagerly: 1,569 copies (523 attention calls, q, k and v each) in the head run, 0 in base.
  • Kill switch: at 1024 and 768 the three kill-switch runs produce the same adapter (identical tensor hash) and the same losses as the three base runs.
  • Numerics: base is deterministic at 1024 and 768 (identical adapters across runs), and so is head. Head matches base exactly for steps 1 and 2, then drifts at rounding level: max loss difference over 20 steps is 4.4e-4 (0.07%) at 1024 and 9.4e-4 (0.15%) at 768. With compile off, head and base produce the identical adapter (same tensor hash) and identical losses at every step, so the wrapper itself is exact; the drift comes from the compiled graph, where the copy changes the layouts inductor picks around the attention call. The compiled trainer is therefore not bit-identical to base. For scale, base at 512 is not run-to-run deterministic on this stack, and its own A/A loss difference is 1.3e-3 (0.20%).
  • Peak memory: +0.53 GB at 1024 and +0.33 GB at 768 for the contiguous copies (2.6% and 2.1%).

Tests

  • tests/test_diffusion_rocm_train_contiguous_qkv.py (new): other AMD arches, NVIDIA builds and no-GPU hosts keep the stock backend; a tag-only ROCm wheel installs on its gfx1151 card only; idempotent install and restore; kill switch values; the env token floor; threshold edges (floor, floor - 1, short cross-attention, no grad, wrong card); outputs and q/k/v gradients bitwise equal through the wrapper (positional and keyword calls); the inference k/v gate still copies only k/v; _apply_perf_flags / _restore_perf_flags install and remove it.
  • tests/test_diffusion_attention_rocm_contiguous_kv.py and tests/test_diffusion_rocm_tag_detect.py pass unchanged.
  • 37 passed locally (CPU) and 37 passed on the gfx1151 runner.

Not covered

  • gfx1151 on Linux only. Windows ROCm training and other AMD arches were not measured, so the gate leaves them alone.
  • Only FLUX.2 klein was trained end to end. Qwen-Image, Wan and LTX training reach the same dispatcher, so they get the same gate, but their step times were not measured.
  • Long video sequences (the 27k-token Wan case) were measured only in the attention bench, not in a full training run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T02:37:20.255965Z 6599220 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6599220aaf

ℹ️ 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 d93f772 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the studio-rocm-train-contiguous-qkv branch November 23, 2026 03:37
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…cess, INT8 attention and MPS guard changes (#19005)

## Summary

Follow-ups to #18965, #18968, #18979 and #18981 from a recheck of the
merged kernel and compile changes. There is one commit per PR. Each fix
is small and backwards compatible. The default bf16 / fp32 paths produce
the same outputs as before.

### #18965: Windows ROCm per-tap Conv3d
- Under CPU bf16 autocast, fp32 inputs came back as fp32 instead of the
autocast dtype. Autocast calls now stay on stock `Conv3d`; bf16, fp16
and fp32 calls outside autocast keep the per-tap path. fp16 stays on it
on purpose: on Windows gfx1151 the real LTX-2.3 fp16 decode is finite
there, and stock `Conv3d` was 2.4x slower (35.7 s vs 87.0 s) with a 7.1
GiB higher peak.
- `torch.compiler.is_compiling()` is now checked before the env switch.
Before this, flipping `UNSLOTH_VIDEO_VAE_ROCM_PERTAP` inside a compiled
region added an env guard and forced a recompile.

### #18968: Lanczos reference preprocess
- The int32 guard bounds a single image. The identity-resize and
vertical-first normalize launches run flat over the whole NHWC batch, so
a `[24, 8192, 8192, 3]` batch wrapped the int32 index. `_normalize_rgb`
now widens the program offset to int64 before the multiply. The TTIR now
shows an `i64` multiply and `i64` pointer offsets.
- If the load-time probe hit a transient OOM, GPU reference
preprocessing stayed off on that device until restart. Now an OOM takes
the CPU path for that call only, and the next request probes again.
Other probe failures are still cached.

### #18981: INT8 attention kernel switches
- Flipping the residual-fold, sink-order or native-P switch built a new
launch plan. The plan's `decision` key left the switches out, so the new
kernel reused the old kernel's accuracy and timing verdict without
racing. The decision key now carries the same switch tuple as the plan
key.

### #18979: MPS large-attention guard
- The prefill check parsed `torch.__version__` with `re.match`. On a
cold regex cache, Dynamo traced into the pattern compiler and failed
`fullgraph=True`. The pattern is now compiled at import.

## Tests

Each new test fails on `origin/main` and passes here:
- `test_video_vae_rocm_pertap.py`:
`test_autocast_keeps_stock_output_dtype`,
`test_compiled_kill_switch_flip_does_not_recompile` (plus
`test_fp16_outside_autocast_still_takes_pertap`)
- `test_diffusion_ref_preprocess.py`:
`test_batched_normalize_uses_64_bit_offsets`,
`test_probe_oom_is_not_cached`
- `test_diffusion_int8_attention_resid_fold.py`:
`test_a_flipped_switch_races_its_own_kernel`
- `test_mps_large_attention_guard.py`:
`test_cold_prefill_check_traces_under_fullgraph`

The touched suites and their neighbours (per-tap VAE, reference
preprocess, MPS guard and families, ROCm contiguous q/k/v and k/v,
CUTLASS race key, attention install, every INT8 attention suite) give
657 passed, 175 skipped (GPU / Mac only) on Linux CPU, torch 2.12.1,
Triton 3.7.1.

## Not changed

- #18966: the 2,560-token q/k/v gate splits a dynamic range into two
graphs. That is bounded: 8 lengths from 1,024 to 4,096 under
`fullgraph=True, dynamic=True` compiled 2 graphs. Studio's trainer never
marks a dynamic range across the threshold.
- #18979: over-cap query lengths still specialize the chunk loop under
compile. Studio never compiles on MPS (training compiles on CUDA only,
and the MPS target defaults to eager).


## GPU, Windows ROCm and Mac checks

Same host and job for both arms, base = the merge base.

| platform | check | base | this PR |
|---|---|---|---|
| A100 40 GB | Lanczos normalize of a `[24, 8192, 8192, 3]` uint8 batch
| illegal memory access | 24 of 24 images equal to the torch reference |
| A100 40 GB | real OOM in the load-time probe, then memory freed | GPU
path off for the process | probes again, GPU path on |
| A100 40 GB | GPU Pillow parity, 6 sizes; INT8 `-m gpu` tests | 6/6; 6
passed | 6/6; 6 passed |
| L4 | flip the residual-fold switch in one loaded process | 1 race,
same decision key | 2 races, keys differ |
| Windows gfx1151 | bf16 1920x1088x121 LTX-2.3 decode | 10 per-tap calls
| 10 per-tap calls, bit-identical, time within the base A/A spread |
| macos-15 | MPS guard suites with `UNSLOTH_MPS_LARGE_ATTENTION=1` | 4
failed, 90 passed | same 4 failed (stock attention past the threshold,
the bug the guard exists for), 92 passed |

On Metal, a V batch wider than Q and K does not broaden the attention,
so the guard keeps counting Q and K only.
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.

1 participant