Repository navigation
Studio: make the image memory plan resolution-aware and stop reserving the text encoder during sampling - #8224
Conversation
…e variant hint, re-check activations at generate time
…d the generate-time activation guard
…che per generation
|
Follow-up: one regression this introduced, now fixed, plus a correction to the description. A text encoder that refuses group offload no longer fails the load. Adding the text encoders to that same all-or-nothing loop quietly widened it. A text encoder is a far less well-trodden target for block-level group offloading than a DiT, and one whose structure diffusers does not recognise can simply refuse. Because the encoders come after the DiTs, that refusal would have arrived with hooks already installed and turned a slow-but-working load into a hard failure, on exactly the small cards this tier exists to rescue. The encoders are now applied one at a time with each failure absorbed: a refusal places that encoder resident instead, which is precisely what happened before this tier existed. The plan's floor becomes optimistic by that encoder's bytes and the load still runs. Each encoder is decided on its own, so one awkward component does not cost the others their streaming. The DiT loop keeps its all-or-nothing semantics untouched, which is now asserted rather than assumed. Ordering was a real choice rather than an oversight. Putting the encoders first would have inverted the risk onto the better-trodden transformer path instead of removing it; making the failure survivable removes it. Five more mutations, all killed: a refusing encoder failing the load again; a refusing encoder left placed nowhere; one refusal aborting the remaining encoders; the DiT loop inheriting the tolerance; and a streamed encoder being placed resident as well as streamed. 47 mutations total, 0 survivors. Correction to the description. It says #8213 "already owns" the unified-memory refusal. #8213 is open and unmerged, so Re-verified after the pre-commit.ci rebase: 347 passed across the three target files, backend suite line set still identical to the merge-base baseline at 86 pre-existing FAILED/ERROR lines, |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7577cc560
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| name, | ||
| exc, | ||
| ) | ||
| module.to(onload) |
There was a problem hiding this comment.
Keep streamed encoders out of the resident fallback
When stream_text_encoders is true, the planner picked this tier specifically because companions + headroom + overhead did not fit but companions - text_encoders + headroom + overhead did. If any text_encoder* refuses group hooks, this fallback puts that encoder back on the GPU after transformer hooks are already installed; on the low-VRAM cards this tier targets, that either OOMs here with no whole-module fallback left or leaves less activation headroom than the plan proved safe. Treat encoder streaming as all-or-nothing for this rescue tier, or fall back before installing partial group hooks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. All-or-nothing is strictly worse here, not safer. By the time the encoders are attached the transformer group hooks are already installed, and diffusers refuses enable_model_cpu_offload once they are, so an encoder refusal under that rule is a hard load failure with no tier left. Keeping that encoder resident can still OOM, but that is the same outcome, reached only after trying, and on the hosts where it does fit the load simply works at the speed it had before this tier existed. The plan's floor becoming optimistic by one encoder's bytes is the cost, and it is the smaller one. The other suggestion, falling back before installing partial hooks, needs to know in advance whether a given encoder accepts group hooks, and the only way to learn that is to attach them.
| elif _group_fits_streamed_te(): | ||
| policy = OFFLOAD_GROUP | ||
| stream_text_encoders = True |
There was a problem hiding this comment.
Use the streamed-encoder tier for balanced mode
This rescue tier is only reachable from auto/fast planning; an explicit memory_mode=balanced still returns plain group offload with stream_text_encoders=False even when group_floor_mib is over budget and group_floor_streamed_te_mib fits. On the 12–16 GB Z-Image cases this change is meant to rescue, selecting balanced therefore still tries to place the text encoders resident and falls back to whole-module offload, making balanced much slower than auto. Let the balanced branch choose streamed text encoders when plain group does not fit but this new floor does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting, as a feature request rather than a bug. An explicit balanced is a request for a named policy, and it does what it says: block-level transformer offload, companions resident, falling back to whole-module when they do not fit. Nothing is placed wrongly and nothing OOMs; the claim is that balanced ends up slower than auto on some cards, which is what choosing a fixed mode over auto means. The rescue tier is a measurement-driven decision and that is exactly what auto is for. Changing what an explicit mode does is a separate call, and worth making deliberately rather than inside a memory-plan bug fix.
# Conflicts: # studio/backend/core/inference/diffusion.py # studio/backend/core/inference/diffusion_memory.py
- The singleton batch floor rests on the OOM backoff halving a failed forward, and under WDDM there is no OOM to catch: the driver serves a device overflow out of system RAM instead, which is the failure mode this guard exists for. Windows now budgets the largest chunk it will run; every other platform keeps the measured batch-32 fast path. - The message quoted the activations while the decision compared activations plus the fixed overhead, so on the reported 15.92 GiB card it printed a smaller number than the budget and then refused. It reports the total now, with the overhead named. - The refusal has its own ValueError subclass, so the OpenAI-compatible route can hand it back as a 400 with the reason instead of sanitising the one message written for the caller into 'Image generation failed.' Every other exception at that boundary is unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7d6d80fb4c
ℹ️ 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".
| batch_size = guard_batch, | ||
| # The hint the load planned with, so the distilled / edit multipliers match. | ||
| family = state.variant_hint, |
There was a problem hiding this comment.
Account for CFG before applying the distilled discount
When a Turbo/distilled model is generated with a CFG-enabling guidance value, the guard still passes only state.variant_hint, so estimate_image_runtime_mib applies its 0.85 discount solely because the model name contains turbo/distilled. That discount is explicitly premised on these variants running without CFG, but generate() accepts arbitrary guidance and forwards it to the pipeline; CFG can increase the live conditioning/latent batch while neither the load plan nor this check sees it. A high-resolution Studio request can therefore pass this new WDDM safety guard with an underestimated requirement. Thread the effective guidance/CFG state into the estimate, or suppress the distilled discount whenever CFG is enabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. estimate_image_runtime_mib takes no guidance and cannot: the load-time plan calls the same function and genuinely does not know what guidance a later request will use, so threading it in here would make the two ends of one comparison disagree, and the guard's second arm is exactly needed <= planned. The 0.85 is one coarse term in a deliberately coarse estimate that is already 8192 MiB scaled by area, with a fail-open on every unknown; a 15 percent margin on a distilled model asked to run with CFG is inside its resolution, not a defect in it. If the distilled multipliers turn out to be wrong for CFG runs that is a change to the estimator's table, worth measuring on its own rather than inferring from the guard.
_streamable_components and _apply_streaming_offload both classify every text_encoder* as leaf_level, and this path handed them the DiTs' block_level kwargs instead. An encoder with no top-level ModuleList has no blocks to group, so block level treats the whole encoder as one unit, which is exactly the residency the streamed-encoder floor was picked to avoid: the plan said leaf and the application said block. The test harness could not see this. _stream_te_kwargs re-installed the fake torch, which mints a fresh stand-in Module class, so the components built beforehand failed isinstance and only the transformer ever reached diffusers; every assertion in those tests was checking one module rather than four. It swaps the hook function now, which is what the existing helper is for.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 67cbde473c
ℹ️ 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".
| if int(needed) + max(0, int(base_overhead_mib)) <= int(budget) or needed <= planned: | ||
| return None |
There was a problem hiding this comment.
Include the onloaded weight peak in the guard
When the active plan uses whole-module CPU offload, this free-memory snapshot is taken while the transformer and text encoders are on the CPU, but the forward subsequently moves one complete component onto the GPU. Comparing only activations plus fixed overhead can therefore pass an oversized request whose activations fit the idle card but whose activations plus the onloaded transformer do not; for example, the cited 3.6 GiB GGUF transformer combined with a moderately enlarged Turbo frame can exceed a 16 GiB card while this condition returns None. On Windows WDDM that restores the host-memory spill this guard is intended to prevent, so the comparison needs to include the peak weight residency implied by the effective offload policy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. This guard is activation-only by construction, and the reason is in its own docstring: weights can be offloaded and activations cannot, so an activation estimate over the free budget is an overrun at every tier, which is what makes the refusal a fact rather than a tuning guess. Adding the onloaded weight peak turns it into a second adjudication of the placement the load already made against safe_device_budget_mib, at generate time, from a snapshot taken while a component is mid-flight. It also fails in the wrong direction: this is a hard 400, and its second arm already exempts everything the load budgeted, so an over-refusal blocks generations that run today. The whole probe fails OPEN on every unknown for that reason. Under-refusing a case the load-time plan accepted is the side I want to be on; if that plan's budget is wrong for model offload then that is where to fix it, and it is not a change this PR should make from the generate path.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
The guard checks one image everywhere except a Windows multi-image chunk, so a refusal almost always means a single image does not fit and reducing the batch cannot change the answer.
|
I went to capture before/after screenshots for this and the comparison says the guard is refusing work that succeeds. Flagging before this merges. Setup: two isolated Studio installs, merge base Left, 2048x2048 generates. Right, the same request is refused with:
Then I measured what that generation actually costs, on the base build, sampling
The generation completed with 17.3 GiB free in total, so its true requirement is at most 17.3 GB and measured around 8.7 GB. The estimate is 29.20 GB. That is roughly 3x high, and it is high in the direction that costs the user the feature: on any card where 2048x2048 works today, this refuses it. Two separate things to look at:
The 1024x1024 control generates on both sides, so this is specifically the large-resolution path. |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
# Conflicts: # studio/backend/tests/test_diffusion_backend.py
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f55d7360e5
ℹ️ 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".
| guard_width, guard_height = _compile_shape_dims( | ||
| workflow, init_pil, width, height | ||
| ) |
There was a problem hiding this comment.
Account for reference-image activations in the guard
For the FLUX.2 reference workflow, _compile_shape_dims returns only the requested output dimensions, while the forward also VAE-encodes the initial image plus up to three additional references and concatenates their latent tokens. Those uploads are not clamped here, and even after the pipeline's per-image preprocessing they can contribute four additional megapixels; nevertheless, a 1024x1024 output produces needed == planned, so the new guard always passes regardless of the reference workload. On the Windows/WDDM scenario this guard is intended to protect, a request with several large references can therefore still spill into host memory. Include the reference-image count/areas in the activation estimate, or impose a combined reference budget before this check.
Useful? React with 👍 / 👎.
| if int(needed) + max(0, int(base_overhead_mib)) <= int(budget) or needed <= planned: | ||
| return None |
There was a problem hiding this comment.
Recheck planned-size requests against the current budget
When another process consumes VRAM after the model was loaded, this unconditional needed <= planned exemption suppresses the guard for every 1024x1024-or-smaller request even if the fresh generation-time snapshot reports almost no usable memory. The load-time plan only proves that this size fit under the earlier snapshot; it says nothing about the current allocation state. On Windows/WDDM, a default-size request in that situation can therefore still spill into host memory instead of producing the intended refusal. Preserve the small-card exemption using the load-time capacity/plan, but do not let it override a shortfall caused by current free memory dropping since the load.
Useful? React with 👍 / 👎.

