Repository navigation
Studio: INT8 attention for diffusers-dispatch DiTs (Qwen-Image-2.1, Wan 2.2) - #17758
Conversation
…e kernel Families whose DiT processors call dispatch_attention_fn (Qwen-Image-2.1, LTX-2, Wan 2.2, Z-Image) now reach the INT8 attention kernel without a processor of their own. Each routable processor gets an Int8Route as its backend (a str equal to the incumbent backend name), and a wrapper around dispatch_attention_fn sends unmasked, non-causal, gradient-free calls of a checked dtype and head dim, at or above the race's token floor, to torch.ops.unsloth_studio.int8_attention_nhd. Every other call runs the incumbent backend. apply_attention_backend installs the route after the backend pick: by name or UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1 wherever the card check passes, and with the switch unset for the listed DiT classes where the kernel wins the timed race against the processor's own backend. The video loader now passes the attention request through. UNSLOTH_DIFFUSION_INT8_ATTENTION_DISPATCH=0 turns off only this route.
…route Where the kernel loses the card race at 4096 / 1024 tokens (A100 against SDPA), time it again at 16384 / 8192 tokens and route the dispatch calls from that length on when it wins there by more than the race margin.
Calls below a route's token floor now leave after the mask check, so an eager family whose calls never reach the floor pays a few attribute reads per call.
…oute Its teacher-forced per-step error with the kernel (rel L2 0.035 at bf16 weights) is above the error of the INT8 weights Studio ships for it (0.024), so it now routes only by name or with the env switch. Qwen-Image-2.1, Wan 2.2 and LTX-2 stay within their shipped weight error and keep racing by default.
Its video output stays within the INT8 weight error with the kernel (rel L2 0.044 against 0.046), but its audio output does not (0.010 against 0.008), so it now routes only by name or with the env switch, like Z-Image-Turbo.
A layer split or a CFG replica places DiT blocks on the selection's other cards after the attention pick, so the dispatch route ran native there. The install now runs the accuracy check and the race on each card of the load's multi-GPU selection and keeps a token floor per card that passed; a call on any of them reaches the kernel, a call spanning two cards keeps the incumbent.
…decisions The dispatch route no longer takes calls under 1024 query or key tokens, even forced: text refiners, audio streams and short text cross-attention lose to every incumbent measured. Where the card race wins at 4096 tokens but not at 1024, a race at 2048 sets the floor at 1536 or 3072 instead of the midpoint guess. Eager calls cache the route decision per call signature, so a call repeated every step costs one dictionary lookup.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 77bb1e2c74
ℹ️ 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".
| with torch.no_grad(): | ||
| q, k, v = I8.probe_inputs(device, dtype, tokens, heads, head_dim, seed = tokens) | ||
| ms = I8._median_ms( |
There was a problem hiding this comment.
Run the extra races in the probed card's device context
For a multi-GPU load, the secondary-card mid/long races run after I8.verdict() has exited its torch.cuda.device(index) context. Here, tensors are allocated on device, but I8._median_ms() records its CUDA events on the current device's stream, so it measures the primary card's idle stream rather than the secondary card's attention kernels. Those timings are then cached and used to select the secondary card's token floor, potentially enabling slower INT8 calls or rejecting beneficial ones. Wrap the probe and timing in torch.cuda.device(device), as I8.verdict() already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6d37387: the mid and long races now probe and time inside torch.cuda.device(device), so a secondary card's events record on its own stream. Added test_extra_races_time_on_the_probed_card, which fails without the change.
…card current [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6d373870e3
ℹ️ 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".
| if install_int8_dispatch(pipe, target, requested = requested, logger = logger): | ||
| return BACKEND |
There was a problem hiding this comment.
Preserve speed-off behavior when installing automatic INT8 routes
When a Qwen-Image-2.1 or Wan pipeline is loaded with speed_mode="off", automatic attention selection, and the INT8 environment switch unset, this unconditional installation can still enable approximate INT8 attention if the card race passes. Both image and video loaders call this function even when speed is off; select_attention_backend() deliberately returns native attention in that case to preserve bit-identical output, but the new installer receives no speed-mode information and independently enables AUTO_DITS. Pass the speed-mode eligibility through and suppress automatic INT8 routing for an explicit speed-off load, while retaining explicitly requested INT8 behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 58568a5: apply_attention_backend takes speed_active and passes it to the dispatch install; with speed off the automatic route (switch unset, not requested) installs nothing and runs no race, so output stays bit-identical. A request by name or the env switch still routes. The image and video loaders pass effective_speed != off. Test: test_speed_off_keeps_the_automatic_route_off.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
[skip ci]
…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.
…2 A14B (#18790) With INT8 attention on Auto (the default), Wan 2.2 A14B renders a different clip from the one it renders with INT8 attention off. Auto races the INT8 kernel for every `WanTransformer3DModel`, and the two A14B experts are that class, so on A100 both experts take it: 160 attention modules, the CUDA kernel. It is about 10% faster per step, but the error compounds over the steps of both experts and the clip changes. On a busy prompt the stall layout, a vehicle, the signs and the lighting all change. ## Change - `diffusion_int8_attention_dispatch.py`: a new `AUTO_SINGLE_EXPERT_ONLY` set (`WanTransformer3DModel`) and a `two_expert_pipeline(pipe)` check (`transformer_2` present). With the switch unset, a DiT in that set is not raced when its pipeline has a second expert. - `diffusion_int8_attention.install_auto` applies the same rule to the strided route. - These still route both experts exactly as before: - an explicit per-load On, - `unsloth_int8` requested by name, - `UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1`. - Wan 2.2 5B, which has one expert, keeps its race and its INT8 default (#17758). ## Evidence Colab A100-SXM4-40GB, main `8b7cde79eb`, hosted INT8 pair (group offload, FP8 text encoder). 832x480, 33 frames, 10 steps, 2 prompts, fresh process per arm. | Arm | INT8 modules | Steady s/step | Frames sha256, prompt 1 / prompt 2 | |---|---|---|---| | INT8 off | 0 | 3.91 | `022433d8...` / `ef160cf3...` | | INT8 off, second fresh process | 0 | 3.91 | `022433d8...` / `ef160cf3...` | | INT8 on (forced) | 160 | 3.51 | `d39260ae...` / `9303ed2a...` | | main, Auto | 160 | 3.53 | `d39260ae...` / `9303ed2a...` (the forced-on clip) | | this branch, Auto | 0 | 3.98 | `022433d8...` / `ef160cf3...` (the off clip) | - **On vs off:** - LPIPS (alex, all 33 frames) 0.135 and 0.277; PSNR 23.1 and 17.7 dB. - The off-vs-off repeat is bit-identical, so none of this is run-to-run noise. - The latent error grows about 1.5 to 2x per step through both experts, reaching rel L2 0.20 and 0.39 by the last step. No single step or expert accounts for it. - **Visual check:** first, middle and last frames side by side. Both clips are clean, with no artifacts. The first prompt keeps the scene with shifted positions; the second changes its content. - **Main and branch Auto** ran on two different A100 VMs. Each matches its expected arm by frame hash. ## Tests - `tests/test_diffusion_int8_attention_dispatch.py::test_auto_leaves_a_two_expert_wan_alone_and_keeps_a_one_expert_wan`, on CPU with a fake card: - Auto routes 0 modules of a two-expert Wan pair. - The name and On each route all 8. - A one-expert Wan still routes its 4. - On main this test fails (Auto routes the pair), and here it passes. `test_differential.py` reports DISCRIMINATING: 1 fixed, 0 head failures. - `tests/test_diffusion_int8_attention_{dispatch,auto,families,toggle}.py`: 164 passed and 7 skipped here, against 163 passed and 7 skipped on main. ## Not covered - Only A100 and only 832x480x33 were run. On L4, G4 and the 720p default this branch is the same code path (A14B Auto stays off), but main's drift there was not measured. - Wan 2.1 14B (single expert) keeps its race and was not measured. - AMD gfx1151 Linux, where Wan is in the ROCm Auto list, gets the same rule. It did not run there.
Summary
Studio's INT8 attention kernel (#17718, Triton fallback #17726) only ran in families with their own strided
attention processors (MiniMax-H3 video, MiniMax-H3-Image, FLUX.3). This PR sends the attention of every family whose
DiT processors call diffusers'
dispatch_attention_fnto the same op, without a processor per family, and turns iton by default for Qwen-Image-2.1 / 2.1-Turbo and Wan 2.2 wherever the on-card check and race say so. Z-Image-Turbo and
LTX-2 / 2.5 route on request.
diffusion_int8_attention_dispatch.py(new):install(pipe, target, requested=...)gives each routableprocessor an
Int8Routeas its_attention_backend. The route is astrequal to the incumbent backend's name,so code that reads the attribute without knowing it (
AttentionBackendName(...),.value, comparisons) still seesthe incumbent. A wrapper installed over the module-level
dispatch_attention_fnof the loaded diffusers and Studiomodules sends the calls it can take to
torch.ops.unsloth_studio.int8_attention_nhd(the kernel's own[B, S, H, D]layout, so nothing is copied) and passes every other call, with the real incumbent backend, to diffusers.
attn_mask,is_causal, dropout, a non-default scale, GQA, LSE or other extraarguments, context parallel, gradient calls, a dtype or head dim the card check did not pass, another card, and
calls with fewer query or key tokens than the race's floor. So Qwen-Image text masks, Z-Image's padded batches,
LTX-2's masked text cross-attention and its short audio streams, and Wan's 512-token text cross-attention all stay
on the incumbent; full unmasked self-attention (and Qwen-Image-2.1's unmasked cached decode, target queries against
prefix + target keys) routes.
verdict(accuracy check against fp32 attention, sharp probe, per-card race againstthe processor's own backend with the 2% margin). No call under 1024 tokens routes, forced or not (text refiners,
audio streams and short text cross-attention lose to every incumbent; 126 tokens: 6x slower). Where the kernel wins
at 4096 but not 1024, a race at 2048 sets the floor at 1536 or 3072. Where it loses at the race's sizes but wins at
video lengths (A100 against SDPA), a race at 16384 / 8192 tokens routes only the calls from that length on.
one dictionary lookup per call; compiled blocks trace the checks once as guards.
pick, so the check and the race run on every card of the load's selection and the route keeps a token floor per
card that passed. A call on any of those cards reaches the kernel; a call whose tensors span two cards keeps the
incumbent.
UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0never routes;=1or a load that asks forunsloth_int8routes every routable DiT wherever the check passes (no race, except the Triton stand-in);
UNSLOTH_DIFFUSION_INT8_ATTENTION_DISPATCH=0turns off only this route. Unset races the classes inAUTO_DITS.apply_attention_backendinstalls the route after the backend pick and reportsunsloth_int8when it engaged (sothe compile cache keys apart). The video loader now passes the load's attention request through.
AUTO_DITS. Z-Image's teacher-forced error with the kernel is 1.4x its shippedINT8 weight error (below its FP8 error); LTX-2.5's video output is within its INT8 weight error but its audio
output is 1.3x. Both route only on request, though they are 5-18% (Z-Image) and 3.5-5.8% (LTX-2.5) faster.
No change to the kernel, its configs, the strided processors or
diffusion_int8_attention.py.Results
Studio defaults per card (the bare-click load: the shipped weight quantisation, offload tier and attention pick),
fresh process per arm, order A B B A (A = merge base and head with the switch at 0, B = head unset), 8 prompts with
matched seeds, timed after one warm render. Accuracy: one denoiser forward at the native arm's saved inputs
(teacher forced) at 15 / 50 / 85% of the steps, relative L2 against native attention on the same weights; the bar
is the same metric for Studio's FP8 and INT8 weights against bf16 weights (both with native attention).
Speed (s per image or clip, median of 16 renders per side, 8 on the L4 Wan row; A/A = the two native processes, which agree to within
the spread shown; "routed" = INT8 calls per render, 0 = the race kept native):
The Z-Image and LTX-2.5 rows were measured before they were taken off the default list; they are what
unsloth_int8by name or the env switch gives. On A100 the race at 4096 tokens keeps SDPA; the second race routes from 6144 tokens, so Wan and
LTX-2.5's 14k-token stage route and 1024^2 images do not (A100-40 Qwen-Image-2.1-Turbo with the route installed and
no call taken: 1.913 against 1.910 s, inside the 0.18% B/B spread). Peak memory (allocated / reserved / nvidia-smi) and
host RSS are unchanged within 0.2 GiB in every pair.
Accuracy, teacher forced (median / max relative L2 of the denoiser output over 8 prompts x 3 steps):
On the shipped weights, auto against native (same card): Qwen-Image-2.1 0.009 / 0.013 (G4, L4), Turbo 0.010 / 0.031,
Wan 0.013 / 0.030 (native A/A on the same probe: 0.004 G4, 0.012 A100, where Wan's own run-to-run variation is that
large), LTX-2.5 0.058 / 0.104 (G4). End of trajectory against the native render (same seed): LPIPS 0.018 / PSNR 36.1
dB Qwen-Image-2.1 G4, 0.033 Turbo, 0.19 Wan G4 (Wan's own A/A on A100: 0.11-0.12), 0.21 LTX-2.5 G4 / 0.027 A100-80
(audio relative L2 0.29), 0.057 Z-Image; the native A/A is bit-identical everywhere except Wan on A100.
Kill switch:
UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0gives 0 routed modules and 0 INT8 calls on every card, and thesame pixels as the merge base (LPIPS 0, PSNR 99 dB on every family except Wan on A100, whose base A/A is not
deterministic either). T4 standard (12.7 GB host RAM) could not load Z-Image at Studio's defaults on the base either
(killed), so T4 numbers are from T4-HM.
Tests
tests/test_diffusion_int8_attention_dispatch.py(43, 3 of them CUDA): the route marker (incumbent semantics, copies, pickle),every fallback reason, the wrapper passing the real incumbent, module patching, real Wan / Z-Image / LTX-2
processors (masked and unmasked calls), the token floor, the long race, kill switches, gate failure, no kernel for
the card, Triton stand-in race, ROCm auto off, the
apply_attention_backendhook, a compiled Wan block withfullgraph=Trueholding two INT8 ops and no graph break, a masked call staying in one graph; CUDA: a Wan DiTroutes and matches native, compiled and CUDA-graph-replayed dispatch call.
attention suites (980 tests) still pass.
two Triton cases) and on G4 at the first commit (159 passed) on Colab;
B200 (no kernel config): the route keeps native in every switch setting and the DiT output is bit-identical.
Not covered
covered by the unit test, not end to end (the per-render INT8 call counts were counted on the Python side).