Skip to content

Studio images: keep the text encoder resident only while the render fits, and lend it to other loads - #18424

Merged
danielhanchen merged 7 commits into
mainfrom
studio-te-resident-when-fits
Nov 19, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-te-resident-when-fits

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Studio images: re-check text-encoder residency on every render

What this changes

The load already decides where the text encoders go, using the planner's measured peaks. On an L4, both INT8 families keep the encoder on the card today:

family offload tier encoder on the card
FLUX.3 klein INT8 none all 4618 MiB
Qwen-Image-2.1 INT8 group 5265 of 8917 MiB, in resident groups

That placement then held for the whole session. A resident encoder could not make room for a later demand: another process taking VRAM, a dictation or chat model loading next to the image model, or a bigger render.

With this PR, on a discrete CUDA card:

  • After every prompt encode, this render's priced peak plus the planner's slack must fit in live free memory. If it does not, the encoders stream from the host for the denoise. Live free memory is driver free, plus reusable allocator cache, minus the user's VRAM Budget.
    • Whole-resident encoders stream through leaf-level group offload from pageable host memory. This is the same apply the VAE out-of-memory path uses, and it is skipped when host RAM is short.
    • Encoders in resident groups stream through release_resident_groups, which now takes a new encoders_only flag.
  • Before a later encode, streamed encoders come back once they, the render's peak and the slack fit again.
  • A dictation load, or a sized chat or media load, next to an idle image model asks for the encoder memory first. The whole image model is evicted only if that is not enough.

The render's priced peak comes from:

  • Whole-resident encoders: the largest of three figures. These are the measured placement reserve, the learned or seeded peak for this family, quant and tier at the render's size and batch, and the calibrated per-phase row (denoise and decode scaled by pixels, with a tiled decode capped at its tile). A priced LoRA forward is added on top.
  • Resident groups: the planner's own reserve. When the placement has a decode lend, only the denoise part counts, because the decode lend already prices the decode.

The same weights run either way. UNSLOTH_DIFFUSION_TE_RESIDENCY=0 keeps the load's placement for the whole session, as before.

Measurements (Colab L4, base d06c19c vs head, fresh process per run, interleaved, 3 processes per arm)

Steady speed (10 new prompts per process, 1024 px). Per-prompt time does not change. The encoder was already resident on base, so there is no residency saving to gain on these two families.

family arm per-process medians (s) pooled median (s) first prompt (s)
FLUX.3 klein INT8 base 8.194 / 8.054 / 8.050 8.072 15.66 / 15.57 / 15.61
head 8.196 / 8.066 / 8.064 8.084 15.79 / 15.61 / 15.51
Qwen-Image-2.1 INT8 base 18.241 / 18.248 / 18.245 18.243 27.70 / 27.65 / 27.75
head 18.278 / 18.255 / 18.261 18.261 27.56 / 27.74 / 27.63

Peak VRAM in steady renders is identical in both arms:

family torch peak allocated NVML per-process peak
FLUX.3 11992 MiB 12952 MiB
Qwen 14636 MiB 16524 MiB

On head, every steady render's decision was "keep".

Memory scenarios (8 steps). In both scenarios, "another process" is a separate process allocating on the same card.

case family base head
another process leaves 1 GiB free, 1024 px FLUX.3 4.15 s, encoder stays (the render happened to fit) encoder streams (3.3 s), render 7.46 s
Qwen 6.28 s 4520 MiB of groups stream, 6.08 s
an 8 GiB load arrives (head lends first) FLUX.3 9.7 s: the decode runs out of memory, recovers by moving the encoder off, card full (23.0 GB) encoder lent (3.4 s, outside the render), 4.1 s, card 19.4 GB
Qwen the 8 GiB load cannot get its memory (out of memory) 5265 MiB lent, the load gets 8192 MiB, render 6.07 s
next render after it ends FLUX.3 8.25 s encoder back on the card (1.2 s), 5.3 s
Qwen 6.09 s groups back (0.4 to 0.5 s), 6.6 s
2048 px both fits with the encoder resident same, "keep"

Two further results:

  • Outputs are unchanged. Every 1024 px render of the reference prompt hashes the same within each family, in both arms, whether the encoder was resident or streamed.
  • The kill switch reproduces base. With it on, FLUX.3 runs 4.18 s in the squeeze case and 9.7 s in the lend case.

Cost

One case is slower. When FLUX.3 klein's encoder is whole-resident and another process leaves only about 1 GiB free, the render is priced at its calibrated peak (2924 MiB, margin included), against a measured peak of about 950 MiB. The encoder therefore streams, costing 3.3 s in that render and 1.2 s to come back. Base kept it there and happened to fit, with 175 MiB to spare.

Tests

