Skip to content

Studio int8: keep torchao's transposed weight in the TN layout for _int_mm (fixes an illegal memory access on L4) - #17613

Merged
danielhanchen merged 4 commits into
mainfrom
h3img-l4-streamed-crash
Nov 13, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
h3img-l4-streamed-crash

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

MiniMax-H3-Image INT8 on L4 (the default streamed tier) crashed on every 1024 render with an illegal memory access was encountered or CUBLAS_STATUS_EXECUTION_FAILED. 2048 renders worked. The crash was deterministic: 6 of 6 arms on main, including the first render of a fresh process.

Root cause: Studio's copy of torchao's safe_int_mm made every transposed int8 weight row-major before calling torch._int_mm. When mat2 is row-major, cuBLASLt 13.x on sm89 (cuBLAS 13.1.1.3, torch 2.13 cu130) picks an NN int8 kernel. That kernel reads activation rows in 64-row tiles without checking the row count, so when M is not a multiple of 64 it reads up to one tile past the end of the activation. Most of the time those extra bytes fall in allocator slack and nothing happens. Inside Studio, the activation can end exactly at a mapped segment boundary, and then the read faults.

Fix: hand the transposed weight to _int_mm as it is. That column-major view is cuBLASLt's TN int8 layout, which every other Studio int8 GEMM already uses (torch._int_mm(a, w.t())). Only a mat2 with arbitrary strides still gets the .contiguous() copy. The Studio copy and unsloth/import_fixes.py change together, because the drift test requires them to stay identical.

Switches: UNSLOTH_TORCHAO_INT_MM_TRANSPOSED=0 restores the row-major copy. ROCm keeps the copy, since the TN path was only checked on cuBLASLt.

Where it faulted

step result
CUDA_LAUNCH_BLOCKING=1, first 1024 render error raised inside safe_int_mm's _int_mm try block, transformer_blocks.0.attn.to_out.0 (a resident block, so streaming is not involved)
sync after every _int_mm the first sync after _int_mm(a[1184, 7168], b[7168, 5376]) raises the illegal address; to_q/to_k/to_v at [1184, 5376] x [5376, 7168] pass
kill switches: stream prefetch off, strided attention off still crash
1024 as the first render of a process crash (the 2048 render before it is not needed)
compute-sanitizer memcheck, plain _int_mm, row-major b, no allocator caching Invalid __global__ read, 114,689 bytes past the 8,486,912-byte activation (M=1184); also at M=4256 and on all four H3 Linear shapes
same, M = 1216 or 1280 (multiples of 64) 0 errors
same, transposed b (TN), all four shapes, M = 1184 and 4256 0 errors, exact int32
torch 2.6.0 / cuBLAS 12.4.5.8, both layouts 0 errors, exact (the NN over-read is new in the cuBLAS 13 stack)

Results (L4, torch 2.13.0+cu130, same VM)

arm renders crashes 2048 denoise (s) 1024 denoise (s)
main, 2048 then 1024 (3 arms) 3 x 2048 ok 3 of 3 on the first 1024 69.2-75.6 crash
main, 1024 only 0 1 of 1 n/a crash
this PR, 2048 / 1024 / 1024 / 2048 / 1024 / 1024 (2 processes) 12 0 33.7-34.1 7.9-8.4
this PR, 1024 only 3 0 n/a 7.9-9.0
  • 2048 renders are byte-identical to main: md5 ac5c164f... (warm, seed 1) and cffd83cf... (lighthouse, seed 7) on both trees. Integer GEMMs are exact, so moving to a different kernel does not change any value.
  • Repeated 1024 renders in one process are byte-identical to each other, and match across processes.
  • The 2048 speedup comes from removing a full row-major copy of every int8 weight on every call. The timings are single runs on a shared Colab VM, not an exclusive benchmark.
  • TN also accepts any row count. On the same shape, the NN path accepted only multiples of 32; every other row count returned CUBLAS_STATUS_NOT_SUPPORTED and fell back to fp32.

