Skip to content

Unsloth Studio (AMD): allow INT8 / FP8 image and video precision without torchao - #11631

Merged
danielhanchen merged 15 commits into
mainfrom
studio-amd-weight-only-quant
Sep 25, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
studio-amd-weight-only-quant

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

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.

  • Auto is unchanged on AMD and stays bf16: this is a memory saving, not a speed-up.
  • NVIDIA, Apple Silicon, Intel and CPU never reach the new code. Their selection and quantization paths are unchanged.
  • One change reaches every host, video only: a video pipeline whose denoiser shards are stored fp8 / int8 now declines a second in-place quantisation (from_pretrained already widened it to bf16, so quantising again compounds the loss). The image loader already did this on every host; the video loader now matches it.

Why AMD was refused

dense_transformer_supported() returns False on every ROCm GPU, for two reasons:

  1. ROCm reports gfx1151 (Strix Halo) as compute capability (11, 5). Studio's auto ladder is built on NVIDIA SM floors, so that value would put the chip in the Blackwell tier.
  2. The torchao schemes do not run there:
    • torch._scaled_mm refuses every fp8 dtype below MI300.
    • torchao's int8 W8A8 ran at 0.48x bf16 speed on gfx1151.
    • On Windows ROCm torch, torchao cannot even be imported, because torch.ops._c10d_functional.all_gather_into_tensor is missing. That is why Studio ships a torchao stub there.

What changes

  • New module diffusion_native_quant.py: a torchao-free weight-only Linear.
    • INT8 uses a per-row absmax/127 scale. FP8 is stored as e4m3fn with a per-row absmax/448 scale.
    • Weights and scales are plain integer buffers, so they:
      • survive the Module.to() calls the offload hooks make;
      • cannot be cast by a module-wide .to(dtype).
    • Layers are swapped one at a time, so the build peak stays near the dense model plus one layer.
  • quantize_transformer: tries the native branch first when both of these hold:
    • the host is ROCm or the Windows torchao stub, with a bf16 GPU;
    • the scheme is an explicit int8 / fp8.
  • Unchanged, so hosted torchao checkpoints, GGUF upgrades and auto rungs never reach an AMD host:
    • select_transformer_quant_scheme
    • dense_transformer_supported
  • Image and video loaders:
    • accept the native scheme at the pre-load gate and in the loader;
    • re-plan memory at the quantized size;
    • keep the quantization under an offload plan (plain buffers move fine);
    • do not force compile, since the arithmetic stays bf16.
  • Status: resolved.transformer_quant reports applied, with a reason that says "weight-only: int8 weights, bf16 compute".
  • Still refused on AMD, as before: GGUF, single-file and the MiniMax-H3 modular workflow, plus nvfp4 and mxfp8.

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:

