Skip to content

Studio: pin a streamed image text encoder once the denoiser is placed (low-RAM hosts) - #17644

Merged
danielhanchen merged 8 commits into
mainfrom
studio-lowram-te
Nov 13, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-lowram-te

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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

Summary

On a standard Colab T4 (12.7 GB host RAM) FLUX.3 klein int8 rendered at 62 to 63 s/img, against 37 s/img on a high-RAM T4. The gap was all in the text encoder: 24 to 27 s of encode per image, against 0.7 s on high-RAM. Denoise was the same 35 to 36 s on both.

This PR pins the streamed text encoder once the load has placed the denoiser on the GPU, when host RAM allows it. On the standard T4 it now renders at 36.6 to 37.0 s/img with 0.8 to 1.2 s of encode per image. Images are byte-identical, and the high-RAM path is unchanged.

Cause

  • The image load decides what to pin (_streamed_pin_plan, diffusion_memory.py) while it still holds the int8 transformer's host copy. On the 12.7 GB VM that reading was encoders=False (7696 MiB) against 0 MiB of pinnable host RAM. The plan-time prefix (_streamed_pin_leftover_mib) was 0 too, so no pinner was queued for the encoder.
  • The 6.0 GiB of streamed encoder groups stayed as views of the memory-mapped safetensors file. Each onload ran ModuleGroup._pinned_memory_tensors (diffusers group_offloading.py:202), which calls tensor.pin_memory() on those views. A py-spy profile puts 26.5 s of a 27.0 s encode window on that line.
  • The page cache could not keep those pages between prompts. During renders the VM had about 8.8 GiB of page cache, about 2.8 GiB of it active (libraries and other mapped files), and the encoder's streamed set is just larger than what was left. A sequential scan over a working set slightly larger than the cache misses almost every page. Each prompt re-read 5.7 to 6.4 GB from disk (process read_bytes), about 25k major faults.
  • Once the load had moved the transformer to the GPU and returned its freed heap (2.4 to 2.6 GiB), the same host had about 10.5 GiB available. That was enough to pin the encoder within the usual reserve.

Change

  • Image loads whose streamed text encoders miss the pin budget at plan time now defer the encoder pin with a cap that is read when the pinner starts, not at plan time. This reuses the existing _GroupPinner byte cap and _late_encoder_pin_cap, which video loads already use.
  • Before reading the budget, the cap returns the load's freed heap to the OS (trim_host_heap_after_load), so the budget counts the denoiser host copy the load has already dropped.
  • The budget is _pin_budget_mib(), unchanged: it keeps max(4 GiB, 15%) of host RAM free. Only the prefix of offload groups that fits is pinned. When nothing fits (under 256 MiB), nothing is pinned and the encoder streams as before.
  • Resident encoder groups drop their host copy first (lazy_resident, as on the existing image path).
  • Unchanged:
    • whole plan-time pins (every high-RAM host);
    • the small-host route, which keeps its memory-mapped bytes out of host RAM on purpose;
    • torchao-weight encoders;
    • Windows / WSL;
    • integrated GPUs;
    • a forced UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN.
  • Kill switch: UNSLOTH_DIFFUSION_LATE_IMAGE_ENCODER_PIN=0 restores the plan-time prefix. The existing UNSLOTH_DIFFUSION_PARTIAL_ENCODER_PIN=0 also turns it off.

Results

Settings:

  • FLUX.3 klein, transformer_quant=int8, 1024x1024, 16 steps, 3 images per run after one warmup image.
  • Every run is a fresh process with a fresh Studio home.
  • Arms alternate on one VM: before, after, before, after, before, after.
  • Before = the current branch head.
  • Encode = prompt start to denoise start, per image.

Standard Colab T4 (12.7 GB host RAM)