Tests

  • New CPU tests in studio/backend/tests/test_torchao_intmm_patch_wiring.py (meta tensors reach the GEMM branch on a CPU-only host):
    • a transposed weight reaches the GEMM as the same column-major view, with no copy. This test fails on main.
    • a row-major mat2 is passed through unchanged, and an arbitrarily strided one is still made contiguous.
  • New studio/backend/tests/test_torchao_int_mm_transposed.py: routing on CPU (TN kept, kill switch and ROCm keep the copy), and on CUDA, fp64 exactness of both layouts at the MiniMax-H3 shapes including M=4384 K=7168 N=5376. 16 of 16 pass on an L4; with UNSLOTH_TORCHAO_INT_MM_TRANSPOSED=0 the same L4 render crashes again (negative control). Exactness also checked on torch 2.6.0+cu124 and 2.10.0+cu128.
  • test_torchao_intmm_patch_wiring.py, tests/test_import_fixes_drift.py (int_mm cases), test_diffusion_int8_fused.py and test_diffusion_peft_torchao_guard.py pass.

Not covered

  • Other GPUs (A100, Blackwell, T4) were not rerun. The resident tiers there use Studio's own int8 GEMM, not this path.
  • torch.compile traces are unchanged (that branch returns before the layout code), but no compiled run was made.
  • No exclusive-card timing.

…nt_mm

Studio's copy of torchao's safe_int_mm made every transposed int8 weight row-major
before torch._int_mm. With a row-major mat2, cuBLASLt 13.x on sm89 (L4, cuBLAS
13.1.1.3) picks an NN int8 kernel that reads up to a 64-row tile past the end of
the activation when M is not a multiple of 64. compute-sanitizer: 114,689 bytes
past an 8,486,912-byte activation at M=1184, K=7168, N=5376. Inside Studio the
activation can end a mapped segment, so MiniMax-H3-Image INT8 streamed on L4
crashed on every 1024 render (illegal memory access / CUBLAS_STATUS_EXECUTION_FAILED).

The transposed view is the TN layout every other Studio int8 GEMM already uses:
memcheck clean on all H3 shapes, exact int32, any M accepted, and no full weight
copy per call (2048 denoise on L4: 72 s to 34 s, images byte-identical).
Arbitrarily strided mat2 still gets the copy. Both copies (Studio and
unsloth/import_fixes.py) change together.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 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-13T11:18:52.789162Z 681cf30 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.

…ight, plus GPU exactness tests

UNSLOTH_TORCHAO_INT_MM_TRANSPOSED=0 restores torchao's row-major copy. ROCm keeps
the copy (hipBLASLt was not checked). The new tests cover the routing on CPU and,
on CUDA, fp64 exactness of both layouts at the MiniMax-H3 shapes including
M=4384 K=7168 N=5376.

