Skip to content

Studio: run an explicit int8 under offload on NVIDIA as torchao-free W8A8 - #11712

Merged
danielhanchen merged 37 commits into
mainfrom
studio-native-int8-offload
Sep 25, 2026
Merged

danielhanchen merged 37 commits into
mainfrom
studio-native-int8-offload

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Stacked on #11631 (base studio-amd-weight-only-quant). It adds three things: the opt-in W8A8 torch._int_mm path for native int8 linears, a ConvRot group-256 Hadamard rotation for that path, and a NVIDIA route that uses it when an explicit int8 request would otherwise be refused because the load offloads.

Why

On NVIDIA an explicit int8 with balanced / low_vram / cpu_offload is refused today. torchao's tensor subclasses do not survive the offload hooks, so users who need offload never get int8. The native linears from #11631 are plain buffers and move with the hooks, so they can run under offload. With activations quantised as well (W8A8 through torch._int_mm), they are faster than bf16 there, not just smaller.

What changes

  • diffusion_native_quant.py:
    • W8A8 forward: per-row activation quantisation plus torch._int_mm, with a per-call fallback to the bf16 weight path when the shape is not eligible (M < 17, or K / N not divisible by 8).
    • ConvRot: the weight is stored already rotated by an orthogonal group-256 Hadamard, and the activation is rotated online, so outlier channels no longer pin the activation scale. dequantized_weight undoes the rotation, so LoRA baking and export see the real weight.
    • native_quant_signature / native_quant_reason report what was actually built.
  • diffusion_transformer_quant.py: native_quant_scheme(..., offload=) returns int8 on an NVIDIA bf16 host (sm_80+) only when the final plan still offloads. native_int8_act defaults W8A8 on for that route.
  • diffusion.py / video.py:
    • The preflight admits int8 on NVIDIA when the memory request forces offload.
    • The loader picks the native route only after the plan is final. A plan that comes out resident keeps torchao exactly as before.
    • Both experts of a dual-DiT video family get the same treatment.
  • diffusion_compile_cache.py: native layers key their own bundle (int8-w8a8-rot256), so they never share one with torchao int8.

Behaviour

Host Memory Scheme Path
NVIDIA bf16 offload (balanced / low_vram / cpu_offload, or a measured plan that still offloads) int8 native W8A8 + ConvRot (new)
NVIDIA bf16 offload fp8 / nvfp4 / mxfp8 refused, unchanged
NVIDIA bf16 offload auto stays bf16, unchanged
NVIDIA resident (fast, or auto that fits) any torchao, unchanged
NVIDIA any int8 on GGUF / single_file refused, unchanged
ROCm any int8 / fp8 native weight-only as in #11631; W8A8 only with UNSLOTH_NATIVE_INT8_ACT=1

Switches: UNSLOTH_NATIVE_INT8_ACT=0 turns the NVIDIA route into weight-only native. UNSLOTH_NATIVE_INT8_ROT=0 drops the rotation.

Measurements

Qwen-Image-2.1, 1024x1024, 20 steps, one idle B200. Seconds per image, where image 0 includes the compile:

Arm Memory Offload policy Per-image s
int8 (new) balanced group 41.4, 6.2, 5.7, 5.5
bf16 balanced group 30.5, 8.8, 7.7, 7.6
int8 (new) low_vram model 42.2, 30.6, 24.3, 24.3
bf16 low_vram model 44.3, 36.1, 33.5, 35.6
int8 (new), no compile balanced group 8.0, 6.3, 6.1, 6.0
  • Steady state is about 1.4x faster than bf16 under both offload modes.
  • On Qwen-Image-2.1, eager W8A8 already beats compiled bf16, so this route does not force a compile. That holds for large, transfer-bound models only (see Z-Image below).
  • LPIPS vs the bf16 images is 0.004 to 0.019 per image.
  • The log reads int8 W8A8 torch._int_mm ConvRot g256 (torchao-free) on 224 linears.

Z-Image-Turbo (6B), 1024x1024, 8 steps, balanced (group offload), one B200 shared with other jobs. Steady-state median seconds per image; compiled arms exclude the first three images (compile and warm-up), eager arms exclude the first. Two alternating runs per arm:

