Skip to content

Studio Qwen-Image-2.1: pass cuDNN attention the strided Q/K/V instead of contiguous copies - #18083

Merged
danielhanchen merged 1 commit into
mainfrom
studio-qwen21-sm89-step
Nov 17, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-qwen21-sm89-step

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Where Studio pins cuDNN attention (Auto on sm86 / sm90, an explicit cudnn request, or INT8 attention off or losing its race), diffusers' _native_cudnn wrapper copies Q, K and V to contiguous [B, H, S, D]. The processor then copies the output back for to_out. cuDNN can read the processor's [B, S, H, D] strides itself, so Qwen-Image-2.1's plain decode call now runs on the views.

  • When it installs: per card, only when a probe finds the strided call bitwise equal to the contiguous one.
  • What keeps diffusers' path: masked, causal, scaled, dropout, GQA and context-parallel calls.
  • INT8 attention: its race now times this strided call as the incumbent, and falls back to it.
  • Kill switch: UNSLOTH_DIFFUSION_Q21_STRIDED_ATTN=0.

Default renders on L4 and G4 already use native flash or INT8 attention, so they are unchanged and bit-identical.

Results

Qwen-Image-2.1 Turbo, 1024x1024, fresh process per arm, interleaved:

card / config main s/step branch s/step delta A/A spread LPIPS
L4 default 0.6990 0.6994 +0.06% 2.2% 0
L4, cuDNN pinned, 5 pairs 0.7434 0.7363 -0.96% (5/5 faster) 2.3% 0
L4, cuDNN pinned, base 25 steps, 3 pairs 0.7592 0.7494 -1.0% (3/3 faster) 1.8% 0
G4 default 0.1120 0.1119 -0.04% 0.2% 0
G4, cuDNN pinned 0.1198 0.1179 -1.54% (3/3 faster) 0.2-0.4% 0
  • Per decode call on L4: 5820 us with copies vs 4715 us strided, bitwise equal.
  • Profile: the cuDNN copy kernel (448 calls, about 100 ms per render on L4) no longer appears.
  • Engagement: the "32 attention modules pass cuDNN their strided views" line shows in every branch run.

Testing

  • CPU: test_diffusion_qwenimage21_strided_attn.py, 12 tests (eligibility, gating, kill switch, the INT8 wiring). It fails to collect on main; related suites pass.
  • GPU: the head tree's pytest passes on L4 and G4 (174 passed), including the 2 GPU bitwise tests. Those bitwise tests also pass on a B200; that run checks correctness only, not timing.
  • Not covered: sm86 (RTX 30) has no allowed test card. The change applies there, but no number exists.

… of contiguous copies

Where Studio pins cuDNN attention (Auto on sm86 / sm90, an explicit cudnn
request), diffusers' _native_cudnn wrapper copies Q, K and V to contiguous
[B, H, S, D] and the processor then copies the output back for to_out.
cuDNN reads the processor's [B, S, H, D] strides itself, so the plain
decode call now runs on the views. Installed per card only when a probe
finds it bitwise equal to the contiguous call; masked, causal, scaled,
dropout, GQA and context-parallel calls keep diffusers' path, and the INT8
route races and falls back to the same strided incumbent.
UNSLOTH_DIFFUSION_Q21_STRIDED_ATTN=0 disables.
@danielhanchen danielhanchen self-assigned this Nov 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T05:38:03.354672Z 4365a63 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: 🔄 Running

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-11-17T05:36:29.875628Z 4365a63 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 4365a63959

ℹ️ 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 d9d5569 into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the studio-qwen21-sm89-step branch November 17, 2026 06:21
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…ded cuDNN admits only the probed dtype, fused int8 takes plain SYMMETRIC only, `_int_mm` fallback stays on the operand's card (unslothai#18140)

Fixes from a re-check of recent Studio INT8 kernel PRs.