arm transformer speed vs bf16 peak LPIPS
bf16 13.25 GiB 1.00x (20.9 s/step) 38.7 GiB ref
int8 weight-only 6.64 GiB 0.97x 30.3 GiB 0.076
fp8 storage, bf16 compute 6.64 GiB 0.97x 30.3 GiB 0.122
torchao int8 W8A8 (today's NVIDIA path) 6.76 GiB 0.48x 30.4 GiB 0.154
torchao fp8 refused

Windows 11, torch 2.11.0+rocm7.13.0 from AMD's gfx1151 index, no torchao:

arm transformer speed vs bf16 peak LPIPS
bf16 13.25 GiB 1.00x (25.7 s/step) 38.7 GiB ref
int8 weight-only (this module's math) 6.63 GiB 0.98x 30.3 GiB 0.114
fp8 weight-only with per-row scale 6.63 GiB 1.00x 30.3 GiB 0.144

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.

state scheme loaded transformer s/image peak LPIPS PSNR
main int8 refused: "dense torchao quant schemes are NVIDIA tensor-core paths"
main fp8 refused, same reason
this PR off yes 13.25 GiB 620.7 38.67 GiB ref ref
this PR int8 yes, reported int8 6.76 GiB 240.7 30.35 GiB 0.092 24.67
this PR fp8 yes, reported fp8 6.63 GiB 233.5 30.22 GiB 0.165 20.33

Verdict: 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_quant set explicitly, sent to main (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.

state scheme loaded transformer s/image peak LPIPS PSNR
main int8 refused: "dense torchao quant schemes are NVIDIA tensor-core paths"
main fp8 refused, same reason
this PR off yes 13.25 GiB 251.8 36.84 GiB ref ref
this PR int8 yes, reported int8 6.76 GiB 272.1 30.35 GiB 0.127 23.53
this PR fp8 yes, reported fp8 6.63 GiB 275.1 30.22 GiB 0.133 22.56

Verdict: 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

  • New tests:
    • test_diffusion_native_quant.py: layer accuracy, filter, host detection and dtype-cast safety, with NVIDIA, MPS, XPU and CPU asserted untouched.
    • End-to-end image and video loads on a simulated AMD host, in test_diffusion_backend.py and test_video_backend.py.
  • Real bug caught: the image end-to-end test fails without the loader fix in the second commit, because the explicit scheme was declined by the select_transformer_quant_scheme(...) is None branch.
  • Full diffusion and video suites: 3998 passed. The 4 failures are pre-existing and also fail on main in this environment: 3 PyAV rotation tests, and 1 order-dependent GGUF Q8_0 test.

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.
@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-25T17:38:34.569821Z 9a21826 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[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: f51c52a870

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

@LeoBorcherding

LeoBorcherding commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

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. unsloth/Qwen-Image-2.1, 1024x1024, 20 steps, seed 1234, speed off. commit f51c52a.

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. NativeWeightOnlyLinear stores each layer's weights as int8 or fp8 plus one scale number per row. every time the layer runs, it turns them back into bf16 and does normal bf16 math. so it's a memory saving, not a speed trick. native_quant_host decides when to use this path instead of torchao.

results:

precision load 1st image 2nd image looks like bf16?
fp8 61 s 46 s 38 s yes, 27.1 dB PSNR
int8 58 s 46 s not measured (ran out of system ram) yes, 27.2 dB PSNR
bf16 (no quant) 62 s 278 s crashed (ran out of system ram) reference
  • the big win: bf16 is too big for the gpu here, so it has to fall back to slow offloading (moving pieces between system ram and gpu). int8/fp8 are small enough for the faster offload mode, so they're about 6x faster per image on this card
  • images are identical run to run for the same seed, and the text on the poster comes out clean in both quant modes
  • the crashes were this box running out of system ram (32 GB isn't enough for this model's text encoder plus offloading). none of them were in the new code

small things, not blockers:

why this matters beyond this pr: users keep picking unsloth/Qwen-Image-2.1-FP8 directly, which downloads ~14 GB and then fails. i have a fix coming that blocks that pick and tells them to load the base model and set precision to fp8/int8 instead. on amd, that advice only works once this pr is in.

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 native_scheme is None exemption at the offload gate (plain int8/fp8 buffers survive offload, that's where the 46 s vs 278 s comes from). #11712 is stacked on this so it goes after.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 3cd99379fe

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

# Conflicts:
#	studio/backend/core/inference/video.py
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_video_backend.py
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen 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 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: 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".

Comment on lines +60 to +61
scale = self.weight_scale.view(torch.float32)
return (wq.to(torch.float32) * scale[:, None]).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 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 👍 / 👎.

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 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.

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 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: 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".

Comment on lines +1133 to +1136
if callable(is_torchao) and callable(restore_torchao) and is_torchao(buffer):
restore_torchao(buffer, cpu)
else:
buffer.data = cpu

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 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 👍 / 👎.

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.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@LeoBorcherding LeoBorcherding changed the title Studio: run explicit INT8 / FP8 weight-only on AMD without torchao Unsloth Studio (AMD): allow INT8 / FP8 image and video precision without torchao 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: 9a21826f23

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

Copy link
Copy Markdown
Member Author

pre-commit.ci run

# Conflicts:
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_video_backend.py
@danielhanchen
danielhanchen merged commit f0b73b2 into main Sep 25, 2026
34 of 37 checks passed
@danielhanchen
danielhanchen deleted the studio-amd-weight-only-quant branch September 25, 2026 18:51
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
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.

3 participants