Arm speed_mode Steady s/image Peak GPU alloc
bf16 default (compiled) 2.84, 2.89 10.24 GiB
int8 W8A8 + ConvRot (new) default (compiled) 2.00, 1.53 10.24 GiB
bf16 off (eager) 3.35, 2.98 10.12 GiB
int8 W8A8 + ConvRot (new) off (eager) 3.45, 3.46 10.12 GiB
  • Compiled, int8 is 1.4x to 1.9x faster than bf16, in line with Qwen-Image.
  • Eager, int8 is 3 to 16% slower than bf16 on this smaller model: on B200 an eager W8A8 linear costs about 3x a bf16 one, so the win comes from moving half the bytes, which only dominates on larger models.
  • PSNR vs the bf16 images: 21 to 30 dB; the prompts render the same content, sign text included.
  • Under low_vram (model offload), int8 cut the peak from 12.07 GiB to 7.77 GiB.

On AMD gfx1151, W8A8 + ConvRot stays opt-in. Eager W8A8 gave no speed gain over weight-only there, and Studio does not compile on ROCm. It did score better LPIPS than weight-only on the prompts tested.

Tests

  • New truth-table, env-switch, shape-gate, rotation and loader tests for image and video, including dual-DiT.
  • Two video tests that asserted the int8 offload refusal now assert it with fp8, which is still refused.
  • test_diffusion_native_quant.py, test_diffusion_backend.py, test_video_backend.py, test_diffusion_compile_cache.py: 1019 passed.
  • A full studio/backend/tests run shows the same failures as the base branch. The one extra failure is a timing test in the streaming stripper that passes in isolation on both.

Not covered

  • Video was not run on a real GPU; it is covered by the unit and loader tests only.
  • LoRA baked onto native layers under offload was checked on a small model only, where it matched resident exactly.
  • Load is slower (about 30 to 60 s vs 8 to 21 s for bf16), because the conversion runs on the CPU.

Before / after in Studio

Z-Image-Turbo loaded from the Images page with Precision INT8 and Memory Balanced, on an NVIDIA B200. Before (parent branch) the load is refused: "transformer_quant='int8' could not be used: 'balanced' memory places the transformer under CPU offload, and torchao quantised tensors cannot be moved by the offload hooks", and no model is loaded. After, the model loads under group offload and the resolved precision reads "W8A8: int8 weights and activations through torch._int_mm with a g256 ConvRot rotation".

Before: INT8 + Balanced refused, no model loaded. After: Z-Image-Turbo loaded as int8 W8A8 under group offload

ROCm hosts and the Windows-ROCm torchao stub refused an explicit transformer_quant of
int8 or fp8 before load, because dense_transformer_supported() is False there. On
gfx1151 an int8 weight-only transformer measured 0.97x bf16 speed at half the weight
memory, while torchao's W8A8 ran at 0.48x and fp8 _scaled_mm is refused, so the AMD
path is weight-only with bf16 arithmetic and no torchao at all (torchao cannot import
on Windows ROCm).

- New diffusion_native_quant: NativeWeightOnlyLinear keeps int8 (per-row absmax/127)
  or fp8 e4m3fn (per-row absmax/448) weights and an fp32 per-row scale as plain
  buffers and dequantises per forward. Swapped one layer at a time so the build peak
  stays near the dense model.
- native_quant_host / native_quant_scheme: explicit int8 / fp8 on a bf16 ROCm or
  torchao-stub GPU, family deny list applied. auto stays bf16. The shared selector is
  unchanged, so hosted torchao checkpoints are never staged for AMD.
- quantize_transformer tries the native branch first. Image and video preflight and
  load paths admit it for pipeline loads only, skip the compile requirement and the
  offload decline (the buffers survive Module.to(), accelerate and group offload),
  and do not force a compile. GGUF, single-file and the modular H3 workflow are
  unchanged.
- NVIDIA, MPS, XPU and CPU never reach the new branch; tests pin that.
Also store fp8 payloads and fp32 scales as integer views so a module-wide dtype cast cannot widen or round them, and say weight-only in the resolved reason. End-to-end image and video load tests on a simulated AMD host.
With the precision fallback allowed, a native pass that swapped some linears
and then raised was treated as a clean decline and the load went on with a
half-converted DiT. Refuse it, as the image loader already does.
PEFT's DoRA forward reads base_layer.weight, and some DiT blocks read a
Linear's weight.dtype to cast their input. The native layer had no weight
attribute, so a DoRA adapter baked into an explicit int8 / fp8 AMD load
raised AttributeError on the first generation. weight now rebuilds the dense
tensor in the original dtype on each read; nothing is stored.
…rt native eager honestly