Fixes #8081. Fixes #8188.
Two reports about the same missing term, pulling in opposite directions, so they have to be fixed together.
estimate_image_runtime_mibscales its activation headroom by pixel area against a 1024x1024 default, but its only caller passedwidth = None, height = None.pixel_scalewas therefore always exactly 1.0 and every image at every resolution was budgeted as one 1 MP frame.video.pyhas always passed real values; image was the odd one out.torch.OutOfMemoryErrorand the job dies cleanly. On Windows WDDM it does not raise at all: the driver satisfies the overflow from system RAM, and the reporter measured about 27 GB held on a 15.92 GiB card with available RAM down to 1.2 GB and the pagefile past 50 GB. No exception, no failed job, just an unusable desktop._group_fits()went false, and a 20-step 1024x1024 image took 48m25s under whole-module offload with only 1m47s of it sampling.Lowering the constant fixes one and worsens the other, so neither issue is fixed by touching it. The constant turns out to be well calibrated; what was missing was everything around it.
Where the reporters were right, and where the numbers need a caveat
Every file and line citation checked out, and the description of the mechanism is correct in both reports.
One number should not be read as a measurement. #8188 gives "headroom actually needed ~13,872 MiB". That is exactly what
estimate_image_runtime_mibreturns at 1088x1920 with the distilled discount applied:8192 * 1.9921875 * 0.85 = 13872. It is the model's own output at the real resolution, not an independent observation of what the run consumed. It is still the right number to plan with, and the fact that it lands on the same figure the reporter derived is a good sign for the estimator, but the estimator has not been validated against a measured peak by this change.Changes
1. A generate-time activation re-check (#8188). Load time genuinely does not know the output resolution, so the load-time call keeps its
width = None. The re-check happens ingenerate(), with the size the forward actually runs at (_compile_shape_dims, so the conditioned workflows are measured from their input image rather than the sliders) against the free device budget. Over budget raisesValueError, which/images/generatealready maps to a 400 with the reason shown. That is the whole point on Windows: there is no OOM to catch there, so an explicit refusal is the only thing that turns a wedged desktop into a message.Deliberately conservative, because a false refusal costs a user work that succeeds today:
UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE=1turns it off.The free reading credits the caching allocator's reclaimable bytes back arithmetically rather than calling
empty_cache(). The load-time settled snapshot flushes, which is right once per load and wrong per image: releasing every cached block sends the next forward back tocudaMallocfor all of its activations.2. Stop counting the text encoder as resident during sampling (#8081). The reporter is right that the encoder runs once, before step 0, and that holding it resident for the whole denoise reserves its bytes for nothing. The proposed route was releasing it after encoding. This does it without any lifecycle surgery:
apply_group_offloadingis applied to thetext_encoder*components too, so they stream like the transformer instead of being placed resident. The planner prices a second floor for that tier (companions - text_encoders + headroom + overhead) and prefers it only where plain group offload does not fit and whole-module offload would otherwise be the answer. Plain group offload keeps the encoders resident exactly as before.One consequence worth being explicit about: diffusers pins every offloaded parameter in host RAM on the copy-stream path. That is a fair trade when group offload was already the plan, but this tier is only ever reached as a rescue from whole-module offload, which pins nothing, on a card small enough that the companions did not fit. Those hosts are not reliably RAM-rich, and #8188's machine got into trouble precisely by turning a device-memory shortfall into unswappable host memory. So the rescue tier passes
low_cpu_mem_usage = True. The encoders it streams run once per call, so the slower unpinned copy is paid once rather than per step. Existing group plans are untouched and still pin.3. The turbo discount now fires (#8081, item 3). The variant hint was built from
repo_id or base or "", which drops the base whenever a repo id exists, which is every GGUF load, and the base is exactly where the marker lives.unsloth/Z-Image-GGUFsays nothing; its baseTongyi-MAI/Z-Image-Turbosays turbo. Both are joined now, deduplicated. Worth about 1.2 GB, and the hint is stored on the load state so the generate-time re-check uses the same multipliers the load did.Before and after, through the shipped planner
Base overhead 2048 MiB, idle card, batch 1. "before" is the same shipped functions called the way main called them (no text-encoder split, no guard).
#8081,
unsloth/Z-Image-GGUFat 1024x1024 (transformer 6451, companions 7820 of which 7560 are encoders). Load-time headroom 8192 before, 6963 after, because the turbo discount now fires.#8188,
unsloth/Z-Image-Turbo-GGUFQ4_K_S at 1088x1920 (transformer 3600, same companions). Activations at that size: 13,872 MiB.Neither fix reintroduces the other: at 1024x1024 nothing is ever refused, at any card size, and at 1088x1920 the cards that cannot hold the activations are refused with a message rather than left to WDDM. A discrete CUDA target at the default resolution keeps its exact previous plan on every card size tested, and passing no split reproduces the previous decision by construction.
Composing with #8213
That PR sizes a unified-memory load from
model_dense_mib + base_overhead_mibagainstsafe_device_budget_mib, deliberately excluding the soft runtime headroom. None of those three terms move here: the split adds a new term and a new floor and leaves the existing ones alone, which is asserted rather than argued. The generate-time guard skips unified memory entirely, so the two refusals never overlap.The open question, partly settled
#8188 asks whether the ~14 GB of non-local memory is caching-allocator bytes that WDDM placed in system RAM, or pinned host buffers from
enable_model_cpu_offload.Not settled, because that needs the Windows ROCm card to sample
torch.cuda.memory_reserved()against the live performance counter, and I do not have one. What can be settled from the source is one half of it:enable_model_cpu_offloadgoes through accelerate'scpu_offload_with_hook, which contains nopin_memorycall anywhere. Diffusers' GROUP offloading does pin, but the reported run loggedoffload=model. So on that specific run there were no pinned host buffers from the offload path, which points at the allocator rather than at pinning. That is an inference from the code, not a measurement, and it does not generalise to the group tier, which is exactly why the new rescue tier declines to pin.Everything here is scoped to be correct either way: the guard bounds the request before allocation rather than trying to bound the allocator, so it does not depend on which pool the overflow would have come from.
Tests
79 new assertions across
test_diffusion_memory.pyandtest_diffusion_backend.py, covering the estimator's scaling, every skip and fail-open path of the guard, its message contents, the exact numbers from both reports, the two floors, the applier, the variant hint, the pinning decision, and back-compatibility with no split for a matrix of card sizes.42 mutations, all killed, none surviving. Among them: the guard never refusing; the guard dropping its planned-resolution floor, its unified skip, its CUDA-only skip, its unknown-free skip, its env override, its base overhead or its batch term; the raiser raising RuntimeError instead of ValueError; the generate call site removed, measuring the sliders instead of the image, budgeting the whole chunk, or dropping the load's hint; the streamed-encoder tier never being reached, or being preferred over plain group; the streamed floor computed without a split or losing its clamp; the applier ignoring or unconditionally applying the flag; the rescue tier pinning host RAM, or the unchanged tier silently unpinning; the reclaimable snapshot no longer crediting cached blocks, losing its capacity clamp, failing closed, or applying off CUDA; and the variant hint reverting to picking one repo id.
Backend suite line sets are identical to the merge-base baseline (86 pre-existing FAILED/ERROR lines either side, 43 more tests passing).
hub/tests304 passed.Not done
No Windows ROCm hardware here, so the WDDM behaviour itself is reproduced from the report, not observed. The refusal path is exercised through the planner and through
generate(), on CUDA and in unit tests, not on the card that reported it.