Repository navigation
Studio int8 video DiTs: fused rotation + quant, native-epilogue GEMM and fused residual / GELU when compiled - #17680
Conversation
… scale and reciprocal) The fused ConvRot rotation + act quant kernel only reproduced torchao's v1 / v2 activation quant. NATIVE adds the native W8A8 Linear's own maths (_int_mm_rows): fp32 s = max(amax, 1e-12) / 127, fp32 1 / s, fp32 product, rint, clamp to +-127, fp32 scales. v1 / v2 launches are unchanged.
…Rot Linears An offloaded int8 video DiT (LTX-2.5 on a 24 GB card, Wan, HunyuanVideo-1.5) is read as NativeWeightOnlyLinear. Compiled, each Linear ran a bf16 rotation GEMM, an amax pass and a quantise pass over [rows, K] before cuBLAS _int_mm, and Q / K / V each repeated all three on the same input. diffusion_native_w8a8_cuda runs the rotq_i8 kernel in its native mode as an opaque custom op instead, probed per card to give the Linear's own codes and scales bit for bit (a miss keeps the stock maths). The int8 GEMM and the fp32 epilogue are the Linear's own. Only traced forwards take it, so an uncompiled denoiser is unchanged. diffusion_speed probes the denoiser's card before the compile. UNSLOTH_NATIVE_INT8_ROTQ=0 keeps the stock rotation + quant.
…A scalar divide does ATen's CUDA div by a scalar divisor computes x * (1 / divisor) in fp32, so _int_mm_rows' clamp_(min=1e-12).div_(127.0) is amax * fp32(1/127), not an IEEE divide. With the divide the L4 probe refused the kernel; with the multiply codes and scales match the eager rotation + quant on every probe shape (A100).
Inductor keeps three calls of the opaque rotation + act quant op on the same input (no CSE across custom ops). A post-grad pass merges calls on one root tensor with the same view shape and group into the first; the op is pure, so the merged Linears read the same codes and scales. Installed only when the fused route engages and the Inductor slot is free. On an L4, a synthetic LTX-2.5-shaped block (14080 rows) goes from 6 to 4 quant calls and from 74.8 ms (stock) to 64.9 ms. UNSLOTH_NATIVE_INT8_ROTQ_SHARE=0 keeps one per Linear.
After the fused act quant, a native Linear still ran cuBLAS _int_mm and wrote an int32 [rows, N] that the consumer read back to apply x_scale, w_scale and the bias. i8mm_dq gets a NATIVE epilogue with the Linear's own maths (fp32 acc * xs * ws, + fp32 bias, one bf16 round) and a native_cuda_i8mm custom op runs it wherever Studio's fused-dequant GEMM has a probed tile on the card (the int8 GEMM gate decides; sm8x on Triton >= 3.8 needs the 8-bit prefetch fix). Probed bit for bit against the eager epilogue, else cuBLAS stays. UNSLOTH_NATIVE_INT8_GEMM=0 keeps cuBLAS _int_mm + the traced epilogue.
…used quant, the gated residual into the native GEMM epilogue On the fused-dequant GEMM route (PR 17669's Triton int8 GEMM, now probed on the native epilogue alone so cards whose torchao tie probe misses still take it), an Inductor post-grad pass re-points: - a quant of a tanh GELU at a quant with the GELU in its prologue, - a quant of RMSNorm(x) * (1 + scale) + shift (used by nothing else) at one with the norm and modulation in front, - residual + linear(x) * gate at the GEMM with the gated residual in its epilogue. The native bias epilogue now uses one FMA, as addcmul does on CUDA. Each fold is probed per card and has its own switch: UNSLOTH_NATIVE_INT8_FUSE_GELU / _NORM / _RESIDUAL=0.
…rologue opt-in In front of the quant the GELU cost more than the pass it saved on an L4 (+0.7 ms per LTX-2.5 block at 3520 rows, +2.8 ms at 14080), so a GELU whose input is only a native GEMM's output now runs in that GEMM's epilogue instead (bit-identical to the GEMM then Inductor's decomposition). The RMSNorm + AdaLN prologue measured no faster and stays behind UNSLOTH_NATIVE_INT8_FUSE_NORM=1.
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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a70d92ae9f
ℹ️ 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 transformer is None or disabled(): | ||
| return 0 |
There was a problem hiding this comment.
Clear active routing when a reload disables the native kernels
If a model has already enabled this route, setting UNSLOTH_NATIVE_INT8_ROTQ=0 (or either master switch) and loading another model in the same process returns here without clearing _STATE["on"] or the GEMM state. The new Linear's _cuda_rotq_on() checks enabled_for(), which only reads that cached state, so its compiled forward still runs the supposedly disabled kernels. This defeats the advertised per-load kill switch precisely when disabling a problematic optimization. Keep probe results cached, but update the active routing state when installing a model with the switches off.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6b670ed. Each native W8A8 Linear now records this load's switches when it is built, and install() refreshes them on the denoiser it installs, so routing is per load while the per-card probe results stay cached. A model already loaded in the process keeps its own setting. The new test arms the route from an earlier load, then builds a Linear with UNSLOTH_NATIVE_INT8_ROTQ=0 (no route) or UNSLOTH_NATIVE_INT8_GEMM=0 (fused quant, cuBLAS GEMM), and checks that a reload with the switch back on re-arms it.
…r inherits the route [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…nd norm folds fold_residuals and fold_norms called int() on the token count (and K) of the traced graph. Under a dynamic=True compile (Wan, HunyuanVideo-1.5 and other non-LTX DiTs on torch 2.14) that count is symbolic, so int() added a shape guard and every new token count recompiled the block where the stock graph compiles once. Skip both folds when the count is symbolic; static compiles (LTX-2.x) fold as before and the GELU fold, which needs no count, still folds. Test: the folds on a symbolically traced block add no guards (norm and residual keep the traced maths, the GELU still folds). [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
## Summary Follow-up to #17680. The native W8A8 post-grad pass folds `residual + linear(x) * gate` into the GEMM epilogue, but its matcher read only the two positional operands of `aten.add.Tensor` and ignored the keyword-only `alpha`. A graph such as `torch.add(residual, y * gate, alpha=2)` (which is `residual + 2 * y * gate`) was folded into `residual + y * gate`, a silent wrong result. The GELU and norm folds had the same gap on the adds they match (`1 + tanh(...)`, `a + 0.044715 * a^3`, `1 + scale`, `n * (1 + scale) + shift`, `mean + eps`). ## Changes - `_fn` (the target check every matcher uses) now rejects an add whose `alpha` is not exactly 1. Every fold rebuilds the unit-coefficient add, so a scaled add simply stays as traced. - The norm fold also refuses an `aten.mean.dim` carrying a non-fp32 `dtype`, since the prologue always computes the fp32 statistic. - The pass uuid moves from `share.v2` to `share.v3`, so any FX graph folded before this check misses the cache instead of being reused. The default LTX-2.5 style graphs have no `alpha` kwarg on these adds, so they fold exactly as before (the existing fold tests are unchanged and pass). The check is compile-time only: it runs while Inductor rewrites the graph and adds no per-call host work. ## Tests `studio/backend/tests/test_diffusion_native_w8a8_cuda.py`: - `test_folds_refuse_a_scaled_add`: for every matched add in the three folds and `alpha` in (2, -1, 0.5), the fold returns 0 and the graph output equals the scaled eager result bit for bit; `alpha=1` still folds. - `test_norm_fold_refuses_a_low_precision_mean` and `test_pass_uuid_names_the_alpha_aware_folds`. | Arm | Result | |---|---| | `origin/main` | 36 passed, 20 failed (all 20 are the new tests) | | this branch | 56 passed | A standalone repro that installs the real pass in `post_grad_custom_pre_pass` and runs `torch.compile(fullgraph=True)` on CPU gave 5 instead of 9 on main for `alpha=2`; on this branch it gives 9 with 0 folds. No GPU run: default inputs take the same folds as before, so the GPU path is unchanged.
…uns without a bias (#18804) LTX-2.x's text connectors replace prompt padding with learned registers and return an all-ones attention mask. The DiT turns that mask into an additive bias of zeros (`(1 - mask) * -10000`) and passes it to both text cross-attentions in every block. Adding zero changes nothing, but any `attn_mask` keeps SDPA off the flash kernel and on the mem-efficient one. Under `torch.compile`, Inductor also materialises the bias at `[batch, heads, video tokens, text tokens]`, which is about 0.9 GB of bf16 zeros written and read on every block at 1280x704x121. On the L4 profile of Studio's LTX-2.5 defaults this showed up as `fmha_cutlassF_bf16_aligned_64x128` (1.75 s per profiled render, one call per block) plus a fused norm + `clone_expand` kernel that writes the bias (0.73 s). ## Change - `video_ltx2.install_ltx2_full_mask_drop(pipe)` registers a forward pre-hook on every `LTX2VideoTransformer3DModel` in the pipe. When `encoder_attention_mask` / `audio_encoder_attention_mask` is a 2-D mask equal to 1 everywhere, the hook passes `None` in its place. The maths is the same, and SDPA can now pick flash. - A padded mask, a 3-D bias, or a positional argument is passed through unchanged. The all-ones check is memoised per tensor and version, so there is one host read per render rather than one per step. If the check raises (for example during a capture), the mask it was checking is kept. - `video.py` installs it next to the HunyuanVideo-1.5 padded-text trim, on every speed tier except `off`, and reports `ltx2_full_mask_drop` in `speed_optims`. `UNSLOTH_LTX2_DROP_FULL_TEXT_MASK=0` turns it off. The output is not bit-identical to main: flash and mem-efficient attention round differently. This is the same trade the HunyuanVideo-1.5 trim already makes. ## Tests New `tests/test_video_ltx2_full_mask.py` (CPU, a tiny real `LTX2VideoTransformer3DModel`): - `test_all_ones_mask_is_dropped_and_the_output_is_unchanged`: the stock forward passes a bias to SDPA, while the hooked forward passes none, drops both masks, and gives the same output (allclose 1e-5). - `test_padded_mask_is_kept`: a padded mask still reaches SDPA and the output is bit-identical. - Also covered: bool, float and int masks, batches, and a 3-D bias; memoisation per tensor and version; the kill switch and non-LTX DiTs; idempotent install; and a failing check leaving the call unchanged. Added to `tests/test_video_backend.py`: `test_ltx2_full_mask_drop_installed_and_reported` (eager / default / max) fails on main and passes here. `test_ltx2_full_mask_drop_skipped_on_the_off_tier` passes on both. `test_differential.py`: DISCRIMINATING, fixed=3, head_fail=0, 547 unchanged. `tests/test_video_backend.py`, `test_video_ltx25.py`, `test_video_ltx2_prequant.py`, `test_diffusion_attention_trim.py`: 758 passed, 2 skipped. ## GPU results (Colab L4, LTX-2.5 Studio defaults, 1280x704x121, 8 + 3 distilled steps, INT8 DiT streamed) One VM, one fresh process per arm, in the order main, branch, branch, main, main, branch. Each arm runs a cold render and then two timed renders (seeds 11 and 12). The first arm of each tree starts with an empty home, and later arms reuse that tree's compile cache. | | main | this branch | |---|---|---| | Denoise, second render (3 arms) | 44.10 s (44.02 to 44.20) | 42.44 s (42.36 to 42.49) | | Denoise, all six renders, median | 44.49 s | 42.80 s | | Stage-1 step, median | 1.993 s | 1.955 s | | Render wall, median | 56.10 s | 55.13 s | | Cold render (first after load) | 173.5 / 185.9 / 174.3 s | 175.4 / 179.0 / 179.6 s | | peak_alloc_gib | 19.009 | 19.009 | The steady denoise is 1.66 s per clip faster (3.8%). The main-vs-main spread is 0.18 s and the two ranges do not overlap. Peak allocation is set elsewhere in the render and does not change. The cold render is a tie. Profile of one render (2 stage-1 + 3 stage-2 steps): - **Mem-efficient attention calls:** 248 on main, 8 here. The 8 that remain are the connectors' own, which run once per prompt. - **Bias kernel:** the `clone_expand` kernel that writes the bias (240 calls, 0.6 s) is gone. - **Denoise time:** attention kernel time drops from 11.00 to 9.28 s, and the denoise span from 32.98 to 31.34 s. - **Kernel count:** 24686 kernels on main, 24420 here. - **GPU busy:** 98.4% of the denoise on both, so the step is not launch-bound. **Accuracy.** Every main arm gives the same frames (md5 equal across all three), and so does every branch arm. Main vs branch: LPIPS 0.114 / 0.052 and PSNR 20.8 / 32.8 dB on the two clips. That is the same size of change #17680 produced (0.117 / 0.056), which is how strongly this distilled sampler amplifies one-ulp differences. The maths is unchanged: the bias that is removed is all zeros. **Accuracy against a higher-precision reference.** I added a third arm on its own L4 VM: main with every attention call run on fp32 q/k/v (fp32 mem-efficient kernel, the mask kept as main passes it, output cast back). Fresh process per arm, order ref / main / branch / ref, same prompts, seeds and shape. LPIPS (alex) and PSNR over all saved frames: | Pair | clip 1 LPIPS / PSNR | clip 2 LPIPS / PSNR | |---|---|---| | main vs fp32 ref | 0.1059 / 21.46 dB | 0.0661 / 31.18 dB | | this branch vs fp32 ref | 0.1055 / 21.47 dB | 0.0609 / 31.43 dB | | main vs this branch | 0.1140 / 20.79 dB | 0.0524 / 32.78 dB | | ref vs ref (fresh process) | 0.0 (identical) | 0.0 (identical) | The branch is no further from the fp32-attention reference than main on either clip, and slightly closer on both. ## Not proven here - LTX-2.0 / LTX-2.3 renders were not run on a GPU. They do take this change: the text connectors return an all-ones mask for every LTX-2.x config Studio loads (all ship 128 registers, and the connector's final `< 1e-6` binarisation maps padded positions to 1 as well), so the bias is dropped there too. A padded mask from any other caller is kept (`test_padded_mask_is_kept`). - With the opt-in INT8, Sage or FlashAttention 4 attention, or ROCm flash attention, the text cross-attentions no longer take the masked native route. They now go to the selected kernel (on ROCm auto, through the timed per-length gate) like every other call. This was not measured here. - An explicit FlashAttention 2 / 3 pick on NVIDIA, which diffusers refuses for a masked call, should now get past the text cross-attentions. This was not run.
Summary
Offloaded int8 video DiTs (LTX-2.5 at Studio's defaults on a 24 GB card, and the other families read as native int8 Linears) spent a large part of every compiled denoise step around their int8 GEMMs: a bf16 rotation GEMM, an fp32 amax and quantise pass, cuBLAS
_int_mmwith an int32 output, then Inductor kernels that dequantise, add the gated residual and apply the GELU. Q, K and V repeated the quant on the same input.This PR (built on #17669, now merged, which makes the Triton int8 GEMM usable on sm_8x again) runs, for those Linears in a compiled forward:
acc * x_scale * w_scale + bias, bf16 out), bit-identical to the cuBLAS path in eager;residual + out * gate) and the MLP's tanh GELU inside that GEMM's epilogue.Results
LTX-2.5 INT8 at Studio's defaults (1280x704x121, distilled two-stage, 8 + 3 steps), one Colab L4 VM, one process per arm, 2 clips per arm. Base is #17669's head (the measurement predates its merge; this branch is the same change replayed onto main); K is head with
UNSLOTH_NATIVE_INT8_ROTQ=0.Profiled render (2 denoise steps, all kernels, same VM):
Frames against a bf16 render of the same prompts (A100-40 with a 16 GiB budget, so the int8 DiT streams as native Linears and takes this route; LPIPS, lower is closer):
Cause
NativeWeightOnlyLinear(W8A8, ConvRot group 256), with the blocks streamed and compiled below their offload hooks. The torchao int8 GEMM swap never sees these Linears._rotate(a[rows * K/256, 256] @ [256, 256]bf16 matmul) and_int_mm_rows(amax, scale, reciprocal, round, clamp), then_int_mminto an int32[rows, N]buffer that the next Inductor kernel read back to dequantise.Change
diffusion_convrot_quant.rotq_i8gets anativemode that reproduces_int_mm_rowsexactly: scalemax(amax, 1e-12) * fp32(1/127)(ATen's CUDA divide by a scalar multiplies by the fp32 reciprocal), fp32 reciprocal and product, round half to even, clamp to +-127.diffusion_native_w8a8_cuda: opaque custom ops around that kernel and around Studio: skip Triton's sm_8x prefetch pass for 8-bit dots and run the int8 GEMM on A100 / L4 again #17669's GEMM with the native epilogue, each probed once per card against the eager maths (codes, scales and outputs must be equal on ragged rows, a zero row, outliers, K from 768 to 32768, and the bf16 tie operands).NativeWeightOnlyLinear.forwardtakes them only inside a compiled forward, for bf16 CUDA activations on a probed card. An uncompiled denoiser does not change.arch_config), so sm_8x takes it only with Studio: skip Triton's sm_8x prefetch pass for 8-bit dots and run the int8 GEMM on A100 / L4 again #17669's Triton prefetch fix installed.addcmuldoes on CUDA (a separate multiply and add differed from cuBLAS +addcmulin about 1 output in 50,000).ShareRotqPass), installed only when the route engages and the slot is free:residual + linear(x) * gate(gate per batch or per token) at the GEMM with the residual in its epilogue (fma(bf16(out), gate, residual), one bf16 round);UNSLOTH_NATIVE_INT8_FUSE_NORM=1opts in). A tanh GELU prologue in the quant was slower than the separate kernel and was dropped for the GEMM epilogue.diffusion_speed._compile_repeated_blocksprobes the denoiser's card before the compile traces the blocks (resident and streamed blocks alike).UNSLOTH_NATIVE_INT8_ROTQ=0: everything here off, stock rotation GEMM + quant + cuBLAS (also underUNSLOTH_DIFFUSION_INT8_ROTQUANT=0/UNSLOTH_DIFFUSION_INT8_GEMM=0);UNSLOTH_NATIVE_INT8_GEMM=0: keep cuBLAS_int_mmand the traced epilogue (the folds need the GEMM);UNSLOTH_NATIVE_INT8_ROTQ_SHARE=0: one quant per Linear;UNSLOTH_NATIVE_INT8_FUSE_RESIDUAL=0,UNSLOTH_NATIVE_INT8_FUSE_GELU=0: keep those ops in Inductor.Numerics
The fused quant and the GEMM equal the Linear's eager maths bit for bit. Inductor's compiled version of the same maths does not (on an L4 about 1 code in 13,000 differs from eager), so frames differ from base while staying as close to the eager maths as base is. The residual epilogue reads the gate as the bf16 tensor eager computes; Inductor keeps it in fp32 when it fuses
table + tembinto the residual kernel, so that fold moves values by at most a bf16 step of the gate. Frame scores against a bf16 render are above.Tests
studio/backend/tests/test_diffusion_native_w8a8_cuda.py, 31 CPU tests: the references equal the Linear's own rotation + quant and epilogue, the routed forward equals the stock traced maths, the forward gate (compiled only, bf16, CUDA, probed card, no input grad, row floor, group and K), every kill switch and default, install and probe placement, the share pass, the three folds on a decomposed LTX-2.5 style graph (match, per-token modulation, replaced ops leave the graph, other users and missing probes keep the stock graph, output within int8 noise), the GEMM probe without the torchao route, and the kernel flags. All 31 fail on the base tree and pass on head.test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data; two errors intest_video_native_quant_on_device.py).test_diffusion_native_w8a8_cuda.py31 passed; withtest_diffusion_int8_gemm.pyin the same run 205 passed, and the 4 failures are the same 4 that main itself fails on a B200 (test_no_compiled_variant_spills_to_local_memory, the two rotquant switch tests,test_failed_shape_tile_probe_keeps_its_shapes_on_the_default).Not proven