Skip to content

Studio int8: fused MLPs and v2 Linears quantize their input with the probed one-pass kernel - #17114

Merged
danielhanchen merged 3 commits into
mainfrom
studio/int8-mlp-fast-act-quant
Nov 8, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio/int8-mlp-fast-act-quant

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

diffusion_int8_fused.py already has a one-pass Triton per-row activation quant (_fast_act_quant, the opaque op unsloth_studio::int8_act_quant_rows). It is used on a card only after _act_quant_device_ok has shown it to be bit-identical to torchao's quant on that card and torchao build. int8_linear_core and the rotated path use it. Four call sites still call torchao's multi-op quant directly:

  • _ff_forward (GELU feed-forward: FLUX, SD3.5, Qwen-Image style blocks)
  • _flux_single_forward (FLUX single-stream proj_mlp)
  • _swiglu_forward (unrotated SwiGLU in-projection)
  • diffusion_int8_gemm._act_quant_v2 (every unrotated torchao v2 Linear on the fused-dequant GEMM path)

All four only run on _plain_int8_weight weights: dynamic, symmetric, per-row, with no static scale or zero point. Those are the weights _fast_act_quant covers, so this PR routes the four sites through it via _mlp_act_quant. On a card whose probe failed, or that was never probed, _fast_act_quant still falls back to torchao's quant, so nothing changes there. UNSLOTH_DIFFUSION_INT8_MLP_FAST_ACT_QUANT=0, read at install as a module global so traced forwards never read os.environ, restores torchao's quant at these sites.

Evidence (Kaggle T4, torch 2.11.0+cu130, Triton 3.6.0, torchao 0.17.0, which is Studio's pin for torch 2.11; base = main at 6244269)

The probe passes on the T4. Each row below is 3 interleaved base / head process reps.

Activation quant at the MLP call site (bf16 input, torchao Int8DynamicActivationInt8WeightConfig(version=2) weight):

rows x K base (torchao quant) ms this PR ms int8 codes + scales
4096 x 3072 2.26 / 2.32 / 2.36 0.313 / 0.313 / 0.313 bitwise equal (all reps, also vs the kill switch)
8192 x 3072 3.07 / 3.08 / 3.11 0.299 / 0.299 / 0.301 bitwise equal
1024 x 12288 1.54 / 1.56 / 1.57 0.216 / 0.216 / 0.216 bitwise equal

LayerNorm, then the input quant, then _int_mm, then torchao's epilogue (the shape of _ff_forward's first projection) into 3072 outputs, under inference_mode:

rows x K base eager ms this PR eager ms this PR torch.compile ms
4096 x 3072 10.67 / 11.41 / 11.56 8.57 / 8.77 / 8.78 4.09 / 4.22 / 4.50 (bitwise equal to its eager)
1024 x 12288 11.41 / 11.63 / 11.96 10.01 / 10.04 / 10.12 2.45 / 2.47 / 3.56 (bitwise equal to its eager)

Base under torch.compile in the same harness raised InternalTorchDynamoError: AttributeError: 'Int8Tensor' object has no attribute 'zero_point' while tracing torchao's quant on this torch / torchao pair. So there is no compiled base number here: the opaque op compiles where the inline torchao quant did not.

New CPU tests in tests/test_diffusion_int8_fused.py: an AST check that the three forwards and _act_quant_v2 call _mlp_act_quant and not _act_quant, plus the kill switch round trip. The file passes 81, with 178 skipped (the skips need CUDA).

Not measured: a compiled base-vs-head A/B on a torch / torchao pair where the base trace compiles (torch 2.12 + torchao 0.18), end-to-end denoiser step time, and sm80+ cards.

@danielhanchen danielhanchen self-assigned this Nov 8, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 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-08T05:10:27.131552Z 813b548 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 813b548a42

ℹ️ 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 86a41b0 into main Nov 8, 2026
@danielhanchen
danielhanchen deleted the studio/int8-mlp-fast-act-quant branch November 8, 2026 21:26
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant