Repository navigation
Studio diffusion: stop flushing the CUDA allocator on every prompt encode under block offload - #14777
Conversation
…ocator On the group-offload 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, on every new prompt. That 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. On a busy host each call took 1.9 to 40 s and was most of the render thread's time on Qwen-Image-2.1 at an 8 GB cap. The flush is not needed for the room to reach the encoder: the encoder allocates from the same caching allocator, and an allocation that finds no free block (also one on the copy stream, which cannot take the default stream's free blocks) releases cached segments to the driver and retries before it raises out of memory, under the per-process fraction cap too.
…graph pool Without any flush in the encode release, a load whose step graph records again on new prompts (block offload whose re-pin moves the resident weights) kept every dropped graph pool's segments reserved beside the new recording: Z-Image-Turbo int8 at a 12 GiB cap went from 10186 to 12178 MiB reserved over four re-records, where main stays at 10186. The graph layer now counts dropped shared pools, and the encode release empties the cache only when one was dropped since its last flush, as the per-prompt flush used to. A load whose graph replays never flushes.
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. |
…pool, and not after a reset already did - A failed per-block or segment capture retires the block layer's own pool, not the shared step pool, so it never counted as a drop and the encode release never handed its segments back. Every pool a failed capture retires now counts. - reset_all (a LoRA load, an adapter switch) empties the cache in each handle's reset after dropping its graphs, then forgets the pool id; counting that as a pending drop made the next prompt encode flush a second time. The graph layer now records when its own empty_cache covered every retired pool (GraphedForward._release, the block layer's release, reset_all), and the encode release flushes only while a retirement is still pending. [skip ci]
…not counted for the encode The encode release no longer decides a flush from a count of retired graph pools. That count needed snapshots against concurrent retirements, acknowledgements from every other flush site and care for swallowed flush errors. The encode never needs a flush: its allocations are eager, and an eager allocation that finds no room makes the allocator release cached segments, retired graph pools included, and retry. Only a capture cannot do that, so pools are handed back where they retire, before anything records beside them: - an offloaded step key re-recorded after its weights moved flushes right before it records (that path skips torch.cuda.graph's own flush), so its dropped recording's pool does not stay reserved beside the new one; - a failed per-block or segment capture flushes after retiring its pool. Both flushes skip while another thread is recording. The other retirements already flush themselves: reset, poison, and the prefetch ring teardown. The encode release is back to no flush at all. [skip ci]
…idation and waits for it; block captures flush only when they retired a pool [skip ci]
…ore it records Retired pools are counted (invalidation, eviction, speed drop, poison, failed capture) and _capturing, which every step, re-record, block and segment capture enters, synchronizes and flushes them under the capture lock with no capture recording before it records. A flush acknowledges only the retirements counted before it began, so one landing mid-flush stays due; a capture that cannot flush in time is refused and runs eager, the next one retries. [skip ci]
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806, #14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775, #14774, #14773, #14772, #14770, #14769, #14768, and others): "files were modified by this hook". pre-commit.ci runs the hooks on all files, and 20 files on main (26 by the time this lands) are not in the formatter's output, so every PR is reformatted outside its own diff. Where pre-commit.ci can push, its autofix commit drags those unrelated files into the PR (for example #14790's touches `tests/test_block_compile.py`, `tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`). The drift came in with PRs merged today, among them #14702, #14751, #14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode, GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target changes. ### Change `python scripts/run_ruff_format.py` (the hook's own entry point, `ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those 20 files, plus 6 more from #14739, #14779 and #14806, which merged while this was open. Formatting only. ### Verification - Every changed file parses to an identical AST before and after. - A second run of the hook over the same files changes nothing (fixed point), and over all tracked Python files on this branch it changes nothing. - `ruff check` passes on the changed files; `tests/test_formatter_fixed_point.py` passes (16). Open PRs pick this up on their next pre-commit.ci run after merging main.
…e waits out another thread's recording GraphedForward._release and the block graphs' release now go through release_cached_outside_capture: empty_cache and the cuBLAS workspace clear run only while no capture records, otherwise the cleanup is counted as a retired pool and the next capture's entry flush does it. [skip ci]
… for the next entry flush When an offloaded wrapper's release is deferred because another thread is recording, the cuBLAS workspace clear it owed is kept as a flag beside the retired-pool count; the entry flush clears the workspaces once under the capture lock, with no capture recording, and resets the flag. [skip ci]
…h outside a capture acknowledges it Immediate cleanups (GraphedForward._release, the block graphs' release, the slot ring drop) go through one capture-lock flush that acknowledges the retirements counted before it, so the next capture does not flush again; a block graph dropping its recordings (poison, reset) counts a retirement; and a capture whose retirements another thread already flushed no longer waits on that thread's recording.
… recording; drops are owed where they happen PyTorch runs no non-captured CUDA work on any thread while a capture is underway, so a capture that must flush a retired pool now waits for another thread's recording to end (bounded like replica-side work) instead of being refused into an eager step beside it. A deferred release publishes its retirement and cuBLAS debt before gc and the lock attempt, GraphedForward.reset counts where it drops, and every block and segment drop (eviction, poison, reset) goes through one helper that counts the retired pool. [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: 45b2c835b6
ℹ️ 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".
| seen = _retired_pools_seen() | ||
| with _CAPTURE_IDLE: | ||
| if seen is not None: | ||
| _settle_retired_pools(seen) |
There was a problem hiding this comment.
Recheck retirements before starting capture
When concurrent render threads are active, another thread can call note_pool_retired() after _retired_pools_seen() returns but before this thread increments _CAPTURE_DEPTH; the current capture then records beside an unflushed retired pool, which can cause the tight-VRAM OOM this mechanism is intended to prevent. The same gap exists when a retirement occurs during _flush_retired_locked()—it remains marked due, but this capture still proceeds. Recheck or loop on the retirement counter under the capture-entry gate before allowing recording to begin.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The capture entry now loops: after the flush and the replica drain, it rechecks the retirement counters under the retirement lock and raises the depth only when nothing is due; otherwise it flushes again under the capture lock. Retirement takes the same lock, so a pool is either counted before that check (and flushed before the recording starts) or counted once the depth is up (due for the next capture). The loop is bounded; if pools keep retiring it refuses before recording. Regression test: test_a_pool_retired_while_a_capture_enters_is_flushed_before_it_records; test_a_pool_retired_while_the_capture_flushes_is_flushed_before_it_records covers a retirement during the flush itself.
…re lock before it raises the depth A pool retired after the entry read the counters, or while its flush ran, is flushed again under the capture lock before the recording starts; retirement takes the same lock, so it is either seen by that check or lands once the capture is recording and stays due for the next one. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…15015) `studio/backend/tests/test_diffusion_offload_step_graphs.py::test_releasing_an_offloaded_step_graph_frees_its_capture_stream_workspace` fails in Backend CI `(Python 3.13, a-k)`, for example on #15005, with `assert [] == [1, 2]`. It fails on a clean `main` every time when run on its own. ## Cause #14777 routed `GraphedForward._release` through `release_cached_outside_capture`. That flush runs `synchronize`, the cuBLAS workspace clear and `empty_cache` only when `torch.cuda.is_available()`. The test patched `_cuda_clearCublasWorkspaces` and `empty_cache` but not the availability probe. On a CPU runner it therefore passed only when an earlier test on the same xdist worker had installed the CUDA spoof, and otherwise recorded no calls. The product is right: there is nothing to flush without CUDA. The test was depending on ambient state. ## Fix The test now also patches `torch.cuda.is_available` (True) and `torch.cuda.synchronize` (no-op). Its assertion is unchanged: the cuBLAS clear and then `empty_cache` run only when the handle owned a capture-stream placement. ## Verification - The file: 15 passed, 15 skipped. Before, it was 1 failed in isolation on every commit back to ae3dc79. - Sabotage check: making `_release` pass `clear_cublas = False` fails the test.
…reads' syncs out of a recording (unslothai#14964) ## Problem Studio records its whole-step diffusion CUDA graphs with `torch.cuda.graph(...)` in its default `capture_error_mode="global"` (and `_graph_without_flush` passes `"global"` explicitly). The PyTorch docs for `torch.cuda.graph` / `CUDAGraph.capture_begin` say: "During cuda graph capture, some actions, such as cudaMalloc, may be unsafe. "global" will error on actions in other threads, "thread_local" will only error for actions in the current thread". In global mode, a "potentially unsafe" call from any other thread during the recording invalidates the capture, and the call itself raises `operation not permitted when stream is capturing` on that other thread. Studio runs CUDA work on several threads at once: the image and video backends each have their own render thread and their own `_generate_lock`, and the two can render side by side once both are loaded under `fit` / `always`. There are also the video background pinner, the stream encode worker, bg compile, the download-plan settle and the unload paths. The existing gates (`hold_off_capture`, `outside_capture` / `held_work`, and unslothai#14777's retired-pool wait) only cover the progress poller, preview, ring drop and CFG replica work. Everything else is ungated. Two captures also never excluded each other, so the second capture's entry `torch.cuda.synchronize()` (and `torch.cuda.graph.__enter__`'s own sync) landed inside the first capture's recording. What each call does when another thread makes it while a capture is recording on the same card (torch 2.14.1+cu130, B200, one fresh process per cell): | call on the other thread | global | thread_local | |---|---|---| | kernel launch on a warm thread, non_blocking H2D, fresh cudaMalloc, `mem_get_info`, new stream | ok | ok | | first cuBLAS matmul in a thread | invalidated (`cublasCreate` fails) | ok | | first cuDNN conv in a thread | invalidated | ok | | `.item()` / `.cpu()`, default or side stream | invalidated | ok | | `event.query()`, `event.synchronize()`, `stream.synchronize()` | invalidated | ok | | `pin_memory()` | invalidated | ok | | `empty_cache()` with free cached blocks | invalidated | ok | | `torch.cuda.synchronize()` | invalidated | invalidated | On main these races are real. The new tests fail there, and one of them fails because of the cross-thread call itself: - If another thread runs a VAE-decode style tail (cuBLAS, cuDNN, a host read, an event query, a pinned buffer) during a recording, it raises `CUDNN_STATUS_INTERNAL_ERROR_DEVICE_ALLOCATION_FAILED`. - If two threads capture at once, the second wrapper is poisoned: `operation not permitted when stream is capturing ... cuCtxSynchronize`. The load then runs eager. ## Fix - **Thread-local capture mode.** Whole-step captures now record in `capture_error_mode="thread_local"` (`CAPTURE_MODE`). This covers both `torch.cuda.graph` (`_graph_with_flush`) and the no-flush re-record. Per-block graphs already record this way, and so do torch.compile's own CUDA graphs (`torch/_inductor/cudagraph_trees.py`). The mode changes only which calls CUDA checks; it does not change what gets recorded. - Other threads' kernels never reach the private capture stream. - The capturing thread is still checked exactly as before. - The one cross-thread call that still breaks a recording, the device-wide synchronize, still errors loudly. It never corrupts silently. - **Captures exclude each other.** `_capturing()` waits for any other thread's recording to end before it raises the depth. The wait is bounded by `RETIRED_FLUSH_WAIT_S`, after which it raises `CaptureRefused` and that step runs eager. A thread's own nested captures still nest. - **Studio's device syncs take the shared side.** `synchronize_outside_capture(device)` replaces the bare `torch.cuda.synchronize` at Studio's in-process sync sites. It waits for another thread's recording to end and is counted as a hold while it runs, so no capture enters during it. This is one process-wide reader/writer gate: captures exclusive, syncs shared. - Sites converted: capture entry, settled memory snapshot (download-plan, loads), offload restore / return, ring drop and abandon, bg compile, CFG batch timing, VMM arena unmap, measured peaks, the int8 / nvfp4 / convrot / moss / attention device probes, and `clear_gpu_cache` (unload beside the other backend). - A capture's own pre-record sync refuses rather than breaking the other recording. - Under `hold_off_capture`, or inside the thread's own recording, it syncs directly, so it never re-takes the non-reentrant lock. - **Cost.** Uncontended, the shared side is one lock section before the sync and one after. Per-thread gate state moved to class defaults on a `threading.local` subclass, so hot-path reads take no missing-attribute path. CUDA graphs stay on by default, nothing new syncs, and the graphs are unchanged. ## Tests - **New: `tests/test_diffusion_capture_serialises.py`.** - Three CUDA races that fail on main and pass here: the decode tail during a recording, two threads capturing at once (both keep their graph and replay on the next call with no second capture), and a Studio device sync during a recording (it waits it out). - CPU tests of the gate: a capture waits for another thread's recording; nested captures do not wait on themselves; a capture held out too long is refused; the sync waits and is counted; a sync under `hold_off_capture` or inside the thread's own recording runs straight away; a capture's own sync refuses while a plain sync still runs. - **Existing stub update.** The `torch.cuda.graph` stub in `tests/test_diffusion_cuda_graph.py` now accepts `capture_error_mode`. - **Main vs branch, 30 test files, failing test IDs compared** (`temp/venv_core`, torch 2.14.1, one B200). Files run: `test_diffusion_offload_cuda_graph.py`, `test_diffusion_offload_step_graphs.py`, `test_diffusion_block_graph.py`, `test_diffusion_cuda_graph.py`, `test_diffusion_failed_capture_pool.py`, the multigpu files (`test_diffusion_multigpu*.py`, `test_video_multigpu_wiring.py`, `test_diffusion_cfg_parallel_tier.py`), `test_video_backend.py`, and the test files of every module whose sync was converted. - Only on main: the 13 new tests fail. - Only on the branch: nothing. - Red on both sides, pre-existing: - `test_diffusion_multigpu.py`: 5 tests that need a second card. - `test_diffusion_memory.py`: 8 pinned / top-level onload tests. - `test_diffusion_int8_gemm.py::test_no_compiled_variant_spills_to_local_memory`. - `test_polled_probe_costs.py`: 3 CPU-percent / process-tree tests. - `test_system_poll_no_cuda_context.py::test_the_probe_would_catch_a_regression`: an nvidia-smi subprocess timeout on a loaded host. - **Paired step benchmark.** A compiled 12-block DiT-like module (d=1024, fp16, batch 4x1024 tokens) under `GraphedForward`, one device sync per step, with global + bare sync and thread_local + gate interleaved in one process. - Both arms record once on the first render and replay for every later render, so the second render does not re-capture. - No dynamo recompiles in the timed renders, and outputs are bit-identical. - Median s/step: 3.84 ms vs 3.75 ms. The host was saturated (load average above 1000) and individual renders ranged from 1.4 ms to 11 ms, so this is noise, not a speedup. - The gate's own CPU cost on that host: about 1.7 us per sync call, against 0.04 us for a bare call with `synchronize` stubbed. ## Two T4s Kaggle 2x Tesla T4, torch 2.11.0+cu128, head `6b458f30b`, `tests/test_diffusion_capture_serialises.py` + `tests/test_diffusion_multigpu_cuda.py`, run 3 times in one kernel: | arm | run 1 | run 2 | run 3 | |---|---|---|---| | head `6b458f30b` | 19 passed | 19 passed | 19 passed | | base `4b9c85f98` (new tests overlaid) | 8 passed, 11 failed, 7 errors | | | The first T4 pass on `6dc4fd37f` failed `test_a_recording_survives_another_threads_decode_tail` with `Offset increment outside graph capture encountered unexpectedly`. Cause: up to torch 2.11, `CUDAGraph::capture_begin` calls `capture_prologue()` on the device's default generator, which sets a `capturing_` flag on the generator state shared by every thread. A draw from that generator on a thread whose stream is not capturing then fails `TORCH_CHECK(!capturing_, ...)` in `CUDAGeneratorState::increase` (`aten/src/ATen/cuda/CUDAGeneratorImpl.cpp`, same code from 2.6 through 2.11). The error comes from the other thread, before any offset or kernel change, so the recording is kept and the generator keeps working once the capture ends. torch 2.12 keys the capture RNG state by capture id (pytorch/pytorch#176752), so a draw on a non-capturing thread there is just a normal eager draw. Explicit `torch.Generator(device=...)` objects that are not registered with the graph are not affected on any version. Studio's render noise already comes from explicit generators. The NVFP4 / MXFP8 load probes (`diffusion_nvfp4_dispatch`, `diffusion_nvfp4_ops`, `diffusion_comfy_block`) drew from the default generator, so on torch 2.11 or older they could fail if they ran while another thread was recording, and the NVFP4 verify caches that failure for the process. They now seed from an explicit generator. In the tests, the other-thread decode now draws the way a render does, and a new test checks how a default-generator draw behaves on each torch version. Local B200: torch 2.11.0+cu128 3/3 and torch 2.12.1+cu130 3/3 (12 passed, 7 skipped each; the two-card tests need a second card). ## Interaction with per-card capture streams Main (with unslothai#14915, per-card capture streams) is merged in at `f906e1e98`. The recorder call is now `recorder(graph, pool = pool, stream = _capture_stream(card))`, so every capture records in thread_local mode on its card's own capture stream. On the merge, `test_diffusion_capture_serialises.py`, `test_diffusion_cuda_graph.py` and `test_diffusion_multigpu_cuda.py` give 127 passed, 8 skipped on one B200 (torch 2.12.1; the skips need two cards), and 135 passed, 0 skipped on two B200s (torch 2.14.1). The gate is process-wide, so captures on different cards record one at a time. That is safe in either capture mode. Measured on two B200s (thread A records on card 0 while thread B, already warm, works on card 1): | what thread B does on card 1 | global | thread_local | |---|---|---| | `torch.cuda.synchronize(1)` | ok | ok | | first cuBLAS in a thread, `.item()` | breaks card 0 | ok | | `empty_cache()` (every card) | breaks card 0 | ok | | `torch.cuda.synchronize(0)` | breaks card 0 | breaks card 0 | | a full `torch.cuda.graph` capture on card 1 | breaks card 0 | both graphs valid | So under thread_local, captures on different cards could record concurrently. Under global they cannot. Letting captures on different cards record at the same time (a per-device depth, shared pool ids checked per card) is left to a follow-up. Recordings are short, so serialising them costs little. ## Not covered - **Third-party device syncs on other threads still break a recording in any mode.** Examples: Triton / Inductor autotune `do_bench` inside the bg compile thread's compiled forwards, and syncs inside diffusers or accelerate code. Only Studio's own sync sites are gated. - **`_RegisteredHostBuffer.__del__`** still calls `torch.cuda.synchronize` directly. A finalizer can run on a thread that already holds the capture lock, so it must not take the gate. - **Cross-card behaviour rests on one probe run with toy kernels**, not on a real two-card render. - **s/step was measured on a shared, heavily loaded host.** No exclusive card was available, so this PR makes no throughput claim beyond the gate's per-call cost. - **The merge `f906e1e98` has not run on torch 2.11.** The Kaggle T4x2 numbers above are from `6b458f30b`, before the merge, and Kaggle had no free T4x2 slot for a rerun. On two B200s with torch 2.14.1 the merge passes all three files with every two-card test running (135 passed, 0 skipped).
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.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:
Tests
test_encode_release_does_not_flush_the_allocator_per_promptcountsempty_cacheover 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.pyandtest_diffusion_offload_cuda_graph.py: 198 passed.