Repository navigation
Studio: split Z-Image guided steps only while the denoiser is compiled or replaying graphs - #14868
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.
|
@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: 94ef9d17fa
ℹ️ 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 compiled_denoiser(denoiser) is not None: | ||
| return True |
There was a problem hiding this comment.
Stop treating failed compilation as engaged
When regional compilation fails on its first call and CUDA graphs are disabled or were not armed, compiled_denoiser() still returns a reason because _unsloth_regional_compile_kwargs and _unsloth_compile_guard remain on the transformer even after the guard clears every compiled submodule. Consequently every subsequent render is classified as compiled and continues issuing two serial eager forwards, preserving exactly the eager slowdown this change is intended to remove; account for the compile guard's error state or verify that a compiled callable remains live.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed: after a first-call compile failure the guard clears the compiled blocks but its marks stay on the transformer, so the check still read the load as compiled. The engagement check now treats a compile guard with a recorded error as eager (unless CUDA graphs are live), with a test for it.
| if armed and slots.get(_COMPILED_ONLY_ATTR) and not _graphs_engaged(pipe, denoiser): | ||
| armed = False |
There was a problem hiding this comment.
Preserve the low-memory path for eager CFG
When an eager resident load is close to its VRAM limit, disabling the split changes a guided step from two serial B-sample forwards to one 2 * B forward, increasing peak activation memory and potentially making a single-image high-resolution render OOM even though the previous split path fit. The outer OOM recovery cannot compensate for this case because diffusion.py immediately re-raises when the chunk already contains one image, so the eager optimization needs either a memory-pressure exception or an OOM retry that re-enables the split.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair point against the current base. An eager guided call now runs batched first, and if that call runs out of memory it retries as the two half-batch calls for the rest of the render, so a render that fit under the split still fits; a test forces the OOM and checks the retry.
| if getattr(pipe, "_unsloth_cuda_graphs", None): | ||
| return True |
There was a problem hiding this comment.
Detect graphs on shared workflow transformers
For Z-Image GGUF/default loads using img2img or inpaint, _workflow_pipe() creates a new pipeline object that shares the transformer but does not copy the root pipeline's _unsloth_cuda_graphs attribute. The default GGUF path compiles only dequantization while CUDA-graph arming is independent, so this check sees neither graph handles nor a compiled denoiser and disables the split even though the shared transformer's graph wrapper is active; guided workflow calls then capture the doubled batch that this feature is meant to avoid. Determine graph engagement from the live denoiser wrapper or the owning pipeline's handles rather than only the pipeline object passed to render().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: from_pipe shares the transformer and its graph wrapper but not the root pipe's handle tuple. Graph engagement is now read from the denoiser itself (any enabled, unpoisoned graph wrapper on it or its blocks), so img2img and inpaint keep the split; covered by a new test.
…ts a failed compile as eager, and splits an eager guided call that runs out of memory [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
…arallel router is active [skip ci]
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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". |
…ided call runs out of memory before splitting [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: 6a1ae6793b
ℹ️ 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".
| router = slots.get("_unsloth_cfg_router") | ||
| routed = router is not None and slots.get("forward") is router | ||
| # A CFG-parallel router needs the halves even eager: it cannot pair one batched call. | ||
| if slots.get(_EAGER_ATTR) and not slots.get(_OOM_ATTR) and not routed: |
There was a problem hiding this comment.
Fall back to batching when the CFG router is unavailable
When the CFG-parallel router has been disabled after replica construction or execution fails, it remains installed in forward, so routed stays true. An eager render therefore bypasses the batched fast path here, run_pair() returns None because disabled_reason is set, and lines 260–262 perform two serial forwards for every remaining guided step and later render. Treat only an enabled router as routed, or return to the batched call when the router is already unavailable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine. A router that already set disabled_reason stayed installed in forward, so an eager render skipped the batched call and then ran the two halves serially because run_pair() returned None. routed now also requires disabled_reason is None and that no background compile eager or capture gate is active (the same check run_pair uses to decline), so a router that cannot pair falls back to the one batched call. Test: test_compiled_only_eager_with_a_disabled_router_runs_batched (fails on 6a1ae67, passes now).
| if getattr(pipe, "_unsloth_cuda_graphs", None): | ||
| return True |
There was a problem hiding this comment.
Ignore graph handles whose recording permanently failed
On a CUDA-graph-only Z-Image load, a failed capture poisons its GraphedForward but leaves the handle in pipe._unsloth_cuda_graphs. This unconditional truthiness check consequently classifies the denoiser as graph-engaged forever, even when there is no compiled denoiser or per-block fallback, so subsequent eager renders continue paying for two serial forwards. Inspect whether a relevant handle or fallback is still enabled and unpoisoned rather than treating the retained tuple as engagement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine. A whole-step capture that failed for good leaves its poisoned handle in pipe._unsloth_cuda_graphs, and the plain truthiness check counted that as engaged. _graphs_engaged now counts a pipe handle only when it is enabled and either not poisoned, or still has a per-block fallback to engage (fallback) or a live fallback_handle. A poisoned GraphedCompiledCall still runs compiled code, and the compiled-denoiser check below catches that. Test: test_compiled_only_ignores_a_poisoned_graph_handle (fails on 6a1ae67, passes now).
| # Eager (compiled_only, nothing compiled or graphed): batched, split only after the batched call ran out of memory. | ||
| eager = bool(slots.get(_COMPILED_ONLY_ATTR)) and not _graphs_engaged(pipe, denoiser) |
There was a problem hiding this comment.
Honor the background compile eager gate
When load-time background compilation is enabled, or deferred compilation engages on generation three, generate() sets diffusion_bg_compile._FORCE_EAGER so that this recording render explicitly bypasses both compiled callables and CUDA graphs. _graphs_engaged() nevertheless sees their installed marks or handles and makes eager false here, causing every guided step in the supposedly eager render to use two serial forwards rather than the faster batched call. Check bg_compile.eager_forced() before classifying the denoiser as compiled or graphed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine. generate() sets _FORCE_EAGER while a background compile is pending, and that covers the zimage_cfg_split_render context. Under that flag the compiled gate and GraphedForward both run eager, but _graphs_engaged still saw the marks and handles and split every guided step. _graphs_engaged now returns False when diffusion_bg_compile.eager_forced() is set, so that recording render stays batched. Test: test_compiled_only_honours_the_background_compile_eager_gate (fails on 6a1ae67, passes now).
…, a poisoned graph handle, or the background compile eager gate
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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]
Two more backend checks fail on `main` (60c7715). Both reproduce on a clean `main` worktree, and in both the test needed to change, not the product. | Check | Introduced by | Fix | |---|---|---| | `studio/backend/tests/test_inference_dispatcher_resilience.py::test_route_llama_streaming_async_clients_disable_proxy_env` (`assert 0 == 5`) | #14546 | That PR builds the five local llama-server clients in `routes/inference.py` through `gated_async_client`. It wraps `httpx.AsyncClient` so that conversation-archive embedding pauses for the request. The AST walk only matched `httpx.AsyncClient(...)`, so it found none. It now counts both spellings and still requires `trust_env=False` on each of the five. It also pins that `gated_async_client` passes its `**kwargs` to the `httpx.AsyncClient` it builds, which is the step that keeps a proxy setting from reaching the local server. | | `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[6]` | #14868 | `test_diffusion_zimage_cfg_split.py` read `diffusion.py` with `read_text()`. That read now passes `encoding = "utf-8"`. | The product side checks out: all five `gated_async_client(...)` calls pass `trust_env = False`, and the wrapper forwards it. ## Verification - `test_inference_dispatcher_resilience.py` and `test_diffusion_zimage_cfg_split.py`: 38 passed. - `tests/test_source_read_encoding.py`: 16 passed. - Sabotage checks, each fails the guard: - removing `trust_env = False` from one of the five calls; - making `gated_async_client` drop its `**kwargs`; - restoring the bare `read_text()`.
… group resident (unslothai#14955) Follow-up to unslothai#14868 (merged into `main`), which gated the Z-Image CFG split on a compiled or graph-replaying denoiser. This PR targets `main` and 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. 1. `install_zimage_cfg_split` treated every `group` policy 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. 2. Even with the split armed, the request guard at generate time priced the guided render as a doubled batch. It then streamed resident groups out "for an oversized request", the split declined on every call, and the batched call compiled anyway. ## Change - `diffusion_zimage_cfg_split`: the `group` policy 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 unslothai#14868's `compiled_only` load, an eager denoiser keeps the batched guided call, so this returns false and the guard keeps pricing it as a doubled batch. - An eager denoiser behind an active CFG-parallel router splits through `run_pair` (unslothai#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`) through `split_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's `DiffusionBackend` (compiled, CUDA graphs). - Each run: guidance off for the first prompt, the same prompt again, a 108-word prompt and a new seed. Then the toggle to guidance 4 (`D_cfg`), back to guidance off, and three more guided renders. - Recompiles are counted from `TORCH_LOGS=recompiles`. - Base is unslothai#14868's head. The batched reference is the same tree with `UNSLOTH_DIFFUSION_ZIMAGE_CFG_SPLIT=0`. All 37 offload groups resident (5999 MiB) in every row: | | batched (base / kill switch) | split (head) | |---|---|---| | CFG toggle: recompiles / new graphs | 3 / 3 | 0 / 0 | | later guided renders: recompiles | 0 | 0 | | split counter after the run | not armed | 16 split, 0 batched | | graph breaks, any render | 0 | 0 | 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 `main` `71d24f7a07`, and a rerun on this branch after merging unslothai#14868's `9369cadf1` (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 unslothai#14868: - Current `main` (`b9bb997a1`), fully resident (policy `none`, 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. - Merging `main` into this branch leaves the 256x256 hashes unchanged, so no newer `main` commit 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_core` on 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: - base (unslothai#14868 head `9369cadf1`): 443 passed, 22 skipped - head (this branch with `9369cadf1` merged in): 448 passed, 22 skipped - no failures on either side These tests fail on base and pass on head: - `test_group_offload_with_every_group_resident_splits` - `test_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_off` - `test_request_guard_prices_an_eager_compiled_only_load_as_doubled` ## Not covered - Z-Image bf16 at the same budget: Automatic places it with streaming groups, so the split stays off and the toggle still costs 2 recompiles there. That is a separate placement question. - img2img and inpaint were not run on the real model. The guard change for them is covered only by the unit tests. - No exclusive-card timing. The recompile and split counts are the result. - Guided parity below 1024x1024 follows the existing split on `main` (above). This PR does not change the split's numerics. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…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.
Problem
The Z-Image CFG split (#14541) runs a guided step as two calls at the guidance-off batch so that turning guidance on compiles and records nothing new. Studio armed it on every resident load, including the
eagerandoffspeed tiers, where the denoiser is neither compiled nor replaying CUDA graphs. There the split saves nothing and only adds a second serial pass through the weights.Eager denoiser timing on B200 (random weights, full 3840 width, 4 main + 2 refiner layers, bf16, 8 interleaved groups after an A/A check, shared GPU so treat as a coarse ratio):
Fix
install_zimage_cfg_splittakescompiled_only. When set,render()splits only while the denoiser runs compiled code (the same detection the CFG batch router uses, plus a torch.compile'd instance forward) or the pipeline replays CUDA graphs. The check runs per render, so a compile engaged after the load still splits from its next render.compiled_only = True. Direct callers keep the old behaviour.On the default tier nothing changes. Tiny Z-Image pipeline through Studio
load_pipeline+generate, new Dynamo graphs and CUDA graph captures per render:Tests
tests/test_diffusion_zimage_cfg_split.py: an eager denoiser keeps the batched guided call (bitwise equal to the plain call) and splits once compiled; every engaged form (regional compile mark, compiled block, CUDA graphs) splits; Studio's load call passescompiled_only = True. All 5 fail on the current main and pass here.tests/test_diffusion_zimage_cfg_split.pyandtests/test_diffusion_cfg_parallel_tier.py: 47 passed.Not covered