A video pipeline whose denoiser shards are stored fp8 / int8 is widened to bf16 by
from_pretrained, and quantising it again compounds the loss. The image loader already reads
the shard headers and declines; the video loader now does the same.

Weight-only runs eager, so the resolved speed_mode no longer claims a quantised
transformer requires compile on that path.
On an NVIDIA CUDA bf16 host, an explicit transformer_quant=int8 whose memory
request or plan offloads the transformer (balanced, low_vram, legacy
cpu_offload, or a measured plan that still offloads after the quant re-plan)
now runs the native layers from diffusion_native_quant with W8A8
(torch._int_mm) and the g256 ConvRot rotation, instead of being refused.
Those layers keep plain int8 buffers, which the offload hooks move with
Module.to(); torchao tensors do not survive that.

Unchanged: a resident NVIDIA load keeps the torchao path, auto never routes
here, fp8 / nvfp4 / mxfp8 under offload stay refused, GGUF and single_file
loads stay refused, ROCm keeps weight-only by default with W8A8 opt-in.

- native_quant_scheme(offload=...) and native_offload_host decide the route;
  native_int8_act picks the kernel (AMD opt-in via UNSLOTH_NATIVE_INT8_ACT=1,
  NVIDIA offload on unless UNSLOTH_NATIVE_INT8_ACT=0). The family deny list
  and UNSLOTH_NATIVE_INT8_ROT=0 still apply.
- apply_native_weight_quant takes act_int8 from its caller instead of reading
  the environment.
- Image and video preflights admit int8 under a named offload on NVIDIA; the
  loaders take the native route once the plan is final, and a resident plan
  still applies the torchao compile requirement.
- Status reports transformer_quant=int8, applied, with a reason read off the
  built layers (W8A8 + ConvRot vs weight-only).
- The compile-cache key separates native layers from torchao under the same
  scheme name.

Qwen-Image-2.1 1024px, 20 steps, one B200, warm images:
balanced bf16 7.6-8.8 s vs native int8 5.5-6.2 s; low_vram bf16 33.5-36.1 s
vs native int8 24.3-30.6 s; LPIPS vs bf16 0.004-0.019 per image.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-25T18:34:36.411672Z 9b4cdf2 Manual request
🔒 Security Review ✅ Completed 2026-09-25T15:01:34.069891Z 3bd4248 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 53aaee5f64

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

)
x_scale = x_scale.clamp_(min = 1e-12).div_(127.0)
xq = torch.mul(x2, x_scale.reciprocal()).round_().clamp_(-127, 127).to(torch.int8)
acc = torch._int_mm(xq, self.weight_q.t())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make the transposed INT8 weight contiguous

Whenever the new CUDA W8A8 path runs, self.weight_q.t() is a non-contiguous matrix passed directly to torch._int_mm. The repository's own verified INT8 wrapper in diffusion_torchao_patches.py explicitly makes mat2 contiguous because CUDA otherwise silently returns incorrect results, but this direct call bypasses that wrapper. Consequently, eligible NVIDIA offload inference can produce corrupted activations; materialize a contiguous transpose before invoking _int_mm (or store the weight in the required layout).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this against an exact int64 CPU reference. torch._int_mm(x, w.t()) with the column-major transposed view is bit-exact on torch 2.11.0, 2.12.1 and 2.13.0 (CUDA 13, B200) across the real DiT shapes (4160x3072x12288, 4297x3072x3072, 4096x12288x3072) and odd ones (M=17, M=33, M=1001 with N=520). The ROCm gfx1151 CI run of this path matched as well. at::_int_mm passes the transpose to cublasLt itself (its error text reports transpose_mat1 / transpose_mat2), so the view is the layout it expects. The torchao comment predates that. A .contiguous() here would copy the whole int8 weight on every forward for no gain (0.107 vs 0.108 ms on the 12288x3072 GEMM), so leaving it as is.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 3e895aaa46

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
diffusers' stream group offload onloads every group module's buffers but
its offload path restores only parameters, so buffers stayed on the GPU.
Native int8 layers keep their weights as buffers, so an explicit int8 under
balanced or low_vram ended up fully resident after the first block ran and
could OOM on the small GPUs that route exists for. Restore buffers from the
same host copies the onload reads.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The route admits an explicit int8 under balanced, low_vram or cpu_offload on the
native W8A8 path, which needs no compile. begin_load re-ran the same gate without
memory_mode / cpu_offload, so an eager request fell through to the compile check
and was refused after the route had already accepted it. Video had the same gap.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: a2bab51287

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