1. **CFG replicas lose the INT8 sink mode (unslothai#18004, route from unslothai#17758).**
`Int8Route.__reduce__`
(`studio/backend/core/inference/diffusion_int8_attention_dispatch.py`)
rebuilt the route from its constructor arguments only, so
`copy.deepcopy` (Studio's CFG-parallel replica builder), `copy.copy` and
pickle reset the sink kernel mode chosen at install to 0. With CFG split
across two cards, the replica ran the plain INT8 path while the primary
ran the sink path, so the guided output depended on the card count. The
reduce tuple now carries the mode as state.
2. **Qwen-Image-2.1 strided cuDNN (unslothai#18083).** The `StridedCudnn` marker
kept only the probed card ids, so a bf16 probe also sent fp16 calls (an
autocast, or a later cast of the pipe) down the strided path. The marker
now carries the probed dtype, `plain_qkv` declines other dtypes, and a
re-install at a new dtype probes that dtype. The INT8 dispatch race
named the strided incumbent `dispatch:_native_cudnn`, the same key as
the contiguous cuDNN call, so cached verdicts crossed over; it now races
as `dispatch:_native_cudnn:strided`. The GPU no-copy check asserted
`flatten(2, 3).is_contiguous()`, which also holds when flatten copies;
it now checks the flatten shares storage.
3. **Fused act quant and exact ConvRot take plain SYMMETRIC weights only
(unslothai#17114, unslothai#17617).** `_plain_int8_weight` accepted any mapping containing
SYMMETRIC, so a torchao weight with `SYMMETRIC_NO_CLIPPING_ERR`
activation quant reached kernels that always divide amax by 127.5.
Studio's own loaders build plain SYMMETRIC only, so this narrows a path
no Studio load takes.
4. **`_int_mm` off-grid fallback returns on the operand's card (unslothai#17613,
inherited from torchao).** For K or N not a multiple of 8 the safe
`_int_mm` wrapper (Studio `diffusion_torchao_patches.py` and the copy in
`unsloth/import_fixes.py`) ran the matmul on the CPU and moved the
result with `.to(input.device.type)`, which is the current card. With
the operands on cuda:1 and cuda:0 current, the int32 result landed on
cuda:0. It now moves back to `input.device`.
5. **FLUX.3 strided attention: a test for the no-copy claim (unslothai#17180).**
No test checked it: restoring diffusers' `.contiguous()` copies passed
every test. The new test spies on `scaled_dot_product_attention` and
asserts Q / K / V arrive as the permuted views. Test only.

### GPU results, base (main 62d66cb) vs this branch

CFG sink mode, Kaggle 2x T4 (sm75), torch 2.11.0+cu130, diffusers
0.42.1. Tiny FLUX.1 transformer with random weights at the real head dim
(128), fp16, one attention-sink key; Studio's `CfgParallelRouter` with
the replica built by `build_replica` on cuda:1; INT8 attention installed
with the sink kernels (mode 2, NVRTC CUDA kernel) on both cards; guided
3-step render, cond on cuda:0 and uncond on the replica.

| | base | this branch |
|---|---|---|
| sink mode, primary (cuda:0) | 2, 2 | 2, 2 |
| sink mode, replica (cuda:1) | **0, 0** | **2, 2** |
| kernel path on cuda:1 | plain x4 | sink x4 |
| final latent, CFG split vs single card | rel L2 4.82e-4, max abs
3.9e-3 | bitwise equal |
| uncond step 2, CFG split vs native attention | rel L2 6.43e-4 (single
card 6.11e-4) | 6.11e-4, same as single card |

`_int_mm` fallback, same Kaggle 2x T4: int8 operands on cuda:1, cuda:0
current, both copies of `_make_safe_int_mm` with the real `out_dtype`.

| case (Studio and core copies alike) | base | this branch |
|---|---|---|
| K=65 (off grid) | result on cuda:0 (values exact); the next op with a
cuda:1 tensor raises "Expected all tensors to be on the same device" |
result on cuda:1, exact |
| N=36 (off grid) | result on cuda:0, same error | result on cuda:1,
exact |
| K=64, N=32 (cuBLAS, control) | cuda:1 | cuda:1 |

L4 (sm89), Colab, torch 2.12.1+cu130, cuDNN 9.20.0, torchao 0.17.0:

| fix | check | base | this branch |
|---|---|---|---|
| strided cuDNN | tiny QwenImage21, bf16 probe at install, then the pipe
cast to fp16 | fp16 call takes the strided path (marker has no dtype) |
fp16 call goes to diffusers; marker records bf16 |
| strided cuDNN | fp16 output vs diffusers cuDNN | equal (on L4 the fp16
strided call happens to be correct; the defect is the admission) | equal
|
| plain SYMMETRIC | Int8Tensor FeedForward 256 to 1024,
`SYMMETRIC_NO_CLIPPING_ERR` weights | fused, identical to the SYMMETRIC
result, differs from torchao in 106941 of 153600 elements (max abs
0.086) | stays on torchao, bitwise equal |
| plain SYMMETRIC | plain SYMMETRIC weights | fused, bitwise equal to
torchao | same, same hash as base |
| no-copy test | real cuDNN, bf16, head dim 128 | SDPA gets the views |
SDPA gets the views; with the copies restored it gets contiguous tensors
and the new test fails |

### Tests

-
`studio/backend/tests/test_diffusion_int8_attention_dispatch.py::test_route_copies_keep_the_sink_mode[1|2]`:
fails on main.
- On the T4 pair: `test_diffusion_int8_attention_dispatch.py` base 2
failed (`test_route_copies_keep_the_sink_mode[1|2]`) / 46 passed, this
branch 48 passed with the two-card tests included.
-
`studio/backend/tests/test_torchao_int_mm_transposed.py::test_off_grid_fallback_returns_on_the_operand_card`:
fails on main; on the T4 pair base 1 failed / 9 passed, this branch 10
passed (including the CUDA transposed `_int_mm` exactness cases).
- `studio/backend/tests/test_diffusion_qwenimage21_strided_attn.py`:
`test_marker_admits_only_its_probed_dtype`,
`test_reinstall_at_a_new_dtype_probes_it`,
`test_strided_incumbent_races_under_its_own_name` fail on main; on the
L4 base 3 failed / 14 passed, this branch 17 passed, and the GPU bitwise
test ran in both arms.
-
`studio/backend/tests/test_diffusion_int8_fused.py::test_only_plain_symmetric_activation_quant_is_eligible[SYMMETRIC_NO_CLIPPING_ERR-False]`:
fails on main; on the L4 this branch 101 passed / 1 skipped (a torchao
>= 0.18 case).
-
`studio/backend/tests/test_diffusion_flux3_strided_attn.py::test_strided_processor_hands_sdpa_the_projection_views`:
passes on main, fails with the copies restored.
- CPU (torch 2.14.1) on this branch: the five files pass (100 passed, 78
skipped, running the Qwen-Image-2.1 file in its own process). Running
the Qwen-Image-2.1 file in one pytest process with the others,
`test_real_processor_decode_call_takes_the_strided_path` hits a
RecursionError on main and on this branch alike (test-order interaction,
not touched here).

### Not covered

- No real checkpoint or decoded image: the CFG check compares DiT
latents of a tiny random model, and the auto (raced) route was not
exercised (the dropped field is the same for any non-zero mode).
- sm80 and sm120 cards; the strided cuDNN and SYMMETRIC fixes ran on L4
only, the CFG and `_int_mm` checks on T4 only.
- torchao 0.18 for the SYMMETRIC narrowing.
- The GPU runs used main 62d66cb; the branch was then rebased onto
main 142c398 and only the CPU tests were rerun there.
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…ok, H3-Image LoRA reload message) (#18583)

`test_attention_hook_installs_on_cudnn_pins` (#18083) read the source of
`_apply_attention_backend` and looked for the literal `if backend ==
"_native_cudnn" and target is not None and _is_cuda_nvidia(target):`
line. #18418 moved that branch into `_apply_attention_backend_impl`, so
on main the test fails with `ValueError: substring not found` before it
checks anything. The production hook is still installed; only the test
broke, and a test that greps source text would break again on the next
refactor.

## Change

Test only (`tests/test_diffusion_qwenimage21_strided_attn.py`). The test
now runs the real `_apply_attention_backend` on a fake DiT, with the
card checks stubbed (`_is_cuda_nvidia`, `_cudnn_serves_pipe`, kernel
install, ROCm guards) and the Qwen-Image-2.1 and FLUX.3 strided installs
replaced by recorders. No production code changes.

## Tests

- `test_attention_hook_installs_on_cudnn_pins`: a `_native_cudnn` pin on
an NVIDIA target engages, pins the DiT, and calls the Qwen-Image-2.1
strided install with `(pipe, "_native_cudnn", target, logger)`. The old
version fails on main (`ValueError`), the new one passes here. With the
`install_q21_strided(...)` call removed from
`_apply_attention_backend_impl`, the new test fails, so it still guards
the hook.
- `test_attention_hook_skips_other_pins` (2 cases): a cuDNN pin on a
non-NVIDIA target and a `_native_math` pin on NVIDIA engage without
calling either strided install.

Suite (`test_diffusion_qwenimage21_strided_attn.py`,
`test_diffusion_flux3_strided_attn.py`,
`test_diffusion_int8_attention_auto.py`,
`test_diffusion_int8_attention_dispatch.py`,
`test_diffusion_int8_attention_persisted.py`,
`test_diffusion_attention.py`,
`test_diffusion_attention_honest_status.py`,
`test_diffusion_attention_cudnn_head_dim.py`): main 272 passed, 1
skipped, 1 failed (`test_attention_hook_installs_on_cudnn_pins`); this
branch 275 passed, 1 skipped, 0 failed.

## Not proven here

No GPU run; none is needed for a test-only change. The new test fakes
the card and the installs, so it shows the apply calls the hook, not
that the strided processors run on a real NVIDIA card (the existing
`gpu`-marked tests in the same file cover that).

## Second stale test: MiniMax-H3-Image LoRA reload message


`tests/test_diffusion_h3_image_trainer.py::test_backend_runs_only_the_load_time_lora_set_for_h3_image`
also fails on main: #18420 reworded the reload error to the shared
`LORA_RELOAD_REMEDY` ("Reload the model with the LoRA selection: ..."),
but the test still matched the old "Load the model again". The behaviour
it checks is unchanged (a different LoRA set or weight on an H3-Image
load is refused), so the test now matches the current message. The file
goes from 1 failed, 20 passed on main to 21 passed here.
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