Repository navigation
Studio diffusion: block-offload re-pins land at the addresses the step graph recorded - #14765
Conversation
…ss renders over a stable device range With memory_mode=low_vram the denoiser's onloads now land in one CUDA virtual address range reserved for the load (driver VMM). Each onload maps new physical memory there and copies the host weights in; each offload syncs, unmaps and releases it, so the text encoder and VAE get the VRAM back as before. The weights sit at the same addresses on every render, so the step graph recorded on render 1 replays on renders 2+ with no new capture. Plain dense weights only; any other parameter type keeps today's eager step. UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0 turns it off.
…model offload memory_mode=low_vram on a compiled tier stores the denoiser as torchao Int8Tensor weights, which the keep-host-weights offload skipped: every render copied them back to fresh pageable host memory and uploaded them again from there (FLUX.2-klein 4B: 0.5 of 4 GiB pinned, every onload paged). Wrapper weights whose inner tensors are plain are now kept like dense ones: the offload swaps the parameter back onto its kept host tensors (no device-to-host copy), and their inner tensors are pinned on the first onload into the same shared chunks.
…able offload range The compiled low_vram tier quantizes the denoiser to torchao int8, so the stable range refused it and the step stayed eager. A wrapper weight whose inner tensors are plain now has each inner tensor placed in the range and is rebuilt over them, swapped in as Module.to moves it; the offload swaps it back onto its kept host tensors as before.
…ooking accelerate's remove_hook_from_module drops instance-level to overrides, and diffusers re-hooks model offload before every render, so the range served only the first onload and later renders recorded the step again. A forward pre-hook puts the override back before the hook's pre-forward onloads the module. The tests now re-hook between renders, as diffusers does, and read torchao weights without the helpers under test.
…, and every registration of a shared buffer offload_placement() now runs the capture-safety refusal before it attaches the stable range, and detaches the range when the placement or its graph handle cannot be built, so an eager denoiser keeps the stock onload (no instance to, no re-install hook, no per-offload card sync). A buffer registered under several names or submodules is now placed for every registration. Module.to() moves each registration on its own, so after an offload they come back as separate host copies; every registration name maps to the one slot, equal copies share one placed tensor again (the graph's placement fingerprint stays the same), and copies that diverged keep the stock move. [skip ci]
…p graph recorded On the group-offload tier the prompt encode streams resident denoiser groups out and pins them back before step 0. The stock re-pin copies each weight into a new caching-allocator block, so the whole-step CUDA graph recorded on an earlier render saw new addresses and recorded again on the next render of an already-captured shape (about 1.7 to 2.8 s on Z-Image-Turbo int8 at a 12 GiB cap), on every render that encodes a new prompt. Once the step graph is armed on a block-offloaded denoiser, each group the encode release streams gets its own CUDA VMM range at its first re-pin. A release unmaps the physical memory, so the encoder gets the VRAM back as before; the next re-pin maps new memory at the same addresses and copies the host weights in, so the recorded step keeps replaying. Plain and torchao wrapper weights are placed; anything else keeps the stock move. The learned-peak probe counts bytes mapped in stable ranges, so the render that first moves groups there does not read low. Opt out with UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0. Status reports the ranges under stable_repin.
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. |
# Conflicts: # studio/backend/core/inference/diffusion_cuda_graph.py # studio/backend/core/inference/diffusion_stable_arena.py
…new layout, roll back a failed map - A poisoned or freed graph handle can never replay its recording, so its placement stops paying for stable addresses: a model-offload module gets its stock onload back (detached mid-render, the range closes on the offload that moves the weights out, never left mapped), and a block-offload denoiser's later re-pins move the stock way. - A model-offload range whose module gained or reshaped a weight on the host since the layout was fixed is laid out again at the next onload, instead of mapping the stale range in full while those weights move beside it at new addresses every render. - VmmArena.map unmaps and releases the physical memory when wrapping the range in a tensor fails, so a failed map leaves the arena unmapped and retryable and the caller's stock fallback holds the only copy. [skip ci]
…l back a failed re-pin The block-offload group ranges get the same two guarantees as the model-offload range: - A released group whose host tensors changed since its range was laid out (a LoRA load or unload, a dtype or shape change) gets a fresh range at the next re-pin, instead of mapping the stale one in full while the changed weights move the stock way beside it at new addresses every re-pin. A range that still holds weights is reused. - A re-pin into the range that raises after mapping it unmaps the range before the group moves the stock way, so the fallback never pays for two copies of the group. [skip ci]
…n, and a removed weight rebuilds the model arena [skip ci]
…r mark, not what is still mapped at the end
… no per-block fallback records [skip ci]
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
… re-pin range is released by the caller [skip ci]
…code under block offload (#14777) ## Summary On the group-offload and streaming tiers, the prompt encode streams resident denoiser groups out so the text encoder fits, then pins them back. Its pre-hook called `torch.cuda.empty_cache()` after every release, so it ran on every new prompt. Each call is a device sync plus a return of every free cached segment to the driver, and the encoder then pays fresh cudaMallocs for its activations and streamed weights. A stack sampler on Qwen-Image-2.1 at an 8 GB cap put 73% of the render thread's time inside that call on a busy host. The flush is not needed for the freed room to reach the encoder. The encoder allocates from the same caching allocator. An allocation that finds no free block releases cached segments to the driver and retries before it raises out of memory. That includes an allocation on the copy stream, which cannot take the default stream's free blocks, and it holds under the per-process fraction cap too. One case still needs a flush. When the step graph records again (a block-offload re-pin that moves the resident weights), the dropped graph pool's segments stay reserved until something empties the cache. Without any flush, Z-Image-Turbo int8 at a 12 GiB cap went from 10186 to 12178 MiB reserved over four re-records. The graph layer now counts dropped shared pools, and the encode release empties the cache only when one was dropped since its last flush. A load whose graph replays never flushes here. ## Results Emulated caps (allocator fraction plus `mem_get_info`), 1024x1024, 8 steps. Every render after the first encodes a different prompt. Encode times are ratios only, because the host is noisy. | | empty_cache per new-prompt render, main | this PR | images vs main | peak reserved vs main | |---|---|---|---|---| | Qwen-Image-2.1, 8 GB cap | 1 | 0 (1 once after a failed capture dropped its pool) | identical at every render | equal (7952 to 8022 MiB) | | Z-Image-Turbo int8, 12 GiB cap | 1 | 1 (the step graph re-records on every new prompt here, so a pool drops every render) | identical at every render | equal (10186 / 9522 MiB) | - Qwen-Image-2.1 encode wall time for renders without a flush is about 1/50 of main's on this host. Most of that is the host's slow empty_cache, not the cudaMallocs. - No out-of-memory errors in any arm. Graph vs no-graph images in the same process are identical in every arm. The main gain is together with #14765 (stable re-pin ranges): there the step graph replays, so no pool drops. On a scratch merge of both branches: - Z-Image 12 GiB: 0 flushes per new-prompt render, 0 captures, images identical to main. - Qwen-Image-2.1 8 GB: the emulated cap makes the range's cuMemCreate fail when the allocator's cached blocks leave no room, exactly as a real 8 GB card would. The range then empties the cache and retries, so it flushes once per render only when that happens. There are no captures and no out-of-memory errors, and images are identical to main. ## Tests `test_encode_release_does_not_flush_the_allocator_per_prompt` counts `empty_cache` over three encodes (0 here, 3 on main) and checks a pool drop triggers exactly one flush. It fails on main and passes here. `test_diffusion_measured_placement.py` and `test_diffusion_offload_cuda_graph.py`: 198 passed.
…on the first load (#14866) ## Summary On its first load on a machine, an automatic FLUX.2 Klein that does not fit resident streams every block on every step, even when the int8 transformer would fit the card whole. `refine_plan_from_loaded_weights` places a torchao denoiser from a measured activation figure. For Klein that figure is the per-phase seed (`_MEASURED_IMAGE_ACTIVATION_MIB["flux.2-klein"]`, measured on klein 4B and 9B). The seed was gated by `_calibrated_activation`, which refuses every reference family the request guard cannot price, because Klein's source image is not in `condition_pixels`. So the first load had no headroom figure and kept the flat plan. Only a later load, after a render had recorded a learned peak, kept the transformer resident. The request guard already handles that unpriced reference for the dense default / max tier seeds: `measured_request_extra_mib(..., unpriced_references=True)` sizes the request from the flat estimate, so the resident groups stream again for that call. This change gives the phase seeds the same treatment: - `_calibrated_activation(..., unpriced_references_ok=True)` skips the reference rule. Only the placement seed (`pipe._unsloth_phase_seeds`) asks for that; the planner's tier choice keeps the rule. - `measured_request_extra_mib` treats a phase-seeded torchao placement like a dense tier-seeded one when a request carries an unpriced reference. Nothing changes for non-reference families, for ROCm / math-only attention (still no seed), or for the eager tier. ## Evidence Single B200, card capped with `set_per_process_memory_fraction`, with `mem_get_info` reporting the capped total. Studio in-process, automatic memory mode, default speed tier (compiled, CUDA graphs), auto int8. Each arm is a fresh process with a fresh Studio home (first load). 1024x1024, 4 steps, 3 new prompts. s/call is the median DiT forward on renders 2 and 3. | model, cap | | resident DiT | peak reserved | s/call renders 2 / 3 | graph breaks / recompiles, renders 2-3 | |---|---|---|---|---|---| | klein-4B, 12 GiB | merge base | 0 of 3.77 GiB | 4.6 GiB (38%) | 0.094 / 0.076 | 0 / 0 | | klein-4B, 12 GiB | this branch | 3.77 of 3.77 GiB | 7.3 GiB (61%) | 0.024 / 0.021 | 0 / 0 | | klein-9B, 16 GiB | merge base | 0 of 8.75 GiB | 6.0 GiB (37%) | 0.189 / 0.180 | 0 / 0 | | klein-9B, 16 GiB | this branch | 8.75 of 8.75 GiB | 13.9 GiB (87%) | 0.042 / 0.049 | 0 / 0 | For reference, the same models resident on an uncapped 24 GiB card run 0.022 (4B) and 0.041 (9B) s/call. Parity: - klein-9B 16 GiB: images are byte-identical to the merge base at every render. - klein-4B 12 GiB: images are byte-identical to the merge base at 8, 16 and 24 GiB. Two merge-base processes at 12 GiB disagree with each other and with every other cap, so the 12 GiB base is not reproducible across processes. This branch at 12 GiB matches the 8 / 16 / 24 GiB output exactly. Edit request (the unpriced reference) at klein-4B 12 GiB, 2 renders with the first image as the source: both complete with no OOM, at a 7.2 GiB peak, and the transformer is back to resident afterwards. CUDA graphs: klein-9B at 16 GiB re-records the step graph after each new prompt (captures 1 / 2 / 3), because the prompt encode streams resident groups out and back. The merge base streams everything, so it re-records nothing. That re-record is what #14765 removes, and on that branch FLUX.1-schnell int8 at 16 GiB shows captures 1 / 1 / 1. The re-record costs one capture per new prompt; the residency itself is still a 3.7 to 4.3x speed-up per step here. ## Tests - New `tests/test_diffusion_reference_phase_seeds.py`: three of its four tests fail on the merge base and pass here. They cover the opt-in skip of the reference rule, the load path using it, and the unpriced reference sizing from the flat estimate on a phase-seeded placement. The fourth pins the first-load 16 GB placement. - `test_diffusion_learned_peaks.py`: its source pin follows the new call. - `test_diffusion_calibrated_activation.py`, `test_diffusion_measured_placement*.py`, `test_diffusion_dense_tier_activation.py`, `test_diffusion_learned_peaks.py`, `test_diffusion_flux3.py`: 718 passed, 2 skipped. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Keep main's _stable_range_failure and _retire_stable_range beside the PR's _retire_stable_placement, unify ModuleArena's deferred detach on main's public retiring flag, keep both sides' new tests, and pin main's retired-pool re-record tests to the stock re-pin (the stable group range makes the step replay instead of re-recording). [skip ci]
…aced A re-pin that raised after an earlier tensor was repointed into the group range left that tensor there, so release_group_range refused to unmap and the rest of the group moved the stock way beside a fully mapped range. pin_group_in_range now points every tensor it installed back at its original storage (t.data for plain tensors, a second swap for wrappers) before re-raising, so the caller's release unmaps the range. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
Summary
On the group-offload tier, each prompt encode streams resident denoiser groups out to make room for the text encoder, then pins them back before step 0. The stock re-pin copies each weight into a new caching-allocator block. The block-streamed step graph is keyed on the resident weights' addresses, so it recorded again on the next render of a size it had already captured. That costs about 1.7 to 2.8 s on Z-Image-Turbo int8 at a 12 GiB cap, on every render after a new prompt.
Once the step graph is armed on a block-offloaded denoiser, each group the encode release streams gets its own CUDA VMM range at its first re-pin. This reuses
VmmArenafrom #14666, and this branch is stacked on it.UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0turns it off. Status reports the ranges understable_repin.Results
Z-Image-Turbo with int8 and group offload, 12 GiB emulated cap (mapped VMM bytes counted against the cap), 1024x1024, 8 steps, 3 prompt encodes over 8 renders:
Images are also byte-identical between base and this PR at every step.
VRAM: the 7 released groups hold 1235.5 MiB of weights, and their ranges reserve 1246 MiB, an overhead of 10.5 MiB from the 2 MiB granularity. The allocator peak plus mapped bytes is within 4 MiB of base on the same steps. Base then grew a further 664 MiB reserved after its re-captures.
Tests
test_an_encode_release_re_pins_where_the_step_recorded: captures per prompt are 1, 0, 0, 0 with outputs bit-identical to eager. On base the same test gives 1, 1, 1, 1. With the kill switch, later prompts record again.test_the_render_peak_counts_weights_moved_into_a_stable_range: fails on base, passes here.Qwen-Image-2.1 at an 8 GB cap
Auto load (int8 denoiser, int8 text encoder, streaming tier with 18 of 35 groups resident), emulated 8188 MiB cap, 1024x1024, 8 steps. Renders 2 to 6 each encode a different prompt, and each encode streams 2447 MiB of resident groups out and back.
Images are byte-identical between main and this branch at every render. The ranges hold 2498.6 MiB of weights in 2520 MiB (0.86% overhead); peak usage including the range bytes was 7918 to 7920 MiB here against 7952 to 8022 MiB on main.
Merged with main (744ee65)
Main had independently added a stable-range retire path (
_stable_range_failure,_retire_stable_range, and a publicretiringflag withretire()indiffusion_stable_arena.py) at the same spots this PR changes. An automatic merge kept main's calls but dropped those definitions (NameError: _stable_range_failure). The manual merge keeps all of main's functions and this PR's_retire_stable_placement, and the PR's delayeddetach()now sets main'sretiringflag, so there is one flag rather than two.ruff --select F821,F811is clean on the merged files.Two of main's new tests assume a prompt encode re-pins resident groups at new addresses and forces a re-record. With this PR the re-pin lands at the same addresses and the step replays, so those two tests now set
UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0to keep exercising the re-record path, which still runs when the stable range is off or fails.test_diffusion_offload_cuda_graph.py: 59 passed; main alone 249 passed across the four offload / graph files; the merge passes them with only those two tests needing the env.