Skip to content

Studio: low-RAM follow-ups: first-load video encoder pin, honour transformer_quant none - #17667

Merged
danielhanchen merged 32 commits into
mainfrom
studio-lowram-followups
Nov 13, 2026
Merged

danielhanchen merged 32 commits into
mainfrom
studio-lowram-followups

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #17649 (base branch studio-lowram-sweep). Retarget to main once that merges.

Summary

This follows up on #17649 with fixes for two of the low-RAM problems that sweep found on a standard Colab T4 (12.7 GB host RAM, 15 GB card). It also records why the third one, the Qwen-Image-2.1 encode, is left as it is.

  1. First video load re-read its text encoder from disk on every clip. The pin plan runs while the load still holds its host copies, and a first load in a Studio home (still writing its cast cache) skipped the late prefix pin a returning load takes. Wan2.1-T2V-1.3B's 12.5 GiB UMT5 therefore pinned nothing. A first load now queues the same late prefix pin: the cap is read when the pinner starts, after the load has returned its freed heap, against the host RAM free then less the existing max(4 GiB, 15%) reserve. The exact page-rounded pricing stays gated on the finished cast-cache write, as before.
  2. transformer_quant=none on a small host rendered int8 while status said off. The small-host route stored every DiT as per-row int8 whatever the request (_apply_small_host_route). An explicit none / off now keeps the denoiser at its stored bf16 weights, memory-mapped, and casts each Linear per call, which the route already does for the streamed text encoders. Where the route still stores int8 (an auto request, or the kill switch), status, the resolved record and the image metadata now report int8 with the reason.

Kill switches: UNSLOTH_VIDEO_FIRST_LOAD_ENCODER_PREFIX=0 (fix 1), UNSLOTH_DIFFUSION_SMALL_HOST_DENSE=0 (fix 2).

Results on a standard Colab T4 (12.7 GB host RAM)

Each arm ran on the same VM as its comparison arm, with the same seeds. Times are per image or per clip, with every render listed.

Wan2.1-T2V-1.3B, 33 frames at 832x480, 20 steps, 2 clips per load

load tree encoder pin s/clip encode s disk GB/clip
first load #17649 none 352.9 / 291.2 115.7 / 67.7 27.4 / 13.5
first load this PR 6.4 GiB 325.2 / 279.8 77.4 / 57.0 21.8 / 8.7
first load, repeat in a fresh home this PR 6.4 GiB 327.9 / 334.5 77.0 / 110.5 22.0 / 8.7
second load, same home #17649 6.2 GiB 324.2 / 260.5 77.5 / 37.9 22.1 / 8.9
second load, same home this PR 6.2 GiB 321.7 / 260.7 74.9 / 37.9 21.9 / 8.6
  • On a first load, each clip now reads about 5 GB less from disk, and the first clip's encode drops from 116 s to 77 s.
  • The second clip of a first load overlaps the denoiser's deferred cast-cache write, so its encode varies between 57 s and 110 s with the same disk reads. That variance is present on both trees.
  • A second load is unchanged.
  • Every clip's frames are md5-identical across all five loads, and to a 51 GB high-RAM T4.

Qwen-Image-2.1-Turbo, transformer_quant=none, 1024x1024, 8 steps

tree denoiser actually run status s/img image md5
#17649 per-row int8 (small-host route) off 68.9 / 69.2 equal to the int8 output
this PR bf16 memory-mapped, cast per call off 276.6 / 276.5 equal to the 51 GB T4's dense output
this PR, repeat same off 264.7 / 262.4 equal to the 51 GB T4's dense output
this PR, auto request per-row int8 int8 (was off) 60.3 equal to the int8 output

Honouring the request costs time: groups that fit neither the card nor the pinned host RAM are read from the file on every step, about 62-66 GB per image. The load log says so and names auto / int8 as the faster choice.

