Skip to content

Studio: give each rotated native int8 Linear its own ConvRot buffer (FLUX.3 INT8 on T4 failed its first render) - #17217

Merged
danielhanchen merged 2 commits into
mainfrom
studio-native-int8-rot-per-layer
Nov 9, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-native-int8-rot-per-layer

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

An explicit INT8 request for FLUX.3 klein on a T4 (and every other fp16-only Turing card) loads, then fails its first render:

RuntimeError: Expected all tensors to be on the same device, but got mat2 is on cpu, different from other tensors on cuda:0 (when checking argument in method wrapper_CUDA_mm)
  File "core/inference/diffusion_native_quant.py", in _rotate
    return (grouped @ self.rot_h.to(x.dtype)).reshape(x.shape)

Cause: a rotated native int8 Linear registers its ConvRot Hadamard as rot_h = build_convrot_hadamard(...).to(self.compute_dtype). The builder caches one float32 tensor per (size, device, dtype). On bf16 GPUs .to(bfloat16) makes a fresh copy per layer, but FLUX.3 on a fp16-only card computes in float32, so .to(float32) returns the cached tensor itself and every layer registers the same buffer. Group offload then re-points that one buffer with whichever offload group touched it last, so the next streamed layer finds rot_h on the host. The compiled W8A8 function hits the same mismatch first ("the compiled int8 W8A8 linear failed on cuda:0 (Tensor device mismatch)") and falls back to eager, which then raises.

Fix: each layer registers its own copy (h.to(dtype, copy=True), 256 KiB per layer at float32 for group 256). Nothing else changes: the rotation values, the codes and every other dtype path are identical, bf16 loads already got their own copy.

Kill switch: UNSLOTH_NATIVE_INT8_ROT=0 (existing) keeps native int8 layers unrotated, so no rotation buffer is registered at all.

Results (Kaggle T4, 31 GB host, FLUX.3 klein, 1024x1024, 16 steps, fresh process per arm, same VM, same seeds)

Base = main at the merge base dcb1eb1ec7, head = this branch. The baseline stack ran its int8 ConvRot file on the same VM.

arm first render s / image (2 renders) peak VRAM process tree PSS LPIPS vs Studio float32 dense
base, INT8 fails (device mismatch above) - - 22.3 GiB -
head, INT8 image 89.2 (89.1 / 89.4) 11.34 GiB 22.5 GiB 0.026 (max 0.051)
baseline stack, int8 ConvRot, 2 runs image 34.2 / 34.8 10.92 GiB 12.5 / 10.5 GiB 0.036 (max 0.049) vs its own float32 render

The same failure reproduced on every main INT8 load in this round (5 loads on 3 VMs). LPIPS is against Studio's float32 dense render of the same 2 prompts and seeds (transformer_quant=none, speed off; that reference is bit-identical across the VMs used, LPIPS 0.000). INT8 now runs, but it is still slower than the baseline stack on this card: float32 attention is most of the gap, which a follow-up PR takes on (float16 attention on fp16-only GPUs: 58.8 s on the same VM, LPIPS 0.006 vs this head).

Tests

studio/backend/tests/test_diffusion_native_int8_rot_per_layer.py (CPU):

  • Every rotated layer owns a distinct rot_h (never the cached tensor) for float32, float16 and bf16 compute, on both the quantise and the given-codes paths; values equal the cached Hadamard at the layer's dtype; still not in the state dict.
  • Re-pointing one layer's buffer (what group offload does) leaves the others alone, and the untouched layer still matches its dequantized weight.
  • The float32 aliasing itself is pinned (cached.to(float32) is cached).

The float32 cases fail on main and pass here. test_diffusion_native_quant.py, test_diffusion_native_quant_fused.py, test_diffusion_int8_runtime_convrot.py, test_diffusion_convrot.py, test_diffusion_fp16_card_int8.py pass unchanged, except test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data, which fails the same way on main in this environment (torchao build).

