Repository navigation
Studio: keep the Z-Image CFG split on when group offload leaves every group resident - #14955
Conversation
…ing denoiser The Z-Image CFG split exists so turning guidance on compiles and records nothing new. On the eager and off speed tiers there is no graph to keep, and the two serial calls are slower than one batched guided call at small sizes (B200 eager denoiser: about 2x at 256px, 1.3-1.5x at 512px, parity at 1024px). Studio now arms it compiled_only: each render checks whether the denoiser runs compiled code or replays CUDA graphs, so a deferred compile still splits from its next render.
…ts a failed compile as eager, and splits an eager guided call that runs out of memory [skip ci]
…up is resident A Z-Image load that fits under group offload keeps all its offload groups resident, but the CFG split treated any group policy as streamed and stayed off. The first guided render then recompiled the denoiser three times at the doubled batch. The split now arms when the stream state reports no streamed group, and the request guard sizes a split guided render at the guidance-off batch so it does not stream resident groups out and fall back to the batched call. A compiled_only load whose denoiser runs eager keeps the batched guided call, so the guard still prices it as a doubled batch.
…arallel router is active [skip ci]
…nslothai/unsloth into studio-zimage-cfg-split-resident-groups
…ided call runs out of memory before splitting [skip ci]
…, a poisoned graph handle, or the background compile eager gate
…nslothai/unsloth into studio-zimage-cfg-split-resident-groups # Conflicts: # studio/backend/tests/test_diffusion_zimage_cfg_split.py
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b585625113
ℹ️ 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 ( | ||
| guard_cfg is not False | ||
| and workflow in ("txt2img", "img2img", "inpaint") | ||
| and guided_runs_at_guidance_off_batch(state.pipe) |
There was a problem hiding this comment.
Price CFG after split-declining state changes
This eligibility check runs before both release_resident_groups and the AUTO maybe_toggle_step_cache call. For an all-resident group-offloaded Z-Image, a positive extra_mib can demote a transformer group; alternatively, a request of at least 20 effective steps can enable FBCache after the guard. Either change makes _declined_now reject the split, so the denoiser runs the doubled CFG batch even though the guard priced and released memory for only the guidance-off batch. On a tight calibrated placement this can cause an otherwise preventable OOM, so split eligibility must be determined after these mutations or the request must be repriced as CFG when they can invalidate it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, this was a real under-reservation. The guard read _declined_now before either mutation, so a positive extra_mib could release transformer groups (text encoders go first, then the denoiser from the last block) and an AUTO FBCache could engage after the guard; both decline the split and the doubled call then ran on a guidance-off price.
Fixed in 4804900:
- The guard now goes through
split_aware_request_extra(pipe, cfg, workflow, price, step_cache=...). It prices the guidance-off batch only when that needs nothing released (extra <= 0). Any positive split price is repriced at the doubled batch, so a release that demotes denoiser groups is always covered by the batched call it causes. - The AUTO cache decision is predicted before the guard:
strength_applied,denoise_stepsandauto_cache_stepsmoved above it (same inputs, nothing in between reassigns them), andauto_step_cache_mode(cache_steps)is passed asstep_cache. When the toggle will engage FBCache, the request is priced doubled. An already engaged cache was handled before through_declined_now.
Tests: test_request_guard_reprices_doubled_when_the_split_would_be_declined (positive split price -> (True, 900), step_cache=True -> doubled, live _unsloth_step_cache -> doubled) and test_studio_guard_passes_the_auto_step_cache_prediction (the prediction comes before both the guard call and maybe_toggle_step_cache). Both fail on b585625.
| guard_cfg = None | ||
| if ( | ||
| guard_cfg is not False | ||
| and workflow in ("txt2img", "img2img", "inpaint") |
There was a problem hiding this comment.
Include plain upscale calls in split-aware pricing
For both hires refinement and the user-facing Upscale workflow, the code above sets workflow = "upscale" and runs fam.img2img_pipeline_class, so Z-Image still reaches the same plain, split-capable transformer call as img2img. Excluding upscale here leaves guard_cfg true; on a fully resident group-offload load, the doubled estimate releases transformer groups, _declined_now then sees streaming, and the guided call stays batched and recompiles—the same feedback loop this change prevents for the other plain pipelines.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Yes. Hires refine and the Upscale workflow both run fam.img2img_pipeline_class, so Z-Image reaches the same plain (x, t, cap) transformer call that _halves splits. Leaving upscale out kept the doubled price, and that started the release -> decline -> recompile loop again.
Fixed in 4804900: the allowed workflows are now SPLIT_PRICED_WORKFLOWS = ("txt2img", "img2img", "inpaint", "upscale") in diffusion_zimage_cfg_split.py. Controlnet and the conditioned workflows still price doubled. Upscale follows the same rule as the others from the P1 fix: it gets the guidance-off price only when that needs nothing released.
Test: test_request_guard_reprices_doubled_when_the_split_would_be_declined covers upscale with the guidance-off price and controlnet with the doubled one. It fails on b585625.
| if not isinstance(state, dict): | ||
| return True |
There was a problem hiding this comment.
Recognize the resident-transformer group tier
When the planner selects group offload with stream_transformer=False, _apply_group_offload streams only the text encoders and leaves the transformer fully resident and unhooked. That transformer never receives _unsloth_stream_state, so this branch classifies it as streaming and every guided call remains batched, preserving the CFG-toggle recompiles this change is intended to eliminate. This is a normal planned tier when the transformer fits after moving the text encoders, so the check should distinguish a transformer with no offload groups from an unknown residency record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right. With stream_transformer=False, _apply_group_offload streams only the text encoders and installs no groups on the transformer, so it never gets _unsloth_stream_state. Treating a missing record as "streaming" kept that tier batched.
Fixed in 4804900: when there is no residency record, _groups_stream now asks diffusion_memory._offload_groups whether the transformer has offload groups. No groups means the resident-transformer tier, so the split stays armed. Groups with no record, or an unknown answer (the probe raising), still count as streaming. A transformer that hook_resident_denoiser hooks later gets its record from _keep_groups_resident, so later releases are still seen.
Tests: test_group_offload_resident_transformer_tier_splits (group policy, bare transformer: guided calls split and compile nothing new) fails on b585625. The existing "no record" cases now model a hooked transformer.
…AUTO FBCache would decline it, covers upscale, and splits the resident-transformer group tier [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4804900820
ℹ️ 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".
| # inpaint) shares the denoiser but opens no cache_context, which the FBCache hooks need. | ||
| from .diffusion_autoopt.runtime import auto_cache_steps | ||
| cache_steps, runner_reason = auto_cache_steps(state.pipe, pipe, denoise_steps) | ||
| auto_step_cache_on = auto_step_cache_mode(cache_steps) is not None |
There was a problem hiding this comment.
Account for a pending AUTO cache disable
When a previous long render left FBCache active but this request predicts it will be disabled—such as a short img2img/upscale render or a runner without cache_context—auto_step_cache_on is false while guided_runs_at_guidance_off_batch() still sees the currently installed _unsloth_step_cache and rejects split-aware pricing. On a tight group-offload placement, the resulting doubled estimate can release transformer groups; maybe_toggle_step_cache() then disables the cache, but those streamed groups still decline the split, recreating the CFG recompilation/residency loop this change is intended to prevent. Eligibility should use the predicted post-toggle cache state rather than the current marker.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 96a732b.
The direction here is over-reservation, not under-reservation: an FBCache marker left by a previous long render makes guided_runs_at_guidance_off_batch() report the batched call, so the guard prices the doubled batch while the AUTO toggle is about to disengage the cache. Nothing OOMs, but on a tight group placement that doubled estimate can release transformer groups, and the streamed groups then decline the split, which is the release / recompile loop this PR is meant to stop.
Rather than having the pricing ignore the marker (which would under-reserve if the disable fails and the cache stays hooked), the AUTO path now disengages the cache before the guard whenever the prediction is off (auto_step_cache_mode(cache_steps) is None, which already covers short img2img / upscale and runners without cache_context). The guard then reads the real post-toggle state: a successful disable gets split-aware pricing, a failed or unverified disable keeps the marker and the doubled price. The existing toggle after the guard becomes a no-op that just updates transformer_cache status.
Test: test_studio_guard_disengages_a_pending_auto_cache_before_pricing (fails on 4804900).
| if slots.get(_COMPILED_ONLY_ATTR) and not _graphs_engaged(pipe, denoiser): | ||
| return False |
There was a problem hiding this comment.
Honor active CFG routing when pricing eager renders
For an eager compiled_only Z-Image with an active CFG-parallel router, the render path intentionally still splits and sends the halves through run_pair, but this early return reports a doubled batch merely because no compiled graph is engaged. On the hookless resident-transformer group tier where CFG-parallel is eligible, that can make the request guard unnecessarily release partially resident text-encoder groups and stream them during prompt encoding, negating part of the multi-GPU performance benefit. Apply the same active-router exception used by the call path when deciding the priced batch size.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in 96a732b.
Same direction as the other one: an eager compiled_only render behind an active CFG-parallel router already splits through run_pair, so pricing it doubled only over-reserves, but that can release resident text encoder groups for no reason on the resident-transformer group tier.
The eager decision now lives in one helper, _eager_now() (compiled_only, nothing compiled or graphed, and no active router, using the same _routed_now() predicate as the call path, including the background compile eager / capture gate). Both guided_runs_at_guidance_off_batch() and render() use it. render() takes that decision once at entry, so a render priced at the guidance-off batch keeps splitting even if the router disables itself mid-render (replica failure); the halves then run sequentially on the primary instead of falling back to the doubled batched call, so the pricing never under-reserves.
Test: test_eager_render_behind_an_active_router_is_priced_and_run_split (fails on 4804900).
…request guard and prices an eager routed render at the guidance-off batch [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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/core/inference/diffusion_zimage_cfg_split.py # studio/backend/tests/test_diffusion_zimage_cfg_split.py [skip ci]
|
@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". |
[skip ci]
`pre-commit.ci - pr` is failing on new PRs (for example #14954 and #14955, both queued after the last format fix) because `unsloth/models/speculative.py` on `main` is not formatted. #14912 left a blank line after the function-local import in `_drop_stale_head`, and the pinned `ruff-format-with-kwargs` hook (ruff 0.6.9) removes it. The hook runs over every file, so every PR inherits the failure. This is format only: - the AST is identical before and after; - re-running `scripts/run_ruff_format.py` over every Python file changed on `main` since the last format fix leaves nothing else to change.
…n the split-aware guard call in the source tests The pre-guard disable now hands its result to the post-guard re-check instead of calling maybe_toggle_step_cache twice. The cfg-off and unpriced-reference source tests check the split-aware guard call that forwards guard_cfg to the pricer. [skip ci]
|
@codex review |
…it-resident-groups # Conflicts: # studio/backend/core/inference/diffusion.py [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
…mage_cfg_split (#15040) `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding` fails on `main` again, for example in `Repo tests (CPU, rest)` on #15033: ``` studio/backend/tests/test_diffusion_zimage_cfg_split.py:551: read_text() studio/backend/tests/test_diffusion_zimage_cfg_split.py:748: read_text() ``` #14955 added two more reads of `diffusion.py` with the platform default encoding to the same test file #15003 fixed earlier. Both now pass `encoding = "utf-8"`. ## Verification - On `main`: `-k checked_in_file_reads` gives 1 failed, 15 passed. - On this branch: 16 passed. - `studio/backend/tests/test_diffusion_zimage_cfg_split.py`: 35 passed.
…er (unslothai#15057) ## Summary Since unslothai#14868, a guided Z-Image render that records inputs for a pending background compile runs the guided call batched at 2B. The background compile then builds a 2B graph. Every later compiled render splits guidance into two batch-B calls, finds no B graph, and compiles every block inline. That is the compile background compile exists to hide. unslothai#14955 inherits the same rule through `_eager_now`. This PR makes the recording render split, the same way the compiled renders will, so the recorder stores B inputs and the background compile builds the graph that later renders replay. ## Details - `diffusion_bg_compile.recording(module)` is a new helper. It is True only when the call is eager-forced, not under `no_record()`, and a `BackgroundCompile` hooked on that module is still `recording` with room for more samples (`BackgroundCompile.wants_samples()`). - `_eager_now` in `diffusion_zimage_cfg_split.py` no longer treats such a render as eager, so the render splits. `guided_runs_at_guidance_off_batch` reads the same function, so the request guard prices the recording render at the guidance-off batch, matching how it now runs. - Unchanged: - Renders under the eager gate while the compile already runs in the background (state `compiling`) record nothing, so they stay batched. - The hires second pass (`no_record()`) also stays batched. - The plain eager tier keeps the batched call, as unslothai#14868 intended. - Pixels: the recording render now produces the split output, which is what it produced before unslothai#14868. Each half is bit-equal to running that branch alone, and it matches the batched call within the existing split-vs-batched tolerance (`atol=1e-5, rtol=1e-4`). New dynamo graphs in the first compiled guided render after the background replay. The setup is the real diffusers `ZImageTransformer2DModel` with a tiny config, Studio's per-block `torch.compile(dynamic=True)`, the real `BackgroundCompile` recorder and the `_rebuild` replay: | tree | samples recorded | new graphs in the next compiled render | |---|---|---| | main | 1 x batch-2 (two latents, t of shape `(2,)`) | 3 (every block kind recompiles) | | this PR | 2 x batch-1 `(16, 1, 8, 8)` | 0 | ## Tests - New `test_background_compile_recording_render_splits_and_records_the_compiled_shape`. It records under a real `BackgroundCompile`, replays like `kick()`, then runs a compiled guided render and asserts: - 0 new graphs; - B-shaped samples; - guidance-off pricing; - outputs within tolerance of the batched call. It fails on main (`assert (6 - 3) == 0`) and passes here. - `test_compiled_only_honours_the_background_compile_eager_gate` now asserts the corrected rule: eager-forced with nothing recording (no recorder, or one already `compiling`) stays batched and records nothing, and a compiled render splits. - `studio/backend`, `python -m pytest -q -p no:cacheprovider`: | test file | result | |---|---| | `tests/test_diffusion_zimage_cfg_split.py` | 36 passed | | `tests/test_diffusion_cold_start.py` | 39 passed | | `tests/test_diffusion_regional_compile.py` | 17 passed | | `tests/test_diffusion_block_graph.py` | 40 passed, 18 skipped | | `tests/test_diffusion_speed.py` | 223 passed | | `tests/test_diffusion_vae_oom.py` | 114 passed, 2 skipped | | `tests/test_diffusion_gguf_compile.py` | 1 skipped | - Not measured: the wall-clock seconds saved on a real Z-Image checkpoint on GPU, and the batching speed the one recording render gives up.
Follow-up to #14868 (merged into
main), which gated the Z-Image CFG split on a compiled or graph-replaying denoiser. This PR targetsmainand only carries the changes on top of it.Summary
Z-Image-Turbo int8 on a 12 GiB budget loads under group offload, and all 37 of its offload groups stay pinned resident on the card. Even so, the first guided render after a guidance-off render (a CFG toggle) recompiled the denoiser 3 times. The Z-Image CFG split exists to prevent exactly that: it runs each guided step as two calls at the guidance-off batch. It stayed off here for two reasons.
install_zimage_cfg_splittreated everygrouppolicy as a streamed denoiser and declined to arm. Group offload only streams when some groups are not resident. At this budget the measured placement keeps the whole int8 / fp8 transformer resident. Only the prompt encode streams part of it, and that part is pinned again before step 0.Change
diffusion_zimage_cfg_split: thegrouppolicy now arms the split. On each call it checks the denoiser's_unsloth_stream_state. If any group is streamed, or there is no residency record, the call stays batched. Streaming and sequential offload still decline as before.guided_runs_at_guidance_off_batch(pipe): returns true when the split is armed and nothing declines it at that moment. On Studio: split Z-Image guided steps only while the denoiser is compiled or replaying graphs #14868'scompiled_onlyload, an eager denoiser keeps the batched guided call, so this returns false and the guard keeps pricing it as a doubled batch.run_pair(Studio: split Z-Image guided steps only while the denoiser is compiled or replaying graphs #14868), so it is priced at the guidance-off batch, and it keeps splitting for the rest of that render even if the router gives up mid-render.diffusion.py: the request guard sizes such a guided render like a guidance-off one (cfg=False) throughsplit_aware_request_extra. This applies only to the txt2img / img2img / inpaint / upscale pipelines, because a control call carries kwargs that the split leaves batched. When the guidance-off price only fits after releasing groups, or an AUTO FBCache will engage after the guard, the split would be declined, so the doubled batch is priced instead. A pending AUTO cache that the toggle will turn off is disengaged before the guard runs.Evidence
Setup: real
Tongyi-MAI/Z-Image-Turbo, int8 transformer, card capped at 12 GiB, loaded through Studio'sDiffusionBackend(compiled, CUDA graphs).D_cfg), back to guidance off, and three more guided renders.TORCH_LOGS=recompiles.UNSLOTH_DIFFUSION_ZIMAGE_CFG_SPLIT=0.All 37 offload groups resident (5999 MiB) in every row:
Wall times come from a heavily shared host and are left out. On an earlier, quieter run the toggle went from 32.1 / 28.6 s to 2.97 / 1.36 s.
Parity
The A/A floor is 0: repeated loads of the same tree, in one process and across processes, give the same sha256 on every render.
At 1024x1024 the split is bit-identical to the batched call. All 9 renders, including the 4 guided ones, have the same sha256 with the split on and with the kill switch set. The hashes also match a run of the same change on
main71d24f7a07, and a rerun on this branch after merging #14868's9369cadf1(16 split, 0 batched, 0 recompiles on the toggle).At 256x256, guided renders differ from the batched call (PSNR 27.8 to 38.0 dB, same composition). Guidance-off renders stay identical. This is not from this PR or #14868:
main(b9bb997a1), fully resident (policynone, where the split already runs today), split vs kill switch at 256x256: the same kind of gap, PSNR 29.3 to 39.5 dB on the 4 guided renders, 0 on the rest.maininto this branch leaves the 256x256 hashes unchanged, so no newermaincommit closes it.The module docstring already describes this: a single unmasked sample can pick different attention / GEMM tiles than the masked pair. At 256x256 the sequence is short enough for the batch size to change that pick; at 1024x1024 it does not.
A second load in the same process placed only 25 of 37 groups resident. The split then declined on every call and kept the batched call (0 split), as intended.
Unit tests,
temp/venv_coreon CPU, run with the split, CFG batch / sync / parallel tier, Z-Image fused, memory, predownload memory guard, accuracy defaults, control capabilities, learned peaks and multi-GPU test files:9369cadf1): 443 passed, 22 skipped9369cadf1merged in): 448 passed, 22 skippedThese tests fail on base and pass on head:
test_group_offload_with_every_group_resident_splitstest_group_offload_while_groups_stream_keeps_the_batched_call(no residency record, 3 streamed groups, an unreadable count)test_request_guard_sizes_a_split_guided_render_as_guidance_offtest_request_guard_prices_an_eager_compiled_only_load_as_doubledNot covered
main(above). This PR does not change the split's numerics.