Repository navigation
Unsloth Studio (AMD): allow INT8 / FP8 image and video precision without torchao - #11631
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.
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. |
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.
|
@codex security review |
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.
|
Codex Review: Didn't find any major issues. 🎉 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". |
|
tested this on an amd card, works 👍 setup: R9700 (gfx1201, 32 GB), windows 11, torch 2.11.0+rocm7.13.0, 31.6 GB system ram. what the pr does, short version: on main, picking int8 or fp8 precision on an amd card gets refused ("the dense torchao quant schemes are NVIDIA tensor-core paths"), because those modes rely on torchao, which only really works on nvidia. this pr adds its own simple version that doesn't need torchao. results:
small things, not blockers:
why this matters beyond this pr: users keep picking only tested on this one card on windows. i didn't try linux or other amd gpus. merge heads up: this merges clean with main, #11533, #11829, #11782 and #11835. it conflicts with #11558, #11883 and #11819 in diffusion.py, at the pre-load and offload gates. whichever lands second should keep this pr's |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
# Conflicts: # studio/backend/core/inference/video.py # studio/backend/tests/test_diffusion_backend.py # studio/backend/tests/test_video_backend.py
|
@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: e45c02cdad
ℹ️ 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".
| scale = self.weight_scale.view(torch.float32) | ||
| return (wq.to(torch.float32) * scale[:, None]).to(dtype) |
There was a problem hiding this comment.
Avoid materializing two FP32 weight copies per forward
For the low-VRAM AMD configurations this path targets, every linear invocation first expands the entire quantized matrix to FP32 and then performs an out-of-place FP32 multiply before allocating the BF16/FP16 result. Thus a large projection transiently requires the stored quantized weight, two full FP32 matrices, and the compute-dtype matrix, while the new memory replanning assumes roughly weight-only INT8/FP8 residency and may consequently drop CPU offload. Models that only fit according to that quantized estimate can therefore OOM on their first denoising step; dequantize directly in the compute dtype or use a fused/chunked operation so the unbudgeted FP32 copies are not materialized.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured on the largest Qwen-Image sized layer (3072 to 12288, 4096 tokens): the per-forward transient is 288 MiB vs 168 MiB with a bf16 dequant, about 120 MiB for one layer at a time, well inside the planner's GiB margins; the real gfx1151 runs peaked at 30.3 GiB with no OOM. A bf16 dequant would also round each per-row scale to bf16 first, moving the numerics the AMD LPIPS was measured on. Keeping the fp32 path.
|
@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: c20490f331
ℹ️ 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 callable(is_torchao) and callable(restore_torchao) and is_torchao(buffer): | ||
| restore_torchao(buffer, cpu) | ||
| else: | ||
| buffer.data = cpu |
There was a problem hiding this comment.
Record buffer use before restoring the CPU storage
With block-level group offload on CUDA, _apply_group_offload enables both a prefetch stream and record_stream=True, but this added buffer path replaces the GPU storage with the CPU copy without first recording the GPU buffer on the current compute stream. Since the forward's dequantization and matmul kernels are asynchronous, the caching allocator may reuse that GPU allocation for a later prefetched group while the current group is still reading it, causing nondeterministic corruption or illegal accesses under the native-quantized offload configuration. Mirror Diffusers' parameter restoration by calling record_stream on the outgoing buffer storage before assigning cpu.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The GPU buffer is already recorded on the compute stream at onload: diffusers' _transfer_tensor_to_device calls tensor.data.record_stream(default_stream) for every tensor _process_tensors_from_modules moves, and that loop covers group_module.buffers(). diffusers' own parameter restore in _offload_to_memory does not record again at offload either (and synchronises first when record_stream is off, before this wrapper runs), so the buffer path mirrors the parameter path exactly.
|
@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". |
|
pre-commit.ci run |
# Conflicts: # studio/backend/tests/test_diffusion_backend.py # studio/backend/tests/test_video_backend.py
…out torchao (unslothai#11631) * 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. * Trim comments * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * 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 * Trim comments --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
On AMD GPUs, an explicit INT8 or FP8 transformer precision for image and video diffusion models is now honoured instead of being refused. The transformer weights are stored in 8 bits (one scale per output row) and dequantized to bf16 for each matmul, without torchao.
Why AMD was refused
dense_transformer_supported()returns False on every ROCm GPU, for two reasons:(11, 5). Studio's auto ladder is built on NVIDIA SM floors, so that value would put the chip in the Blackwell tier.torch._scaled_mmrefuses every fp8 dtype below MI300.torch.ops._c10d_functional.all_gather_into_tensoris missing. That is why Studio ships a torchao stub there.What changes
diffusion_native_quant.py: a torchao-free weight-only Linear.Module.to()calls the offload hooks make;.to(dtype).quantize_transformer: tries the native branch first when both of these hold:int8/fp8.select_transformer_quant_schemedense_transformer_supportedresolved.transformer_quantreportsapplied, with a reason that says "weight-only: int8 weights, bf16 compute".Measured on real gfx1151 (AMD CI, Radeon 8060S)
Qwen-Image-2.1, 1024x1024, 20 steps, cfg 4.0, 2 prompts. Same seeds as the bf16 arm; LPIPS is against that arm.
Linux, torch 2.11.0+rocm7.13.0:
Windows 11, torch 2.11.0+rocm7.13.0 from AMD's gfx1151 index, no torchao:
On both OSes, every arm rendered the prompt correctly, including legible sign text. The per-prompt LPIPS spread is wide: the fp8 text encoder alone scored 0.04 on one prompt and 0.28 on the other.
Through Studio's own DiffusionBackend, base vs head (Linux, gfx1151)
Same probe on the Linux runner (main b9f8155, this branch f51c52a), each scheme in a fresh process, 1024x1024, 2 images per arm.
int8fp8Verdict: CONFIRMED on Linux as well. The bf16 time here is well above the Windows run and above the earlier per-step measurement, so treat the Linux speed column as memory-pressure sensitive on this 62 GB unified-memory APU; the memory and quality columns are the stable result.
Through Studio's own DiffusionBackend, base vs head (Windows 11, gfx1151)
The same request,
transformer_quantset explicitly, sent tomain(b9f8155) and to this branch (3502f74), each scheme loaded in a fresh process. 1024x1024, 2 images per arm, LPIPS and PSNR against the head's bf16 arm.int8fp8Verdict: CONFIRMED, the refusal reproduces on main and is gone on this branch. Weight-only halves the transformer and cuts peak memory by about 6.5 GiB on a unified-memory APU, at roughly 8 to 9% more time per image; it is a memory saving, not a speed-up. Not covered on this host: AMD fp8 matrix cores (MI300 class), discrete AMD GPUs, multi-GPU.
Tests
test_diffusion_native_quant.py: layer accuracy, filter, host detection and dtype-cast safety, with NVIDIA, MPS, XPU and CPU asserted untouched.test_diffusion_backend.pyandtest_video_backend.py.select_transformer_quant_scheme(...) is Nonebranch.