Not covered

  • Other Turing cards (RTX 20xx, Quadro RTX) take the same path but were not run.
  • The regression switchboard GPU units did not run (its batch notebook is over Kaggle's size cap); owed.

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

chatgpt-codex-connector Bot commented Nov 9, 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-09T07:26:35.399210Z cb30644 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. Nice work!

Reviewed commit: cb3064495b

ℹ️ 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 6511d95 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the studio-native-int8-rot-per-layer branch November 9, 2026 11:54
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 9, 2026
…er image GGUF, -34% INT8) (unslothai#17223)

## Summary

GPUs without bf16 (T4 and other Turing / Volta cards) run FLUX.3 in
float32, because its residual stream overflows float16. That includes
attention, which then runs on the float32 SIMT memory-efficient kernel
(`fmha_cutlassF_f32_aligned_32x128_rf_sm75`): 42.4 s of a 210 s Q4_K_M
render on a T4 in a torch profile, the second largest cost after the
float32 GEMMs. Attention cannot overflow float16 here, so this PR runs
it on the float16 tensor-core kernel instead:

- Q and K leave an RMSNorm (`norm_q` / `norm_k`, then RoPE, which keeps
each rotated pair's norm), so every entry is at most `sqrt(head_dim) *
max|norm weight|`. The patch reads that bound from the loaded weights
once at install and engages only when it is below 16384 (float16 max is
65504). FLUX.3 klein's largest norm weight is 6.81, a bound of 77.
- V is unbounded, so each (batch, head) slice is divided by a power of
two that puts its largest entry in [2^13, 2^14] (exact in float32)
before the cast, and the output, a convex combination of V rows, is
multiplied back in float32.
- Float16 keeps 10 mantissa bits; bf16 GPUs run this same attention at
7.

`diffusion_flux3_half_attn.py` wraps `dispatch_attention_fn` in
diffusers' `transformer_flux3` module (the same module-level patch
pattern as the FLUX.3 fused RoPE), registered as the autoopt load patch
`flux3_fp16_attn`. It engages only for a FLUX.3 transformer on an sm70 /
sm75 GPU, and each call still requires float32 CUDA inputs without
autograd and no mask (or a bool one); anything else calls stock. An
explicit speed `off` keeps stock float32 attention (exact); an unset
request that a dense load resolves to off still engages. bf16 GPUs,
16-bit loads, ROCm, MPS, CPU and every other family are unchanged.

Kill switch: `UNSLOTH_DIFFUSION_FLUX3_FP16_ATTN=0` (also
`UNSLOTH_DIFFUSION_PATCH_FLUX3_FP16_ATTN=0`).

## Results (Kaggle T4, FLUX.3 klein, 1024x1024, 16 steps, fresh process
per arm, same VM, same seeds)

Base = `main` at the merge base `dcb1eb1ec7`, head = this branch. Order
base, head, head, base.

| arm | s / image, run 1 | run 2 | attention kernel per render (profile)
| LPIPS |
|---|---|---|---|---|
| GGUF Q4_K_M, base | 226.7 (227.9 / 225.4) | 227.1 (228.9 / 225.3) |
44.6 s `fmha_cutlassF_f32` (Q8_0 profile on the same VM) | 0.068 vs
float32 dense |
| GGUF Q4_K_M, head | 193.7 (193.6 / 193.9) | 191.9 (192.9 / 190.8) |
12.4 s `fmha_cutlassF_f16_aligned_32x128_rf_sm75` | 0.0001 vs base (both
runs); 0.068 vs float32 dense |

15% faster per image. With the INT8 fix of unslothai#17217 applied on both arms
(another VM, base = unslothai#17217 alone): INT8 89.2 s -> 58.8 s per image,
LPIPS 0.006 vs the float32-attention render, 0.029 vs Studio's float32
dense render (0.026 before).

The float32 dense reference (`transformer_quant=none`, speed off) is
unchanged: an explicit off keeps stock attention.

## Tests

`studio/backend/tests/test_diffusion_flux3_half_attn.py`:
- The scaled float16 path matches a float64 reference to float16
rounding per head for V magnitudes 1e-6 to 1e7 (one head 1000x louder
than the rest), where a plain float16 cast overflows.
- CPU / 16-bit / masked calls run stock; the Q / K bound is read from
the RMSNorm weights (inf when a norm is missing or not RMSNorm).
- Install gating: engaged, idempotent, uninstall restores the symbol;
explicit off, a loud norm weight, another denoiser class, a GPU with
bf16, the kill switch and an unexpected symbol all stay stock. Only sm70
/ sm75 qualify.
- Registered as a load patch that passes `explicit_off`.
- diffusers' real `Flux3Transformer2DModel` (tiny config): every
attention call of a forward takes the float16 path, output within
float16 rounding of the float32 forward (diffusers 0.42.1 venv; skipped
where diffusers has no FLUX.3).

`test_diffusion_autoopt_core.py` (the fused-DiT group now lists the
patch) and `test_diffusion_autoopt_parity.py` (the legacy sequence calls
it like the other FLUX.3 patch; the fixture gains `"flux3_fp16_attn":
false` on the 640 image cases, and nothing else) pass.

## Not covered

- V100 (sm70) takes the same path but was not run.
- FLUX.3 klein-base and reference-image edits take the same path but
were not timed.
- The regression switchboard GPU units did not run (its batch notebook
is over Kaggle's size cap); owed.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 9, 2026
…he bf16 checkpoint as stored instead of widening the transformer to float32 (unslothai#17228)

## Summary

unslothai#17173 keeps FLUX.3's bf16 weights as stored on fp16-only GPUs (T4) and
upcasts per layer, but an explicit transformer quant still loads the
transformer widened to float32 first ("a transformer quant rebuilds the
dense Linears it reads"). For the fp16-only card's native build (INT8
from unslothai#17167, FP8 from unslothai#17218) that widened copy is not needed: the
native linear reads `weight.float()` anyway, and widening bf16 to
float32 is exact, so the codes are the same either way. The widened load
costs host RAM on the 31 GB Kaggle T4 VM, where a Studio INT8 load
already sits at 23 GiB PSS.

This PR loads the transformer at bf16 with the manual cast when the
requested scheme takes the fp16-only card's native route, and lets that
build read manual-cast Linears:

- `load_flux3_pipeline(..., transformer_storage=...)` is also true for a
native scheme on an `fp16_card_int8_host` that is not the shared ROCm /
MPS native route (`native_quant_scheme(...) is None`) and not the native
offload build.
- `make_filter_fn(require_dtype=...)` counts a manual-cast Linear by its
compute dtype (`linear_compute_dtype`: `_unsloth_compute_dtype`, else
the weight dtype), so the float32 filter of the fp16-card path still
selects them.
- The native linear takes its compute dtype from that attribute too, and
holds a manual-cast source's bf16 bias at the compute dtype (`F.linear`
needs one dtype).
- Everything the quant skips (the M=1 modulation projections, small
layers) stays a bf16 manual-cast Linear instead of a float32 copy.

bf16 GPUs, explicit-quant loads elsewhere, ROCm / MPS native routes and
the native offload build are unchanged. Kill switch:
`UNSLOTH_DIFFUSION_FP16_CARD_QUANT_STORAGE=0` restores the widened load.

## Results (Kaggle T4, 31 GB host, FLUX.3 klein, 1024x1024, 16 steps,
fresh process per arm, one process on the VM, same seeds)

Both arms carry unslothai#17217 (INT8 renders), unslothai#17218 (FP8 on Turing) and the
other T4 FLUX.3 PRs of this round; head adds this PR. Order head-less,
head, head, head-less.

| format | arm | s / image (2 runs) | load s | process tree PSS | min
MemAvailable | peak VRAM | LPIPS |
|---|---|---|---|---|---|---|---|
| INT8 | widened (today) | 52.8 / 52.9 | 145.7 / 143.6 | 23.1 / 23.0 GiB
| 8.0 / 8.0 GiB | 11.34 GiB | - |
| INT8 | head (stored bf16) | 53.1 / 53.2 | 136.0 / 133.7 | 20.9 / 21.2
GiB | 12.9 / 12.9 GiB | 11.20 GiB | 0.000 vs widened (pixel-identical),
both runs |
| FP8 | widened (today) | 185.2 | 121.9 | 22.0 GiB | 8.3 GiB | 11.05 GiB
| - |
| FP8 | head (stored bf16) | 185.8 | 113.9 | 21.1 GiB | 12.7 GiB | 11.19
GiB | 0.000 vs widened (pixel-identical) |

Same images and the same speed; 0.9 to 2.2 GiB less process PSS, 4.4 to
4.9 GiB more host memory left free at the low point of the load, and an
8 to 10 s shorter load.

## Tests

`studio/backend/tests/test_diffusion_fp16_card_quant_storage.py` (tiny
diffusers `Flux3Transformer2DModel`, Turing capability monkeypatched):
- INT8 (and FP8 where unslothai#17218 is present) built from the manual-cast bf16
transformer gives the same native layers as the widened float32 load:
same layer set, compute dtype float32, `torch.equal` codes, scales and
biases; the rest stay bf16 manual-cast Linears; the forward output is
`torch.equal` to the widened model's.
- The filter counts a manual-cast Linear by its compute dtype; a plain
bf16 Linear is still rejected by the float32 filter.
- The loader gate is the fp16-card native route only; the kill switch
and its name.

The INT8 case fails on `main` (no layer passes the float32 filter). The
fp16-card INT8, FLUX.3 manual cast, native quant, fused native quant and
FLUX.3 suites pass unchanged (407 passed, diffusers 0.42.1).

## Not covered

- Without unslothai#17217, INT8 still fails its first render on a T4 (separate
fix); without unslothai#17218, FP8 is still refused there.
- Other Turing cards were not run.
- The regression switchboard GPU units did not run (its batch notebook
is over Kaggle's size cap); owed.
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