studio/backend/tests/test_diffusion_te_residency.py has 33 CPU tests. They fail on base, where the module does not exist, and pass on head. They cover:

  • the fit decision and slack per placement;
  • the re-check per render at its own size and batch;
  • pricing (reserve, learned peak, calibrated row, LoRA, decode lend);
  • bit-identical streaming and restore, the host RAM refusal, a failed stream, and a restore that runs out of memory;
  • groups that keep releasing after a partial release;
  • install conditions and the kill switch;
  • the lend path for the engine, dictation and the GPU residency free steps;
  • the wiring in diffusion.py.

The 76 related test files show the same failing IDs on head and base. They fail in this environment and are not caused by this change.

Not covered

  • Z-Image, Wan and other cards (T4, 16 GB, B200).
  • ROCm and Windows.
  • Multi-GPU card splits, which are skipped by design.
  • A real dictation or chat load on the GPU: the lend was driven through the engine call those loads use.

Update: lends hand memory to the driver, dictation lends only when short, Windows ROCm reading

  • Grouped encoders: a lend of resident encoder groups now returns the freed blocks to the driver (empty_cache), so the dictation worker, llama.cpp and the free-memory check that decides on eviction can actually use them. Before this, a Qwen co-load still evicted the image model after the lend.
  • Dictation: passes its size (weight files plus 512 MiB of worker context); the encoder moves only when that plus the planner slack does not fit in live free memory. A dictation load beside an image model with room to spare moves nothing, as on main.
  • Free-memory reading: the residency check uses trusted_mem_get_info, the same reading the load planner uses, so a Windows ROCm card that over-reports free memory cannot pull the encoder back over a full card.
  • Unload: keeps its GPU-memory cache invalidation (the new lend method had been inserted between the decorator and unload).

Placement cells (480): the per-render check turns on only on a discrete CUDA / ROCm card with no multi-GPU selection and encoders on the card; MPS, CPU, XPU, unified-memory APUs, layer split, CFG multi-GPU, sequential and model offload, GGUF, sd.cpp and MLX behave exactly as main. The FLUX.3 1 GiB squeeze cost is kept on purpose: the render is priced at its 1024 px decode, the same figure the load planner places the encoder with, and the alternative there is the decode out-of-memory recovery (9.7 s against 4.1 s).

… encoders when the render or another load needs the room

The load places the text encoders from the planner's measured peaks and that placement then held for the whole
session. A resident encoder could not make room for a larger render, for another process that took VRAM, or for a
dictation or chat model loading beside the image model.

Now, on a discrete CUDA card:
- after every prompt encode, the render's priced peak at its own size and batch plus the planner's slack must fit in
  live free memory, else the encoders stream from the host for the denoise (leaf-level group offload for
  whole-resident encoders, release_resident_groups for encoders in resident groups);
- before a later encode they come back once they, the render and the slack fit again;
- a dictation load and a sized chat or media load beside an idle image model ask for the encoders first, before the
  whole image model is evicted.

The same weights run either way. UNSLOTH_DIFFUSION_TE_RESIDENCY=0 keeps the load's placement as before.
… release, and are priced by the denoise phase when a decode lend covers the decode

On Qwen-Image-2.1 (L4) a near-steady render streamed 81 MiB of encoder groups, which then marked the encoders as
streamed and blocked an 8 GiB lend later in the session. A further release or a lend now streams whatever is still
resident, and one restore re-pins all of it. With a decode lend in the placement, the post-encode check prices the
denoise-phase reserve, as the decode is already priced by the decode lend.
…wn fit, priced by the denoise the decode lend leaves

The planner packs resident encoder groups into the room left after its slack, so requiring that slack again before
re-pinning them kept Qwen-Image-2.1's encoders streamed for the rest of the session after one squeeze on an L4.
They now come back when the denoise peak and twice the decode lend's slack fit beside them. Without a phase reserve,
the denoise is priced as the whole-render reserve less what the placement lent to the decode.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-19T05:29:07.992942Z 43acbb5 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 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: d28a82d017

ℹ️ 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 +501 to +502
_apply_group_offloading_packed(apply_group_offloading, module, kwargs, logger)
_pin_vision_embedding_device(module)

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 Update the render grad mode when resident encoders start streaming

When a pipeline loaded with OFFLOAD_NONE has torchao-quantized text encoders, this new path can install streaming hooks without changing its offload policy. _torchao_render_needs_no_grad() still immediately returns false for OFFLOAD_NONE, so subsequent prompt encodes run the newly streamed encoder under torch.inference_mode(). Moving torchao weights in that context triggers the aliasing-check failure that the existing grad-mode helper explicitly avoids for other offloaded pipelines. Make the grad-mode decision account for dynamic encoder streaming, including lending before a render, so a memory squeeze does not break subsequent image generation.

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 the latest push: the residency check records at install whether any encoder holds tensor-subclass (torchao) weights, and _torchao_render_needs_no_grad returns true for a resident (OFFLOAD_NONE) load in that case, so a render that may stream or restore those encoders runs under no_grad like offloaded quant loads. Plain encoders and loads without the check keep inference_mode. Test added; it fails without the change.

Comment on lines +16655 to +16656
@_invalidates_gpu_memory("diffusion unload")
def lend_text_encoder_vram(

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 Preserve GPU-memory invalidation on unload

Inserting the lending method below the existing decorator transfers _invalidates_gpu_memory("diffusion unload") from unload() to lend_text_encoder_vram(), leaving actual unloads undecorated. Neither _unload_locked() nor clear_gpu_cache() invalidates these readings, so ejecting an image model can now leave the GPU display caches reporting its freed VRAM as occupied until their freshness window expires. Keep an invalidation decorator on unload() as well as on the new lending operation.

Useful? React with 👍 / 👎.

… frees the driver memory, dictation lends only when short

The text-encoder lend method was inserted between unload and its
invalidates_gpu_memory decorator, so unload no longer invalidated cached
VRAM readings. Both methods now carry one.

A lend of resident encoder groups left the freed blocks in this process's
allocator cache, where another process (dictation worker, llama.cpp) and
the residency fit check cannot see them; it now empties the cache.

A dictation load streamed an idle image model's encoders even on a card
with room. It now passes its size (weight files plus the worker context)
and the encoders stay when that and the slack already fit.
…ay the load planner does

Windows ROCm over-reports driver free memory (a fresh process sees the card
near empty), so the per-render check could bring streamed encoders back over
a full card, where WDDM spills to host RAM instead of failing. It now uses
trusted_mem_get_info, which is unchanged everywhere else.

[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. Swish!

Reviewed commit: 9236d67ef0

ℹ️ 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. Nice work!

Reviewed commit: 43acbb56ac

ℹ️ 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
danielhanchen merged commit edddefa into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the studio-te-resident-when-fits branch November 19, 2026 19:22
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…treaming without diffusers (#18535)

## Summary

`(Python 3.13, diffusion)` fails on `main` for every PR (seen on #18526
and #18348, neither of which touches diffusion). Four tests, from two
recent merges:

```
FAILED tests/test_diffusion_backend.py::test_apply_loras_quant_unbaked_requires_reload
FAILED tests/test_diffusion_backend.py::test_apply_loras_quant_baked_matrix
    Expected regex: 'Reload the model with the adapter selection'
    Actual message: 'This INT8 build was loaded without LoRA adapters, ... Reload the model with the LoRA selection: on the Images page click Reapply ...'
FAILED tests/test_diffusion_te_residency.py::test_release_streams_and_restore_unhooks_with_identical_outputs
    assert 0 == 4   (release('test') == r.mib)
FAILED tests/test_diffusion_te_residency.py::test_a_restore_that_runs_out_of_memory_keeps_streaming
    assert True is False
```

## Root causes

**LoRA reload refusal (#18420).** #18420 turned this refusal into
`LoraReloadRequiredError` and rewrote its message to name the remedy
(Reapply on the Images page, or `loras` in `/images/load`). The routes
key on the type (`X-Unsloth-Refusal: lora-reload`, `error.code =
"lora_reload_required"`). The two tests still matched the old wording.
The behaviour is intended; the tests pinned prose.

**Encoder residency streaming (#18424).** `EncoderResidency.release()`
streams the text encoders through diffusers' group offloading. The
`(Python 3.13, diffusion)` lane does not install diffusers (the same log
shows `No module named 'diffusers'` skips), so the stream fails,
`release()` correctly keeps the encoders resident and returns 0, and the
two tests that need a real stream fail. The module is right to refuse;
the tests needed diffusers and did not say so.

## Changes

- `test_diffusion_backend.py`: both tests assert
`pytest.raises(LoraReloadRequiredError, match = "Reload the model with
the LoRA selection")`, the typed refusal plus the remedy phrase both
messages share.
- `test_diffusion_te_residency.py`: the two streaming tests are marked
to skip when `importlib.util.find_spec("diffusers") is None`. Only the
absence of diffusers skips: with diffusers installed, a regression in
Unsloth's streaming still fails them. The tests that do not stream (host
RAM refusal, a failed stream putting the encoders back) keep running
everywhere.

Test-only change.

## Testing

- With diffusers 0.43.0 (current release) on a CPU host: `pytest
tests/test_diffusion_te_residency.py tests/test_diffusion_backend.py`:
733 passed, the two streaming tests included.
- Sabotage: raising a plain `LoraSelectionError` instead of
`LoraReloadRequiredError` fails both LoRA tests.
- The no-diffusers lane is the `(Python 3.13, diffusion)` job on this
PR.
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