arm load s s/img (median) encode s per image denoise s per image disk read GB per image peak PSS GiB min MemAvailable GiB during renders
before r1 (includes download) 369.2 62.34 26.9 / 26.1 / 23.7 36.2 / 35.2 / 36.0 6.4 / 6.2 / 5.7 8.40 8.23
before r2 184.7 61.99 25.5 / 25.6 / 25.4 35.6 / 35.5 / 35.5 5.9 / 5.9 / 5.9 8.92 8.50
before r3 181.0 63.45 26.9 / 26.8 / 26.8 35.6 / 35.7 / 35.7 6.2 / 6.2 / 6.2 9.11 8.51
after r1 212.3 36.90 0.8 / 0.9 / 1.0 35.2 / 34.9 / 35.2 0.0 8.52 3.42
after r2 212.6 37.04 1.2 / 0.8 / 0.8 35.2 / 34.7 / 35.3 0.0 9.00 3.48
after r3 213.4 36.62 0.8 / 0.8 / 0.8 34.9 / 34.8 / 35.1 0.0 9.15 3.48
  • s/img: 62.3 to 37.0 (median of medians). The before A/A spread is 1.5 s.
  • Load: about 28 s longer. The pin itself (6.0 GiB in 23 to 27 s) reads the encoder from disk once, during the load.
  • Host memory: peak PSS is unchanged. The lowest MemAvailable over the whole run was 3.41 GiB, against 3.74 to 4.02 GiB before.
  • Images: md5s identical in all six runs (bc8107ba, 952ea0be, a8876fe8).
  • Engagement: each after run logs pins up to 6.6 GiB of its offload groups (cap read at pin start) and pinned 6.0 GiB of Qwen3VLForConditionalGeneration host weights ... (onloads waited 0.0 s, registered).

High-RAM Colab T4 (53 GB host RAM), no-regression check

arm load s s/img (median) encode s per image md5
before r1 (includes download) 149.5 37.01 0.7 / 0.7 / 0.7 identical
before r2 54.9 37.39 0.7 / 0.7 / 0.7 identical
before r3 54.7 37.64 0.7 / 0.7 / 0.7 identical
after r1 59.7 37.72 0.8 / 0.7 / 0.8 identical
after r2 54.7 37.56 0.7 / 0.7 / 0.7 identical

On this host the plan pins the whole encoder up front (encoders=True (7696 MiB) against 34590 MiB), so the new branch is never taken: no run logs it. The s/img difference is run-to-run noise.

Tests

  • New: tests/test_image_encoder_late_pin.py, 11 CPU tests. They cover:
    • routing: a plan-time miss defers with the late cap; the kill switch keeps the plan-time prefix; whole pins and the small-host route are unchanged;
    • the cap is read at pin start after a heap trim, earlier pinners' outstanding bytes come off it, and a forced plan or a budget under the minimum pins nothing;
    • a pinner pins the prefix that fits the budget at pin start.
  • On the current branch head these tests fail. With this change they pass, together with tests/test_image_encoder_background_pin.py.
  • Wider suite: every backend test touching diffusion_memory or group offload (14,000+ tests) fails the same 4 tests with and without this change. Those failures already exist on the branch head.

…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.
@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:12:49.462786Z 623cfff 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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fcce34dbad

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

Copy link
Copy Markdown

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

Reviewed commit: fcce34dbad

ℹ️ 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. Keep it up!

Reviewed commit: 623cfff50f

ℹ️ 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-t4 to main November 13, 2026 13:12
@danielhanchen
danielhanchen merged commit 4600152 into main Nov 13, 2026
@danielhanchen
danielhanchen deleted the studio-lowram-te branch November 13, 2026 13:18
danielhanchen added a commit that referenced this pull request Nov 13, 2026
danielhanchen added a commit that referenced this pull request Nov 13, 2026
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…FLUX.3 on 12 GB hosts (#17649)

Stacked on #17644. I swept Studio image and video loads on a standard
Colab T4 (12.7 GB host RAM, 15 GB card) beyond FLUX.3 klein int8. That
turned up three problems; this PR fixes the first two and leaves the
third:

1. **Dense FLUX.3 klein never finishes loading.** With
`transformer_quant=none` the VM stops responding and gives no output for
an hour. The float16 build still converts the 11.1 GB bf16 transformer
on the host, and that conversion peaks at about 1.6x the stored bytes.
2. **Streamed denoiser blocks are re-read from disk on every step.** On
a 12 GB host the image plan never pins the denoiser. The late encoder
pin from #17644 then takes the RAM that is free after the load.
- Dense klein, given a load that works: 52 GB read from disk per image,
217 s/img.
- Qwen-Image-2.1 int8: up to 134 GB read from disk per image, 576 s/img.
Whether it thrashes varies by VM and by prompt.
3. **The Wan2.1 text encoder streams from disk on a first load** (only
measured, not fixed here; see the end).

## Changes

Each change is its own commit:

1. **Small-host route pins its streamed denoiser prefix late.** The
small-host route keeps its int8 denoiser in a memory-mapped scratch file
and never pinned it. It now queues a background pin for the leading
streamed (non-resident) denoiser groups.
- The cap is read when the pinner starts, after the load's freed heap is
returned to the OS.
   - It keeps the usual max(4 GiB, 15%) host reserve.
   - Resident groups spend none of the cap.
2. **Streaming tier gets the same late pins.**
`_apply_streaming_offload` decided its pins only at plan time. Image
loads there now pin the denoiser prefix late, then the encoder prefix
late, as the group tier does. Unchanged:
   - video loads, which have their own background pins;
   - whole pins;
   - the small-host encoders.
3. **A dense float16 FLUX.3 transformer reads as stored when the widened
copy does not fit.**
- It widens on the host only when about 1.6x its stored bytes, plus the
small-host reserve, fits in available RAM.
- Otherwise it reads bf16 as stored and casts each Linear per call, as
the text encoder already does.
   - Each call sees the same float16 weights the widened load holds.
4. **A late denoiser pin that cannot be queued is never fatal.** On the
streaming tier any exception during setup fails the load. The pin is an
optimisation, so a failure now logs and leaves the denoiser unpinned.
5. **The group tier pins the denoiser prefix before the encoders on any
image load,** not only on the small-host route. The encoder's late cap
subtracts only the denoiser groups that still stream.

**Kill switches**
- `UNSLOTH_DIFFUSION_LATE_DENOISER_PIN=0` turns off 1, 2 and 5.
`UNSLOTH_DIFFUSION_PARTIAL_ENCODER_PIN=0` also turns them off.
- `UNSLOTH_DIFFUSION_LATE_IMAGE_ENCODER_PIN=0` now covers the streaming
tier too.
- `UNSLOTH_DIFFUSION_FLUX3_DENSE_STORAGE=0` turns off 3, as does
`UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0`.

A pin only moves a host copy into pinned memory, so the bytes are
unchanged, and it never goes past the existing pin reserve.

## Standard Colab T4 sweep (#17644 head, 1024x1024, encode / denoise per
timed image)

