Repository navigation
Studio: run an explicit int8 under offload on NVIDIA as torchao-free W8A8 - #11712
Conversation
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.
…t pin the activation scale
…(no-Triton) hosts
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.
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 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()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
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.
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.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…to r11712 # Conflicts: # studio/backend/tests/test_diffusion_native_quant.py
|
@codex review |
There was a problem hiding this comment.
💡 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".
| h = self.rot_h.to(torch.float32) | ||
| return ( | ||
| (w.reshape(self.out_features, -1, g) @ h).reshape(self.out_features, -1).to(dtype) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…to r11712 # Conflicts: # studio/backend/core/inference/video.py
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
…to r11712 # Conflicts: # studio/backend/core/inference/diffusion.py
# Conflicts: # studio/backend/tests/test_diffusion_backend.py # studio/backend/tests/test_video_backend.py
# 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
…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>
…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.
Stacked on #11631 (base
studio-amd-weight-only-quant). It adds three things: the opt-in W8A8torch._int_mmpath 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
int8withbalanced/low_vram/cpu_offloadis 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 throughtorch._int_mm), they are faster than bf16 there, not just smaller.What changes
diffusion_native_quant.py: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).dequantized_weightundoes the rotation, so LoRA baking and export see the real weight.native_quant_signature/native_quant_reasonreport 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_actdefaults W8A8 on for that route.diffusion.py/video.py:diffusion_compile_cache.py: native layers key their own bundle (int8-w8a8-rot256), so they never share one with torchao int8.Behaviour
UNSLOTH_NATIVE_INT8_ACT=1Switches:
UNSLOTH_NATIVE_INT8_ACT=0turns the NVIDIA route into weight-only native.UNSLOTH_NATIVE_INT8_ROT=0drops the rotation.Measurements
Qwen-Image-2.1, 1024x1024, 20 steps, one idle B200. Seconds per image, where image 0 includes the compile:
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:
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
test_diffusion_native_quant.py,test_diffusion_backend.py,test_video_backend.py,test_diffusion_compile_cache.py: 1019 passed.studio/backend/testsrun 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
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".