[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: e2938c2819

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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 681cf30132

ℹ️ 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 self-assigned this Nov 13, 2026
@danielhanchen
danielhanchen merged commit 2befb8d into main Nov 13, 2026
@danielhanchen
danielhanchen deleted the h3img-l4-streamed-crash branch November 13, 2026 13:13
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…rs (#17658)

Stacked on #17617 (base branch `h3-int8-sm120`). Retarget to `main` once
that merges.

## Summary

#17617 moved uncompiled, resident int8 denoisers onto Studio's
bit-identical int8 GEMM routes. A denoiser that streams block by block
still ran torchao's eager int8 Linear. That covers MiniMax-H3 INT8 at
speed `off` on L4, A100-40 and any card where the other components need
the room. This PR gives those streamed denoisers the same routes in
call-time mode.

MiniMax-H3 INT8-ConvRot, speed `off`, streamed, 640x384, 124 frames, 20
steps:

- G4: 2.06 -> 1.14 s/step, the same speed as the resident tier (1.13).
- L4: 12.26 -> 9.16 s/step (-25%).
- Frames are byte-identical to the base on both cards (sha256).

## Root cause

`apply_speed_optims` runs `_install_eager_int8_gemm` (#17617) before
placement, and that function skips any denoiser that will move (`moved =
offload_active if denoiser_offloaded is None else denoiser_offloaded`).
The compiled streamed install (`video.py`, `if denoiser_streamed and
"compiled" in speed_optims`) covers only the compiled tier. So a
streamed H3 denoiser on speed `off` / `eager`, or after a declined
compile, kept torchao's Linear for all 300 int8 calls per step: a
float32 epilogue, an eager rotation and an eager act quant. The generic
video placement (`apply_memory_plan`, with the event-fenced prefetch
from `diffusion_memory`) has the same gap for any other family that
streams int8 Linears.

## Change

- `diffusion_int8_gemm.install_streamed_eager(transformer, device)` is
`install(..., device=device, exact=True)`. These are `install_eager`'s
routes: the fused-dequant GEMM, the dense `rotq_i8` rotation + act quant
(never `rotq_h16`), and no SwiGLU fusion. They run in the existing
call-time mode: each call checks that the Linear's own weight is still
the installed Parameter and sits on the activation's card. Otherwise the
call takes torchao's path.
- `diffusion_speed.install_streamed_eager_int8_gemm(pipe, device)` runs
after placement. It engages only on a denoiser that:
- is driven by the event-fenced prefetcher (`module_prefetcher`). That
prefetcher copies into the same Parameters (`swap_tensors` /
inner-tensor re-pointing), so the identity check sees every onload;
- is not compiled (`compiled_denoiser`), not already swapped, and has
int8 candidates.
- `video.py` calls it in two places:
- in the MiniMax-H3 branch, for a streamed denoiser the compile did not
take;
- in the generic video placement, right after
`compile_pipe_below_offload_hooks`, for every denoiser view.

Status reports `int8_gemm_streamed`, and `int8_gemm_live` drops it when
nothing swapped.
- `shared_rotq_linears` (shared Q/K/V act quant) now passes `exact` when
every Linear in the group is on the eager routes. The shared quant is
then the same dense kernel each Linear runs on its own. Compiled
installs never set the mark, so they are unchanged.

Switches:

- `UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED_EAGER=0` keeps torchao's path on
streamed denoisers.
- `UNSLOTH_DIFFUSION_INT8_GEMM_EAGER=0`,
`UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0` and
`UNSLOTH_DIFFUSION_INT8_GEMM=0` also turn it off.

## Results

MiniMax-H3 fl2va, hosted INT8-ConvRot (text encoder int8), 640x384, 124
frames, 20 steps, guidance 1.0, torch 2.14.1+cu130, torchao 0.18.0,
Triton 3.8.0. Setup:

- Base is this PR's parent with #17618 and #17613 merged in, and it is
repeated (A/A). The base already includes #17613's TN-layout `_int_mm`,
so it is faster than the 3.31 s/step #17617 started from.
- One Colab session per card. Each arm runs in a fresh process.
- s/step is the median over steady denoiser forwards. A
`cuda.synchronize` at each forward boundary applies to every arm alike.
- s/clip is the `generate` wall time, which includes the encode and the
decode.

G4 (RTX PRO 6000 Blackwell), streaming forced with the VRAM budget, 2
clips:

| placement | arm | s/step | s/clip (clip 1, clip 2) | peak VRAM alloc
GiB | frames vs base |
|---|---|---:|---|---:|---|
| fully streamed (budget 30%, `UNSLOTH_H3_DIT_RESIDENT=0`) | base |
2.056 | 45.9, 43.9 | 6.37 | - |
| | base repeat | 2.057 | 45.7, 43.9 | 6.37 | identical |
| | this PR | **1.140** | 28.6, 25.6 | 6.38 | identical |
| | this PR, switch off | 2.057 | 45.2, 43.9 | 6.37 | identical |
| part resident (budget 20%, 27 of 50 blocks resident) | base | 2.049 |
45.7, 43.7 | 16.95 | - |
| | base repeat | 2.050 | 45.7, 43.7 | 16.95 | identical |
| | this PR | **1.137** | 26.7, 25.5 | 16.95 | identical |
| budget 30% (per-request refit holds all 50 blocks) | base | 2.037 |
45.9, 43.5 | 26.60 | - |
| | base repeat | 2.039 | 45.2, 43.5 | 26.60 | identical |
| | this PR | **1.126** | 27.3, 25.3 | 26.60 | identical |
| | this PR, switch off | 2.039 | 45.2, 43.5 | 26.60 | identical |
| resident (no budget, #17617's eager install) | this PR | 1.128 | 25.4,
25.3 | 25.32 | identical |
| speed default (compiled), budget 30% | base / this PR | 0.891 / 0.891
| 28.9, 19.8 / 22.9, 19.8 | 25.13 / 25.13 | identical |
| speed default (compiled), fully streamed | this PR | 0.895 | 28.6,
20.0 | 4.91 | - |

L4, 1 clip (it streams on its own: 9 blocks resident at load, 37 of 50
after the per-request refit):

| arm | s/step | s/clip | peak VRAM alloc GiB | frames vs base |
|---|---:|---:|---:|---|
| base, speed off | 12.261 | 298.7 | 20.31 | - |
| base repeat | 12.264 | 288.0 | 20.31 | identical |
| this PR, speed off | **9.156** | 225.7 | 20.31 | identical |
| base, speed default (compiled) | 6.345 | 189.2 | 19.30 | - |
| this PR, speed default (compiled) | 6.359 | 176.3 | 19.30 | identical
|

Host RSS peaks were 96-105 GiB on G4 and 46.4-46.7 GiB on L4. The spread
was the same between the base and its repeat, with no shift this PR
adds.

What runs per denoiser forward (torch.profiler, two steady forwards, per
forward):

| card, placement | arm | int8 Linear calls | route | int8 GEMM kernel |
H2D copy (overlapped) |
|---|---|---:|---|---|---|
| G4, fully streamed | base | 300 | torchao: eager rotation + quant,
cuBLAS `i16832gemm_s8 tn`, float32 epilogue | 451 ms | 344 ms (330 ms) |
| G4, fully streamed | this PR | 300, 0 fallbacks | `rotq_i8` +
`i8mm_dq_tma` | 431 ms | 344 ms (333 ms) |
| L4, streamed | base | 300 | torchao | 2555 ms | 414 ms (394 ms) |
| L4, streamed | this PR | 300, 0 fallbacks | `rotq_i8` + cuBLAS TN +
torchao's epilogue op for op (the Triton GEMM stays off on sm_89) | 2699
ms | 412 ms (392 ms) |

The prefetcher already hides the copies (14 ms exposed per forward on
G4, 20 ms on L4), so the streamed tier was compute-bound on torchao's
eager Linear. On G4 the base's three largest elementwise kernels (the
float32 / bf16 epilogue passes and the bf16 copy, about 490 ms per
forward) are gone, and the eager rotation + quant becomes one `rotq_i8`
launch per Linear. With them gone, the streamed tier runs at the
resident tier's speed.

## Tests

- New CPU tests:
- both kill switches, and `install_streamed_eager` threading `device` +
`exact` through `install`; the streamed and global switches also stop
it;
- `install_streamed_eager_int8_gemm` engages behind the prefetcher and
skips:
    - a denoiser with no prefetcher;
    - a compiled denoiser;
    - a dense denoiser;
    - an already swapped denoiser;
    - a call with no device;
  - it swallows an install failure;
  - `int8_gemm_live` drops the new key;
  - the shared Q/K/V quant is exact only when every Linear is;
- an AST check that `video.py` calls it in the H3 streamed-uncompiled
branch and after the generic offload hooks.
- New GPU test: a ConvRot int8 Linear (torchao v1 and v2 configs) is
installed while its weight is on the host. After a `swap_tensors` onload
(what the prefetcher does) it takes the eager routes, bit-identical to
torchao's Linear, with no `rotq_h16`.
- `test_diffusion_int8_gemm.py` + `test_diffusion_stream_int8_gemm.py`
with CUDA tests on (`-o addopts=`):
  - G4: 188 passed (base 181).
- L4: 187 passed, 1 failed (base 180 passed, 1 failed). The L4 failure,
`test_no_compiled_variant_spills_to_local_memory`, fails the same way on
the base (Triton 3.8 spills on sm_89).
- The commit applies cleanly on #17617 alone, and
`test_diffusion_int8_gemm.py` + `test_diffusion_speed.py` pass there
(308 passed).

## Not covered

- Other video families that stream int8 Linears through the generic
placement (Wan, LTX, HunyuanVideo-1.5) are covered by the CPU wiring
tests only. No GPU render was run for them.
- A100-40 was not run. On sm_80 the route is the same as on L4: the
dense rotation kernel plus cuBLAS TN, because the Triton GEMM stays off
on sm_8x with Triton 3.8.
- Streamers that swap in new Parameters per call (H3-Image's pageable
`ModuleListStreamer`) are excluded by the prefetcher gate. Diffusers'
own onload without the prefetcher is excluded too.
- The shared Q/K/V quant change affects the resident `eager` speed tier
with strided attention, which now takes the dense kernel instead of
`rotq_h16`. That tier was not timed here.
- ROCm, MPS and Windows were not run. The install refuses ROCm and
non-CUDA devices.
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…n the streamed tier (#17618)

Stacked on #17593 (base branch `h3-exact-qk-rmsnorm-rope`). Retarget to
`main` once that merges.

## Summary

Two MiniMax-H3 / H3-Image denoiser changes, each with a kill switch.

1. **Per-row AdaLN modulation and gated residual without gathers,
bit-exact** (`UNSLOTH_H3_ROW_MOD=0` turns it off). The block forward
read its six AdaLN chunks per packed row with `index_select`, one `[seq,
hidden]` copy each, and ran every op as its own pass. Two Triton kernels
now read the AdaLN tables through the row index and keep eager's
fp32-op-then-round chain with explicit-rounding PTX. They engage per
(device, dtype, hidden) only after a bit-exact check and a timed probe;
anything else takes the stock math. The block forward is swapped only
when its class forward is the stock body statement for statement. On for
every tier unless the opt-in regional compile is on. New module
`video_minimax_h3_rowmod.py`.
2. **Int8 GEMM on the H3-Image streamed tier**
(`UNSLOTH_H3_IMAGE_INT8_GEMM_STREAMED=0` or
`UNSLOTH_DIFFUSION_INT8_GEMM_STREAMED=0` keeps the stock path). The
streamed tier only took the attention levers, so its int8 ConvRot
Linears ran the stock rotate + int8 Linear path while their block was on
the card. The speed installer now asks the int8 GEMM for its call-time
mode on the streamed tier (the mode the generic offloaded denoisers
already use): a Linear whose weight is on the card at call time runs the
fused-dequant GEMM the resident tiers run; anything else keeps the stock
path. This one is tolerance-level, not byte-identical to the stock
streamed path.

## Results

Steady-state 2048 px H3-Image renders, 6 steps, seed-matched noise,
measured as per-commit deltas on one integration branch:

| change | card | before | after | output |
|---|---|---|---|---|
| row modulation | RTX PRO 6000, int8 resident, denoise | 2.085 s | 2.01
s | byte-identical |
| row modulation | same, elementwise / copy kernels per render | 112 /
30 ms | 2 / 2 ms | |
| streamed int8 GEMM | L4, int8 streamed, s/img (denoise) | about 85 s
(73 s) | 22.95 to 24.4 s (16.1 to 16.2 s) | see below |
| streamed int8 GEMM | L4, 2720x1536 edit, first render | 184 to 194 s |
56 to 58 s | see below |

Accuracy of the streamed GEMM: LPIPS against a bf16 render is 0.087 to
0.095, in the same band as the resident int8 tier rendered on a
different card (0.072 to 0.088). Against the stock streamed path it is
0.08 to 0.15 (different rounding, not a regression).

The L4 "before" includes the per-call weight copy that #17613 removes;
with #17613 alone the L4 2048 denoise is about 34 s, and this change
takes it to about 14 to 16 s.

## Tests

- New `tests/test_h3_row_mod.py`: the bit-exact check, the stock-forward
match, the probe gating and the kill switch. On GPU: 8 passed on each of
an RTX PRO 6000, an L4 and an A100.
- `test_diffusion_minimax_h3_image_speed.py`: the streamed tier asks for
the call-time mode and the kill switches keep the stock path.
- CPU, this branch: `test_h3_row_mod.py`,
`test_diffusion_minimax_h3_image_speed.py`,
`test_diffusion_minimax_h3_image.py`, `test_video_minimax_h3_attn.py`,
`test_h3_qk_rope_exact.py`: 187 passed, 58 skipped (CUDA-only cases).

## Not covered

- MiniMax-H3 video was not rendered with real weights with the row
modulation on (the kernels are shared and checked per device).
- The streamed GEMM was timed on L4 only; T4 and A100 40GB streamed
tiers were not run.
- ROCm and Apple are untouched (both kernels are CUDA only and fall back
to the stock math).
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…d VAE canvas gates (#17681)

## Summary

Two checks fail on main (`7bf13f2`) and on every PR based on it. The
`(Python 3.13, a-f)` and `(Python 3.13, rest)` shards show them on
staging runs:

```
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_torchao_patches.py': [66], 'diffusion_vae_canvas.py': [296]}

studio/backend/tests/test_small_host_dense_denoiser.py::test_qkv_fusion_skips_a_mapped_denoiser[True]
core/inference/diffusion_small_host.py:863: in prepare_streamed_encoder_
E   ModuleNotFoundError: No module named 'diffusers'
```

Both reproduce locally on main (the second with `diffusers` blocked).

### ROCm gates (#17613, #17595)

The lint is right, and both reads are real bugs on AMD SDK / Radeon
wheels, which leave `torch.version.hip` unset and carry the ROCm tag
only in `torch.__version__`:

- #17613 gates the int8 GEMM's transposed-weight path with
`getattr(torch.version, "hip", None) is None`. On a tag-only ROCm wheel
that is true, so the cuBLASLt-only TN layout would be sent to hipBLASLt.
The comment above it says ROCm should keep the row-major copy.
- #17595's `diffusion_vae_canvas._is_rocm()` calls `is_rocm_torch()`
with no argument. That raises `TypeError`, which the `except` swallows.
The fallback then reads `torch.version.hip`, so every call took the raw
read, and a tag-only ROCm wheel got the NVIDIA tile-graph replica count.

### Mapped denoiser test (#17667)

`test_qkv_fusion_skips_a_mapped_denoiser[True]` maps the denoiser
through `prepare_streamed_encoder_`, which uses
`diffusers.hooks.apply_layerwise_casting`. The backend test shards do
not install `diffusers`. The bit-for-bit test in the same file already
guards on it with `pytest.importorskip("diffusers.hooks")`.

## Change

- `diffusion_torchao_patches.py`: `keep_transposed` now uses
`_is_rocm_torch(torch)`, a small helper that calls
`rocm_bf16.is_rocm_torch`.
- `unsloth/import_fixes.py`: `_make_safe_int_mm` must stay AST-identical
to the Studio copy (`test_studio_copy_matches_unsloth_import_fixes`). It
gets the same call, plus its own `_is_rocm_torch` with the same
tag-aware check, so whichever copy patches torchao first behaves the
same.
- `diffusion_vae_canvas._is_rocm()`: calls `is_rocm_torch(torch)`, with
no raw fallback.
- `test_small_host_dense_denoiser.py`: the mapped case calls
`pytest.importorskip("diffusers.hooks")`, like its sibling. The unmapped
case still runs everywhere.

## Guards

- `test_vae_canvas_graph_replicas_see_a_tag_only_rocm_wheel` and
`test_vae_canvas_rocm_check_does_not_fall_back_on_a_cuda_build` in
`test_diffusion_rocm_tag_detect.py`.
- `test_a_tag_only_rocm_wheel_keeps_the_row_major_copy` in
`test_torchao_int_mm_transposed.py`, next to the existing
`torch.version.hip` case.

## Testing

- `test_diffusion_rocm_tag_detect.py`,
`test_torchao_int_mm_transposed.py`,
`test_torchao_intmm_patch_wiring.py`,
`test_small_host_dense_denoiser.py`: 33 passed, 4 skipped (CUDA-only
cases).
- Sabotage: with main's three source files and these tests, 3 fail (the
lint, the VAE canvas tag-only case, the int8 tag-only case).
- With `diffusers` blocked: main's
`test_qkv_fusion_skips_a_mapped_denoiser[True]` fails with the CI error;
here it skips and `[False]` passes.
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.
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