| model / mode | result | load s | s/img | encode s | denoise s | disk
GB/img | peak PSS GiB | min MemAvailable GiB |
|---|---|---|---|---|---|---|---|---|
| FLUX.3 klein int8 | loads | 212 | 37.8 | (0.8-1.2 in #17644) | | | 9.2
| 3.3 |
| FLUX.3 klein fp8 | loads | 349 (incl. download) | 53.3 | | | | 8.9 |
3.7 |
| FLUX.3 klein dense | VM unresponsive, no output for 60 min (two VMs) |
- | - | - | - | - | - | - |
| FLUX.3 klein-base int8 (50 steps, CFG) | loads | 419 | 242.8 | 2.7-3.9
| 238 | 0.2-0.6 | 9.8 | 2.8 |
| Qwen-Image-2.1 int8 (VM 1) | loads | 485 | 576.0 | 29-30 | 544 |
131-134 | 8.8 | 6.9 |
| Qwen-Image-2.1 int8 (VM 2) | loads | 419 | 147.3 (warm-up 396) | 29 |
116 (warm-up 358) | 8.5 (warm-up 81.6) | 10.2 | 6.7 |
| Qwen-Image-2.1-Turbo int8 | loads | 432 | 73.2 | 29 | 42 | 8.3 | 9.8 |
6.5 |
| Wan2.1-T2V-1.3B, 33 frames 832x480, 20 steps | loads | 560 (incl.
download) | 342 s/clip | 90-115 | 222-231 | 13-27 | 9.2 | 4.2 |
| MiniMax-H3-Image | refused before the weights download | - | - | - | -
| - | - | - |

- **Offload tier:** every load took the group tier (`offload=group`),
and Qwen-Image-2.1 took the small-host route. No model reached
`_apply_streaming_offload` on a real T4. I exercised that tier by
capping the card at 7 GiB (see below).
- **MiniMax-H3-Image:** the smallest tier (int8 DiT + int8 encoder)
needs about 46 GB of host RAM and refuses with a clear message after
fetching only configs and the VAE. There is no GGUF / sd.cpp tier for
it.

## Results, standard T4, head-before vs this PR on the same VM

| model / mode | before s/img | after s/img | disk GB/img before / after
| md5 |
|---|---|---|---|---|
| FLUX.3 klein dense, `LATE_DENOISER_PIN=0` vs on (ABAB) | 217.6 / 214.6
| 66.0 / 65.5 | 52 / 4.2 | identical in all four runs |
| Qwen-Image-2.1 int8 | 147.3 (warm-up thrashed: 396) | 140.1 / 140.1 |
8.5 (warm-up 81.6) / 7.3 | identical |
| Qwen-Image-2.1-Turbo int8, VM A | 71.65 / 72.82 | 69.22 / 69.41 | | |
| Qwen-Image-2.1-Turbo int8, VM B | 72.6 / 74.6 / 75.9 | 71.1 / 71.2 /
71.2 | 7.2-8.4 / 6.8-6.9 | identical |
| FLUX.3 klein int8 (the #17644 case) | 37.79 | 37.84 | | (same as
high-RAM) |
| FLUX.3 klein-base int8 | 242.8 | 246.2 | 0.2-0.6 / 0.3-0.6 | identical
|
| FLUX.3 klein int8, card capped at 7 GiB (streaming tier) | 120.2 /
123.2 | 137.5 / 124.4 | | identical (`bc8107ba`, `952ea0be`) |

Notes on these rows:

- **Dense FLUX.3:**
- The head itself never loads dense klein on this host, so the before
arm keeps change 3 and turns off the late denoiser pin with its kill
switch.
- The md5s (`5003c0b3`, `9b896f69`) equal the widened load on a high-RAM
T4, so reading as stored is bit-identical on the GPU.
- **Qwen-Image-2.1:** the gain depends on the VM. Without the pin the
streamed set (5 GB) sometimes stays in the page cache and sometimes
thrashes:
  - On another VM every image read 131-134 GB (576 s/img).
- The fixed tree pins 3.9 GiB of it and ran 140-146 s/img with 7.3-8.3
GB read per image on both VMs where it ran.
- **klein-base:** its logs are identical in both arms (the transformer
is resident, so the new pinner has nothing to pin). The 3 s gap is
single-run variation.
- **Streaming tier:** both pinners ran but read a 0 GiB cap, because the
host was already under the reserve (min MemAvailable 0.7 GiB in both
arms). The change engages there but has nothing to pin, so both arms do
the same work: 7.3 GB read per image and identical images. Denoise times
range from 73 to 104 s within both arms, so this host cannot resolve the
137.5 s run from noise.

## High-RAM T4 (51 GB), head vs this PR

| model / mode | head s/img | this PR s/img | md5 |
|---|---|---|---|
| FLUX.3 klein dense | 43.74 | 43.51 | identical (`5003c0b3`,
`9b896f69`) |
| FLUX.3 klein int8 | 37.95 | 37.98 | identical (`bc8107ba`, `952ea0be`)
|
| Qwen-Image-2.1-Turbo int8 | 30.49 | 30.46 | identical (`6caddcb2`,
`a2821dca`) |

The plan pins every streamed component up front there, so none of the
new code runs.

## Tests

- **New files:**
- `studio/backend/tests/test_small_host_denoiser_pin.py`: routing on
both tiers, kill switches, resident groups skipped, the cap read at pin
start, the encoder cap net of the denoiser's owed bytes, and that whole
pins, video and torchao denoisers are unchanged.
- `studio/backend/tests/test_diffusion_flux3_dense_storage.py`: the host
RAM gate, its kill switches, and that explicit choices are unchanged.
- **Updated:** `test_diffusion_flux3_manual_cast.py`, which checks the
new helper. The float16 manual cast stays bit-identical to the float16
load (`test_diffusion_flux3_half_storage.py`).
- **Wider suite:** every backend test file touching `diffusion_memory`,
group offload, background pins, FLUX.3 or the small-host route.
  - This branch: 15080 passed. The #17644 head: 15059 passed.
- The same four tests fail on both:
`test_the_pin_budget_leaves_the_reserve_free`,
`test_mirrored_base_still_trips_the_flux2_shape_guard`, and the two
`test_integrated_gpu_no_host_pin` checks, with identical messages.

## Not covered

- **Wan2.1-T2V-1.3B:** on a first load in a Studio home the encoder pins
nothing (`_video_exact_pins` keeps the default plan while the cast cache
is written). Its UMT5 then streams from disk on every clip: 90-115 s of
a 342 s clip, 13-27 GB read. I did not change the video route or test a
second load in the same home.
- **Qwen-Image-2.1 encode:** the encoder still streams 8.9 GB from its
file on every prompt, about 30 s per image. After the denoiser pin there
is no room left to pin it.
- **Qwen-Image-2.1 / Turbo with `transformer_quant=none`:** on this host
they take the small-host int8 route. The output is md5-identical to
int8, while status reports `transformer_quant=off`. This is unchanged
here.
- **Streaming tier:** it was exercised only with a simulated 7 GiB card,
where the host had no room to pin. That configuration also runs the host
down to 0.7 GiB MemAvailable without this PR.
- **Not run:** LTX-2.5, L4, A100, ROCm, Windows and macOS.
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