@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 554fcebb5c

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

Comment on lines +117 to +119
h = self.rot_h.to(torch.float32)
return (
(w.reshape(self.out_features, -1, g) @ h).reshape(self.out_features, -1).to(dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid re-rotating full weights in every DoRA forward

When a DoRA adapter is loaded on the default W8A8 ConvRot route, PEFT reads base_layer.weight during every forward, and the property above reaches this branch. It reconstructs the entire weight in float32 and multiplies every 256-element group by the dense Hadamard matrix on every projection and every denoising step, an O(weight_elements * 256) operation that also materializes a dense weight despite offload; large DiTs can therefore become unusably slow or exhaust memory. Preserve the model-basis value needed by DoRA without repeating this full inverse rotation, or reject/disable this combination.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured the scale: on a 3072 x 12288 projection the inverse g256 rotation is about 19 GFLOP against about 309 GFLOP for the layer's own matmul at 4096 tokens, roughly 6%, and PEFT's DoRA forward already materialises the dense base weight for its norm on every call for any base layer, so this adds no new dense copy class. Not unusable; keeping it.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9b4cdf242b

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

…to r11712

# Conflicts:
#	studio/backend/core/inference/diffusion.py
# Conflicts:
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_video_backend.py
Base automatically changed from studio-amd-weight-only-quant to main September 25, 2026 18:51
# Conflicts:
#	studio/backend/tests/test_diffusion_backend.py
# Conflicts:
#	studio/backend/core/inference/diffusion.py
#	studio/backend/core/inference/diffusion_native_quant.py
#	studio/backend/core/inference/diffusion_transformer_quant.py
#	studio/backend/core/inference/video.py
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_diffusion_native_quant.py
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
@danielhanchen
danielhanchen merged commit de7c4fd into main Sep 25, 2026
33 of 37 checks passed
@danielhanchen
danielhanchen deleted the studio-native-int8-offload branch September 25, 2026 19:01
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…W8A8 (unslothai#11712)

* Studio: run explicit INT8 / FP8 weight-only on AMD without torchao

ROCm hosts and the Windows-ROCm torchao stub refused an explicit transformer_quant of
int8 or fp8 before load, because dense_transformer_supported() is False there. On
gfx1151 an int8 weight-only transformer measured 0.97x bf16 speed at half the weight
memory, while torchao's W8A8 ran at 0.48x and fp8 _scaled_mm is refused, so the AMD
path is weight-only with bf16 arithmetic and no torchao at all (torchao cannot import
on Windows ROCm).

- New diffusion_native_quant: NativeWeightOnlyLinear keeps int8 (per-row absmax/127)
  or fp8 e4m3fn (per-row absmax/448) weights and an fp32 per-row scale as plain
  buffers and dequantises per forward. Swapped one layer at a time so the build peak
  stays near the dense model.
- native_quant_host / native_quant_scheme: explicit int8 / fp8 on a bf16 ROCm or
  torchao-stub GPU, family deny list applied. auto stays bf16. The shared selector is
  unchanged, so hosted torchao checkpoints are never staged for AMD.
- quantize_transformer tries the native branch first. Image and video preflight and
  load paths admit it for pipeline loads only, skip the compile requirement and the
  offload decline (the buffers survive Module.to(), accelerate and group offload),
  and do not force a compile. GGUF, single-file and the modular H3 workflow are
  unchanged.
- NVIDIA, MPS, XPU and CPU never reach the new branch; tests pin that.

* Keep the AMD weight-only path out of the loader's select-is-None decline

Also store fp8 payloads and fp32 scales as integer views so a module-wide dtype cast cannot widen or round them, and say weight-only in the resolved reason. End-to-end image and video load tests on a simulated AMD host.

* Refuse a video denoiser the weight-only pass converted part-way

With the precision fallback allowed, a native pass that swapped some linears
and then raised was treated as a clean decline and the load went on with a
half-converted DiT. Refuse it, as the image loader already does.

* Give native weight-only layers a dense weight view

PEFT's DoRA forward reads base_layer.weight, and some DiT blocks read a
Linear's weight.dtype to cast their input. The native layer had no weight
attribute, so a DoRA adapter baked into an explicit int8 / fp8 AMD load
raised AttributeError on the first generation. weight now rebuilds the dense
tensor in the original dtype on each read; nothing is stored.

* Decline a narrow-stored video DiT before weight-only conversion; report native eager honestly

A video pipeline whose denoiser shards are stored fp8 / int8 is widened to bf16 by
from_pretrained, and quantising it again compounds the loss. The image loader already reads
the shard headers and declines; the video loader now does the same.

Weight-only runs eager, so the resolved speed_mode no longer claims a quantised
transformer requires compile on that path.

* Opt-in W8A8 torch._int_mm path for native int8 diffusion linears

* Rotate W8A8 native int8 inputs with ConvRot so outlier channels do not pin the activation scale

* Native W8A8: fold the float32 upcasts into single-pass ops for eager (no-Triton) hosts

* Run an explicit int8 under offload on NVIDIA as torchao-free W8A8

On an NVIDIA CUDA bf16 host, an explicit transformer_quant=int8 whose memory
request or plan offloads the transformer (balanced, low_vram, legacy
cpu_offload, or a measured plan that still offloads after the quant re-plan)
now runs the native layers from diffusion_native_quant with W8A8
(torch._int_mm) and the g256 ConvRot rotation, instead of being refused.
Those layers keep plain int8 buffers, which the offload hooks move with
Module.to(); torchao tensors do not survive that.

Unchanged: a resident NVIDIA load keeps the torchao path, auto never routes
here, fp8 / nvfp4 / mxfp8 under offload stay refused, GGUF and single_file
loads stay refused, ROCm keeps weight-only by default with W8A8 opt-in.

- native_quant_scheme(offload=...) and native_offload_host decide the route;
  native_int8_act picks the kernel (AMD opt-in via UNSLOTH_NATIVE_INT8_ACT=1,
  NVIDIA offload on unless UNSLOTH_NATIVE_INT8_ACT=0). The family deny list
  and UNSLOTH_NATIVE_INT8_ROT=0 still apply.
- apply_native_weight_quant takes act_int8 from its caller instead of reading
  the environment.
- Image and video preflights admit int8 under a named offload on NVIDIA; the
  loaders take the native route once the plan is final, and a resident plan
  still applies the torchao compile requirement.
- Status reports transformer_quant=int8, applied, with a reason read off the
  built layers (W8A8 + ConvRot vs weight-only).
- The compile-cache key separates native layers from torchao under the same
  scheme name.

Qwen-Image-2.1 1024px, 20 steps, one B200, warm images:
balanced bf16 7.6-8.8 s vs native int8 5.5-6.2 s; low_vram bf16 33.5-36.1 s
vs native int8 24.3-30.6 s; LPIPS vs bf16 0.004-0.019 per image.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments

* Studio: return module buffers to the host under stream group offload

diffusers' stream group offload onloads every group module's buffers but
its offload path restores only parameters, so buffers stayed on the GPU.
Native int8 layers keep their weights as buffers, so an explicit int8 under
balanced or low_vram ended up fully resident after the first block ran and
could OOM on the small GPUs that route exists for. Restore buffers from the
same host copies the onload reads.

* Studio: forward the offload request to begin_load's precision re-check

The route admits an explicit int8 under balanced, low_vram or cpu_offload on the
native W8A8 path, which needs no compile. begin_load re-ran the same gate without
memory_mode / cpu_offload, so an eager request fell through to the compile check
and was refused after the route had already accepted it. Video had the same gap.

* Trim comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments

* Read a cached snapshot's shard headers when an offline load passes a hub id

* Resolve an offline hub id against Studio's live cache before the default

* Return module buffers to the host under stream group offload

* Keep native quantised projections out of the max speed QKV fusion

* Report a native video quant as weight-only in its resolved status

* Chunk the eager W8A8 forward so fp32 temporaries stay bounded on long inputs

* Key native W8A8 bundles on every layer's rotation; reshape rotations by leading dims

* Report ConvRot from every native layer, as the bundle key does

* Trim comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
jasonjack-jay pushed a commit to jasonjack-jay/unsloth that referenced this pull request Oct 25, 2026
…d function (bit-identical, 1.33x streamed) (unslothai#15183)

## Summary

A streamed or offloaded denoiser on the torchao-free native int8 W8A8
path runs eager. Examples:
- FLUX.2-klein-4B int8 under a small budget;
- Wan2.2 offloaded with `speed_mode=off`.

Each linear then runs the ConvRot rotation, the activation quantise,
`torch._int_mm` and the rescale as separate kernels, with Python between
them. The render thread spends almost all its time there: py-spy puts it
in `_int_mm_rows` / `_rotate`. Under host CPU load, GPU utilisation
drops from 99% to 77%.

Why it was eager:
- unslothai#11712 left this path uncompiled on purpose: eager W8A8 already beat
compiled bf16, and the first image cost 41 s compiled against 8 s eager.
- unslothai#14412 forces compile only when the denoiser stays resident.

Compiling the whole block (the existing regional compile) is fast, but
it is not bit-identical to eager. Triton's approximate fp32 reciprocal
moves the per-row scale by one ulp and flips about 1 in 10^4 int8 codes.
LPIPS against eager is 0.0175, against a bf16 eager-vs-compiled floor of
0.0097.

## Changes

- Each eager native int8 linear on CUDA runs as one `torch.compile`'d
function of plain tensors (`_w8a8_rows`, dynamic shapes): rotation,
scale, quantise, `torch._int_mm` and rescale together.
- The function takes tensors, not the module, so the offload hooks
moving weights never invalidate the graph.
- **Bit-identical to eager:** the reciprocal is taken in fp64, which
gives exactly the eager CUDA value, so the int8 codes match bit for bit.
- **No guard churn:** inputs are detached, so guards on view bases and
Parameter shapes do not pile up. That gives 2 graphs (with and without
bias), and 8 input shapes x 4 layers still give 2.
- **Regional compile unchanged:** compiled blocks still trace the eager
code.
- **When it stays off:**
  - on ROCm and on hosts without Triton;
  - during CUDA graph capture;
  - for too few rows.
- **Fallback:** a failed compile falls back to eager once and stays
there.
- **Kill switch:** `UNSLOTH_NATIVE_INT8_FUSED=0`.

## Results

Exclusive B200, Studio pinned to 8 cores, base and head interleaved, 7
processes per arm. FLUX.2-klein-4B int8 streamed, 1024x1024, 8 steps.
The host's load average stayed at 160-385 on 192 cores, so the quiet
figure is the best phase per process.

| | base | head |
|---|---|---|
| ms / step (median of per-process best) | 103.0 | **77.6 (1.33x)** |
| A/A spread, calm processes | 102.8-103.1 (5 of 7) | 74.9-77.6 (5 of 7)
|
| wall per image, calm processes | 0.93-0.94 s | 0.71-0.76 s |
| first step, cold compile cache | 0.55-0.73 s | 2.4-2.8 s (about +2 s
compile) |
| first step, warm compile cache | - | 1.86 s |

Wan2.2-TI2V-5B, `low_vram` int8, `speed_mode=off` (one process per arm,
no A/A): 9.71 / 8.77 -> 6.72 / 6.81 s per clip (about 1.35x); first
render 55.6 -> 50.9 s.

- **Images:** bit-identical to eager, 12 of 12 (2 prompts x 6 seeds) for
klein and 3 of 3 clips for Wan 5B.
- **Compile behaviour:** 0 graph breaks, 2 graphs (one recompile at the
first no-bias layer), and 0 recompiles on follow-up seeds and prompts.
- **Under CPU contention:** 251 ms (range 170-315) on base against 229
ms (137-349) on head. The host load makes this inconclusive, so no claim
is made for it.

## Tests

- New `tests/test_diffusion_native_quant_fused.py`, CPU parts:
- the kill switch, and staying eager without an inductor runtime, on
ROCm, for CPU input and for too few rows;
- fallback after a failed compile, while an out-of-memory error
propagates;
  - detached, non-Parameter inputs to the compiled function;
  - chunking on the accumulator;
  - the fused maths tracking the eager kernels.
- The CUDA test (bit-identical to eager, with and without rotation) was
run on a GPU.
- Native quant, speed, cold start and video suites: 3089 passed, 115
skipped.

## Limits

- No contended speed claim: the shared host was too loaded.
- Not run: Wan2.2-A14B, other GPU generations, and the torch 2.6 floor
(only torch 2.14.1 was tested).
- The path only runs on bf16 CUDA targets, so a T4 (fp16) never takes
it.
- On main, the regional int8 compile drifts from eager for the same
reciprocal reason. That is not changed here.
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.

2 participants