Repository navigation
Studio diffusion: replay a model-offloaded denoiser's CUDA graph across renders and pin torchao int8 host weights - #14666
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.
|
@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: be14e9fd97
ℹ️ 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".
| return None, MODEL_OFFLOAD_REASON | ||
| # Recorded only where the onloads land at the same addresses every render (diffusion_stable_arena). | ||
| from .diffusion_stable_arena import attach | ||
| arena, _arena_why = attach(module) |
There was a problem hiding this comment.
Detach the arena when graph setup is refused
When a model-offloaded denoiser passes attach() but is subsequently rejected by _forward_refusal() or fails OffloadPlacement construction, this call has already replaced the module's to method and installed a pre-hook, yet no graph handle exists to manage that arena. The denoiser therefore continues using the VMM onload path—and its full-device synchronization on every offload—for the remainder of the pipeline lifetime despite running eagerly. Run the remaining eligibility checks before attaching, or call arena.detach() on every post-attachment failure path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. offload_placement() now runs the capture-safety refusal before it attaches the stable range, and detaches the range when OffloadPlacement or the graph handle cannot be built, so an eager denoiser keeps the stock onload with no instance to override, no re-install hook and no per-offload sync. New test test_a_refused_model_offload_leaves_the_stock_onload covers both paths; it fails before the change and passes after.
| if t is None or id(t) in seen: | ||
| continue | ||
| seen.add(id(t)) | ||
| out.append((f"{mod_name}.{leaf}" if mod_name else leaf, mod, leaf, kind, t)) |
There was a problem hiding this comment.
Preserve every registration of shared buffers
When the same buffer tensor is registered under multiple names or submodules, this ID-based deduplication places only the first registration into the stable arena; _set_tensor replaces that registry entry rather than mutating the shared tensor, so the remaining registration is subsequently moved by stock Module.to() into an ordinary allocation. _module_tensors() also deduplicates buffers when computing the placement token, so later renders can replay a graph containing the first ordinary allocation's now-stale pointer instead of invalidating it, producing incorrect output or an invalid memory access. Each buffer registration must be updated to the arena view, even when its original tensor object was shared.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The stable range now places every registration of a shared buffer. Module.to() also 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 (so the placement fingerprint does not change between renders), and copies that diverged keep the stock move. New test test_model_offload_stable_range_places_every_registration_of_a_shared_buffer registers one buffer on two submodules and re-hooks between renders: both registrations read the placed copy, 0 captures after the first render, 0 invalidations, outputs exact. It fails before the change and passes after.
…, 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]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
…p graph recorded (unslothai#14765) ## 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 `VmmArena` from unslothai#14666, and this branch is stacked on it. - A release unmaps the physical memory, so the encoder gets the VRAM back exactly as before. - The next re-pin maps new memory at the same addresses and copies the pinned host weights in, so the recorded step replays. - Plain tensors 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 record a low peak. - `UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0` turns it off. Status reports the ranges under `stable_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: | | captures | step-graph invalidations | graph vs no graph, same process | |---|---|---|---| | base | 3 (re-records after 2 of the encodes) | 2 | identical bytes, 8 of 8 | | this PR | 1 | 0 | identical bytes, 8 of 8 | 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. - The offload graph, measured placement, prefetch, learned peak and step graph test files pass, apart from 6 learned-peak video tests. Those fail with the same IDs on base when run after the offload graph file, because a process-wide failed-capture counter carries over between files. ### 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. | | main (merge base) | this branch | |---|---|---| | Render 1 | 2 recompiles, 1 capture | the same 2 recompiles, 1 capture | | Render 2 (new prompt) | re-captures, the capture runs out of memory under the cap and the step graph is disabled for the rest of the load | 0 recompiles, 0 captures, 7 replays | | Renders 3, 4, 6 (new prompt, same length) | ungraphed | 0 recompiles, 0 captures, replays | | s/step, renders 2 to 6 | 0.084 to 0.35 | 0.084 to 0.085 | 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 public `retiring` flag with `retire()` in `diffusion_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 delayed `detach()` now sets main's `retiring` flag, so there is one flag rather than two. `ruff --select F821,F811` is 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=0` to 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.
Summary
Under
memory_mode=low_vram(whole-module CPU offload) on a compiled speed tier, the denoiser step now runs as a CUDA graph on every render, recorded once on render 1, and the int8 weights the compiled tier stores stop being copied back and forth through pageable host memory on every render.Four commits:
diffusion_stable_arena.py). The denoiser's onloads land in one CUDA virtual address range reserved for the load (driver VMM:cuMemAddressReserveonce, thencuMemCreate+cuMemMapon every onload andcuMemUnmap+cuMemReleaseon every offload). The weights get the same addresses on every render, so render 1's step graph replays on renders 2+ with no new capture. The physical memory is still released at every offload, so the text encoder and VAE phases get the VRAM back as they do today. This is the same idea as ComfyUI'scomfy_aimdomodel_vbar. Studio diffusion: keep a model-offloaded denoiser's step eager instead of re-recording its CUDA graph every render #14497 kept this placement eager because the stock onload moved the weights on every render.offload_placement()now arms the graph only when the range attaches;UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0brings back Studio diffusion: keep a model-offloaded denoiser's step eager instead of re-recording its CUDA graph every render #14497's eager step.diffusion_memory.py). The keep-host-weights offload skipped torchao wrapper weights (Int8Tensor). Every render then copied them device-to-host into fresh pageable memory and uploaded them again from there. On FLUX.2-klein 4B only 0.5 of 4 GiB of the denoiser was pinned. Wrapper weights whose inner tensors are plain are now kept: the offload swaps the parameter back onto its kept host tensors (no copy), and their inner tensors are pinned on the first onload.Module.tomoves it.remove_hook_from_modulepops instancetooverrides (_accelerate_added_attributes), and diffusers re-hooks model offload before every render. Without this commit the range served only render 1. A forward pre-hook now puts the override back before the hook's pre-forward onloads the module.The existing offload speed check still judges each recorded key. A replay has to be at least 1% faster than the eager step, or the graph is dropped for the load. That covers the devices where a replay does not pay.
Numbers
Studio
begin_load+generate,memory_mode=low_vram,speed_mode=default(auto int8), 1024^2, 4 prompts (new text length and seed each time, guidance change on 4), B200. Base = main465e0c8d27, head = this branch. The host was heavily loaded during these runs (load average 1100-2000), so wall times are not comparable across processes. The counters are exact, and the same-process eager vs replay timings are fair.Same-process A/B on head Z-Image at 512^2, 8 steps, same prompt and seed. The replay ran at 31.7 ms per denoiser call. The same compiled step with the graph bypassed ran at 86.8 ms (min 56.0). Wall per render was 35.6 s against 57.6 s, and the image sha was identical in both modes. Wan 2.2 5B low_vram (480x832, 17 frames): armed over a 4848 MiB range, speed check 54.1 ms eager vs 21.1 ms replay.
The first denoiser call of a render includes the onload. On base it took 26-58 s on every klein render: the int8 weights were uploaded from pageable memory after a device-to-host copy. Head klein render 3 took 0.195 s. Renders 2 and 4 took 109 s and 149 s while the host was stalling, so treat the onload time as unmeasured here.
Quiet-host check, Colab A100 40 GB. Studio was installed by
install.shat465e0c8d27; "new" adds the four commits.FLUX.2-klein-4B,
low_vram, speed default (auto int8), 1024^2, 4 steps. Renders 2-4 (render 1 compiles):UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0(commit 2 only: int8 kept + pinned)On main the compiled low_vram tier was slower per render than speed off (4.7 s vs 2.5 s) because of the int8 re-copy.
The head is 2.5x faster than main and 1.3x faster than speed off. On a quiet A100 the graph itself adds about 1-2%:
in-process, 512^2 is 33.0 vs 33.5 ms per call and 1024^2 is 114.1 vs 114.4 ms, bit-identical. Most of the per-render
win comes from commit 2. The graph's large gains on the loaded B200 (Z-Image 512^2: 31.7 vs 86.8 ms) come from CPU launch
overhead, which graphs remove. That is real for a CPU-starved machine, but it is not the quiet-host number.
The graph pool lives across renders. That costs about 0.85 GiB reserved on klein and 0.6 GiB on Z-Image, held during the text encoder and VAE phases. The range itself is released at every offload.
Tests
test_model_offload_replays_over_the_stable_range_and_frees_it_between_renders,test_model_offload_stable_range_holds_torchao_int8_weights,test_torchao_int8_weights_keep_their_host_storage_and_are_pinned[0|1]. Updated:test_model_offload_records_nothing_after_the_first_render[False](main arms nothing there; it now arms the graph and records 0 captures on renders 2+), andtest_model_offload_keeps_the_step_eager_without_the_stable_range(Studio diffusion: keep a model-offloaded denoiser's step eager instead of re-recording its CUDA graph every render #14497's eager test, now with the range turned off).test_torchao_int8_weights_keep_their_host_storage_and_are_pinnedcases fail (the host tensors change on every render). The stable-range tests cannot import on main, because the module does not exist there.test_diffusion_offload_keep_cpu.py39 passed.test_diffusion_offload_cuda_graph.py -k "model_offload or stable_range": all passed, including re-hooking between renders the way diffusers does, and torchao int8.test_diffusion_memory,test_diffusion_block_graph,test_diffusion_offload_step_graphs,test_diffusion_multigpu,test_diffusion_offload_precisionandtest_diffusion_offload_keep_cpu: base 499 passed / 1 failed / 63 skipped, head 499 passed / 1 failed / 65 skipped. The one failure has the same ID on both (test_execution_device_reports_the_primary_of_a_split_pipeline, a diffusers / huggingface_hub import mismatch in that environment). The two extra skips on head are the new CUDA tests.