Qwen-Image-2.1 encode, about 29 s per image from the memory-mapped text encoder. I measured the options before changing anything:

  • Splitting the late-pin room between the denoiser and the encoder: I did not build it.

    • The denoiser's streamed groups are read every step, 25 times per image. The encoder's are read once per prompt.
    • With the denoiser pinned first, the whole image reads 7.3-7.6 GB from disk, almost all of it in the encode, so the denoise phase reads well under 1 GB.
    • Each GiB moved from the denoiser pin to the encoder would save at most 1 GiB of encoder reads per image, and would put that GiB back into the per-step stream.
    • Without the denoiser pin, the same configuration thrashed on one VM (576 s/img, 131 GB/img in the Studio: late pins for streamed denoisers on low-RAM hosts, and dense FLUX.3 on 12 GB hosts #17649 sweep).
  • Keeping encoder groups on the card in the VRAM a render leaves unused, sized after the first render: I built and measured this, then did not ship it.

    Qwen-Image-2.1 int8, 25 steps, same VM s/img (renders 2-4) encode s disk GB/img
    Studio: late pins for streamed denoisers on low-RAM hosts, and dense FLUX.3 on 12 GB hosts #17649, two loads 145.4 / 144.0 / 144.3, 145.0 / 144.7 / 143.9 29.6-30.5 7.3-7.6
    this PR (the path is unchanged) 144.5 / 143.9 / 143.5 29.5 7.3-7.4
    encoder kept in the unused VRAM, two loads 134.5 / 135.1 / 135.4, 137.6 / 137.4 / 137.4 21.9-24.5 5.2-5.5
    • It saves about 6% with md5-identical images. On Qwen-Image-2.1-Turbo it saves about 4% (71.4 to 68.5 s/img).
    • Every later render then ran the card to its limit, and the allocator logged out-of-memory retries.
    • Its recorded activation peak rose from 6.7 GiB to 10.1 GiB. A later load in the same home would read that peak and place less of the denoiser on the card.
    • To be safe it needs to be tied into the decode-lend accounting, which is a separate change.
  • Kept: the denoiser-first late pin from Studio: late pins for streamed denoisers on low-RAM hosts, and dense FLUX.3 on 12 GB hosts #17649.

High-RAM T4 (51 GB), no-regression check: this code does not engage there.

model #17649 s/img or s/clip this PR md5
Qwen-Image-2.1-Turbo none 36.2 / 38.8 38.8 / 37.5 identical
Qwen-Image-2.1-Turbo int8 33.7 / 31.8 32.7 / 32.3 identical
Wan2.1-T2V-1.3B 258.6 256.3 identical

Tests

  • tests/test_video_encoder_exact_pin.py covers three cases:
    • a first load queues the late prefix with a callable cap;
    • both kill switches restore the old first load;
    • the cap returns freed heap before reading the budget.
  • tests/test_small_host_dense_denoiser.py covers the following:
    • the routing decision: no int8, no spill, mapped route size;
    • bit-exact equality of a mapped DiT with the converted one, repeated calls included;
    • the LoRA refusal;
    • int8 status reporting;
    • load plumbing.
  • The related backend suite was run on this branch and on Studio: late pins for streamed denoisers on low-RAM hosts, and dense FLUX.3 on 12 GB hosts #17649, two 8-worker runs side by side on one CPU host.

…t16 builds

A float16 FLUX.3 load (fp16-only cards such as T4) converted the bf16 text
encoder and transformer to float16 on the host, a private copy of each
(about 20 GB for klein, more while converting), which killed the process on a
12.7 GB host. The float16 build now reads both components as stored (memory
mapped, no copy) with the exact per-call cast the float32 build already uses.

- flux3_storage_dtype returns bf16 for float16 CUDA loads too
  (UNSLOTH_DIFFUSION_FLUX3_HALF_STORAGE=0 restores the widened load).
- The transformer is read as stored only when a native quant rebuilds its
  Linears, or when storage saves memory (float32); a dense float16
  transformer still loads widened so it never casts per step.
- The native quantiser rounds a manual-cast weight to the compute dtype before
  quantising, so the int8 codes match a widened load bit for bit.
- After a native quant on an fp16-only card, the Linears left dense become
  plain float16 modules again, exactly what a float16 load holds.
…r's weight

Reading .weight on a native quantised Linear dequantises it, so the undo
pass after the FLUX.3 klein int8 build dequantised all 228 quantised Linears
(about 22 s of the load and a dense transient on the host). Only manual-cast
modules are inspected now.
…nce the denoiser is placed

On a 12 GB host the image load decides what to pin while it still holds the
denoiser's host copy, so a FLUX.3 klein int8 load on a T4 pinned none of its
7.5 GiB text encoder. The encoder then streamed from its memory-mapped file,
and since its streamed groups are slightly larger than the page cache left,
every prompt re-read about 6.5 GB from disk (21 to 27 s of encode per image).

When the plan-time budget misses, the streamed encoder now defers its pin with
a cap read when the pinner starts: the load's freed heap is returned to the OS
first, the usual max(4 GiB, 15%) reserve is kept, and only the prefix of
offload groups that fits is pinned. Whole pins, the small-host route and the
plan-time prefix are unchanged.

Kill switch: UNSLOTH_DIFFUSION_LATE_IMAGE_ENCODER_PIN=0.
…once the load returns

On a 12 GB host the small-host route never pins: its int8 denoiser lives in a
memory-mapped scratch file and every streamed group is copied from there on
each step. Qwen-Image-2.1 int8 on a T4 streams 5 GB of its denoiser per step,
more than the page cache left, so every step re-read it from disk (134 GB per
image, 23 s per step) while 7 GB of host RAM sat free after the load.

The route now pins the leading streamed (non-resident) denoiser groups with a
cap read when the background pinner starts: the load's freed heap is returned
to the OS first and the usual max(4 GiB, 15%) reserve is kept. Resident groups
spend none of the cap and keep their host copy. The bytes are the same, only
the host copy moves into pinned memory.

Kill switch: UNSLOTH_DIFFUSION_LATE_DENOISER_PIN=0.
The streaming tier (a denoiser or encoder larger than the card) decided its
pins only at plan time, while the load still held its host copies. On a 12 GB
host that pinned nothing: the encoder and every streamed denoiser group were
copied from pageable or memory-mapped host memory on each use, and re-read from
disk once they outgrew the page cache.

An image load whose plan-time pin budget misses now does what the group tier
does: the denoiser pins the leading streamed groups that fit when the
background pinner starts, then the encoders pin the prefix still free, each cap
read after the load's freed heap is returned to the OS and keeping the usual
max(4 GiB, 15%) reserve. Whole pins, video loads (their own background pins)
and the small-host encoders are unchanged.

Kill switches: UNSLOTH_DIFFUSION_LATE_DENOISER_PIN=0 and
UNSLOTH_DIFFUSION_LATE_IMAGE_ENCODER_PIN=0.
…dened copy does not fit host RAM

A dense FLUX.3 load on an fp16-only card (transformer_quant none on a T4)
still converted the bf16 transformer to float16 on the host. That conversion
peaks at about 1.6x the stored bytes, about 18 GB for klein's 11.1 GB
transformer, and on a 12.7 GB Colab T4 the load stalled with no output for an
hour.

By default the transformer now widens on the host only when that copy fits
the available host RAM beside the small-host reserve; otherwise it reads bf16
as stored and casts each Linear per call, which the text encoder already
does. The float16 weights each call sees are the ones the widened load holds,
so the output is unchanged. Hosts with the room, quantised builds and an
explicit transformer_storage keep their current load.

Kill switch: UNSLOTH_DIFFUSION_FLUX3_DENSE_STORAGE=0 (UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0
also keeps the widened load).
… unpinned

Queuing the late prefix pin is an optimisation. On the streaming tier any
exception during setup is fatal for the load, so a denoiser whose offload
groups cannot be read (a duck-typed module) failed the load instead of
streaming unpinned as before. The queueing now logs and returns instead.
…ncoders on any image load

The late denoiser pin covered only the small-host route. A dense FLUX.3 klein
on a 12.7 GB T4 takes the ordinary group tier: 2.9 GB of its transformer
streams every step, the plan pinned nothing, and the late encoder pin then
took the 6.5 GiB free after the load, so each step re-read the streamed blocks
from disk (217 s per image).

Any image load whose plan-time budget misses the denoiser now queues the
denoiser's prefix pin first, then the encoder's; the encoder cap subtracts only
the denoiser groups that still stream (resident groups are not owed). Whole
pins and video loads are unchanged.
… the load returns

A first video load in a Studio home (still writing its cast cache) pinned
none of a streamed text encoder that missed the plan-time pin budget. The
plan runs while the load still holds its host copies, so on a 12.7 GB Colab
T4 Wan2.1-T2V-1.3B's 12.5 GiB UMT5 pinned nothing and re-read its
memory-mapped weights from disk on every clip (90-115 s of a 342 s clip).

The first load now queues the same late prefix pin a returning load already
takes: the cap is read when the pinner starts, after the load has returned
its freed heap to the OS, against the host RAM free then less the existing
max(4 GiB, 15%) reserve. The exact page-rounded pricing stays gated on a
finished cast-cache write as before.

Kill switch: UNSLOTH_VIDEO_FIRST_LOAD_ENCODER_PREFIX=0 (UNSLOTH_VIDEO_EXACT_PIN_PLAN=0
also turns it off).
…ort an int8 denoiser as int8

On a host too small for the dense float16 copy (a 12.7 GB Colab T4), the
small-host route stored every DiT as per-row int8, whatever the request. A
Qwen-Image load with transformer_quant none therefore rendered the int8
output (md5-identical to an int8 load) while status reported the transformer
quant as off.

An explicit none / off now keeps the denoiser at its stored bf16 weights,
memory-mapped, and casts each Linear per call, as the route already does for
the streamed text encoders. The float16 weights each call sees are the ones
the dense load converts once, so the output matches a host with the RAM. The
streamed groups read from the file (the late denoiser pin still pins the
prefix that fits). Such a load refuses LoRA with its own reason, as the int8
route does. On a 12.7 GB Colab T4, Qwen-Image-2.1-Turbo at 1024x1024 then
takes about 265-275 s per image (the int8 route: about 69 s) and its images
are md5-identical to a 51 GB T4's dense load.

Where the route still stores int8 (an auto request, or the kill switch),
status, the resolved record and the image metadata now say int8 with the
reason instead of off; an explicit none that fell back reads as fell back.

Kill switch: UNSLOTH_DIFFUSION_SMALL_HOST_DENSE=0.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T12:50:32.387092Z 18b11b5 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 756b7ff3e1

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

…ndeferrable encoders on their old route

UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0 never pins, but the late image route still queued an encoder pinner with a zero cap: it dropped resident host copies, trimmed the heap and logged a pin plan. A pipe with no deferrable text encoder (none, or torchao weights) logged the late pin plan without queuing anything. Both now keep their old route and log.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a03db07219

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

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 509b27fb5d

ℹ️ 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 +13433 to +13435
elif getattr(decision, "dense_denoiser", False):
# the float16 weights each call sees are the ones the dense load converts once, so output is unchanged
mib = prepare_streamed_encoder_(module, 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.

P2 Badge Exclude mapped denoisers from subsequent QKV fusion

On a small-host FLUX.1 load with transformer_quant="none" and speed_mode="max", this leaves the projection weights in bf16 with per-Linear casting hooks, but the later apply_speed_optims call still invokes _fuse_qkv (diffusion_speed.py). That helper excludes quantized and manual-cast projections, not these mapped projections, so fusion creates new bf16 to_qkv layers without the casting hooks. The fused attention then feeds fp16 activations into those bf16 Linears and generation fails with a dtype mismatch. Skip QKV fusion for mapped denoisers, or ensure the newly fused projections receive the same casting treatment.

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.

Fixed in 9919052e6. Rather than special-casing mapped denoisers, QKV fusion (and the fused-bytes estimate) now skips any denoiser whose Linears carry diffusers' layerwise-casting hook, since a fused to_qkv is a plain Linear without that hook. A test covers a mapped denoiser (skipped) and a plain one (still fused).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 18b11b57ec

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

Base automatically changed from studio-lowram-sweep to main November 13, 2026 13:19
# Conflicts:
#	studio/backend/core/inference/diffusion.py

[skip ci]
@danielhanchen
danielhanchen merged commit 7bf13f2 into main Nov 13, 2026
@danielhanchen
danielhanchen deleted the studio-lowram-followups branch November 13, 2026 13:22
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…d VAE canvas gates (#17681)

## Summary

Two checks fail on main (`7bf13f2`) and on every PR based on it. The
`(Python 3.13, a-f)` and `(Python 3.13, rest)` shards show them on
staging runs:

```
studio/backend/tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly
E   AssertionError: use core.inference.rocm_bf16.is_rocm_torch(torch): AMD SDK / Radeon wheels leave torch.version.hip unset.
    Raw reads: {'diffusion_torchao_patches.py': [66], 'diffusion_vae_canvas.py': [296]}

studio/backend/tests/test_small_host_dense_denoiser.py::test_qkv_fusion_skips_a_mapped_denoiser[True]
core/inference/diffusion_small_host.py:863: in prepare_streamed_encoder_
E   ModuleNotFoundError: No module named 'diffusers'
```

Both reproduce locally on main (the second with `diffusers` blocked).

### ROCm gates (#17613, #17595)

The lint is right, and both reads are real bugs on AMD SDK / Radeon
wheels, which leave `torch.version.hip` unset and carry the ROCm tag
only in `torch.__version__`:

- #17613 gates the int8 GEMM's transposed-weight path with
`getattr(torch.version, "hip", None) is None`. On a tag-only ROCm wheel
that is true, so the cuBLASLt-only TN layout would be sent to hipBLASLt.
The comment above it says ROCm should keep the row-major copy.
- #17595's `diffusion_vae_canvas._is_rocm()` calls `is_rocm_torch()`
with no argument. That raises `TypeError`, which the `except` swallows.
The fallback then reads `torch.version.hip`, so every call took the raw
read, and a tag-only ROCm wheel got the NVIDIA tile-graph replica count.

### Mapped denoiser test (#17667)

`test_qkv_fusion_skips_a_mapped_denoiser[True]` maps the denoiser
through `prepare_streamed_encoder_`, which uses
`diffusers.hooks.apply_layerwise_casting`. The backend test shards do
not install `diffusers`. The bit-for-bit test in the same file already
guards on it with `pytest.importorskip("diffusers.hooks")`.

## Change

- `diffusion_torchao_patches.py`: `keep_transposed` now uses
`_is_rocm_torch(torch)`, a small helper that calls
`rocm_bf16.is_rocm_torch`.
- `unsloth/import_fixes.py`: `_make_safe_int_mm` must stay AST-identical
to the Studio copy (`test_studio_copy_matches_unsloth_import_fixes`). It
gets the same call, plus its own `_is_rocm_torch` with the same
tag-aware check, so whichever copy patches torchao first behaves the
same.
- `diffusion_vae_canvas._is_rocm()`: calls `is_rocm_torch(torch)`, with
no raw fallback.
- `test_small_host_dense_denoiser.py`: the mapped case calls
`pytest.importorskip("diffusers.hooks")`, like its sibling. The unmapped
case still runs everywhere.

## Guards

- `test_vae_canvas_graph_replicas_see_a_tag_only_rocm_wheel` and
`test_vae_canvas_rocm_check_does_not_fall_back_on_a_cuda_build` in
`test_diffusion_rocm_tag_detect.py`.
- `test_a_tag_only_rocm_wheel_keeps_the_row_major_copy` in
`test_torchao_int_mm_transposed.py`, next to the existing
`torch.version.hip` case.

## Testing

- `test_diffusion_rocm_tag_detect.py`,
`test_torchao_int_mm_transposed.py`,
`test_torchao_intmm_patch_wiring.py`,
`test_small_host_dense_denoiser.py`: 33 passed, 4 skipped (CUDA-only
cases).
- Sabotage: with main's three source files and these tests, 3 fail (the
lint, the VAE canvas tag-only case, the int8 tag-only case).
- With `diffusers` blocked: main's
`test_qkv_fusion_skips_a_mapped_denoiser[True]` fails with the CI error;
here it skips and `[False]` passes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant