Repository navigation
Studio images: keep the text encoder resident only while the render fits, and lend it to other loads - #18424
Conversation
… 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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| _apply_group_offloading_packed(apply_group_offloading, module, kwargs, logger) | ||
| _pin_vision_embedding_device(module) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| @_invalidates_gpu_memory("diffusion unload") | ||
| def lend_text_encoder_vram( |
There was a problem hiding this comment.
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]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…nders under no_grad [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…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.
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:
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:
release_resident_groups, which now takes a newencoders_onlyflag.The render's priced peak comes from:
The same weights run either way.
UNSLOTH_DIFFUSION_TE_RESIDENCY=0keeps 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.
Peak VRAM in steady renders is identical in both arms:
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.
Two further results:
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.pyhas 33 CPU tests. They fail on base, where the module does not exist, and pass on head. They cover: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
Update: lends hand memory to the driver, dictation lends only when short, Windows ROCm reading
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.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).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).