Repository navigation
Studio diffusion: record CUDA graphs thread-locally and keep other threads' syncs out of a recording - #14964
Conversation
…, gate device syncs A whole-step capture recorded in CUDA's global mode, so any other Studio thread's event query, host read, pinned alloc, empty_cache, stream sync or first cuBLAS / cuDNN call invalidated it (the other backend's render, a decode, the video pinner, download-plan). Captures now record thread_local, wait for another thread's recording before they enter, and Studio's in-process device syncs go through synchronize_outside_capture, the shared side of the capture gate.
_graph_with_flush forwards an optional stream to torch.cuda.graph (None keeps torch's default capture stream), so a per-card capture stream can be passed through without touching the capture gate.
[skip ci]
|
@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. |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…ptures Up to torch 2.11 a CUDA graph capture marks the device's default generator as capturing for every thread, so another thread's default-generator draw raises "Offset increment outside graph capture encountered unexpectedly" in that thread (the recording itself is kept). torch 2.12 keys the capture RNG state by capture id. The NVFP4 / MXFP8 load probes that already wait out a recording now seed their inputs from an explicit generator, the test's other-thread decode draws like a Studio render does, and a new test pins the per-version behaviour of a default-generator draw. [skip ci]
# Conflicts: # studio/backend/core/inference/diffusion_cuda_graph.py # studio/backend/tests/test_diffusion_cuda_graph.py [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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]
The NVFP4 and MXFP8 probes seeded a CUDA torch.Generator, which raises on a CPU-only or spoofed torch before the probe's own failure handling runs. Draw the inputs on CPU from an explicit CPU generator and move them to the device: still never the default generator, so the torch <= 2.11 capture flag fix holds. [skip ci]
|
@codex review |
Resolve diffusion_measured_peaks.py: keep the capture-aware sync and main's stable-range peak accounting. Route main's new ConvRot h16 / SwiGLU probes and the unlisted latency check through synchronize_outside_capture, an explicit CPU generator, and a serialised thread_local capture. [skip ci]
A weakref finalizer can run on a thread that already holds the non-reentrant capture lock (inside synchronize_outside_capture's Condition setup), so VmmArena.close() -> unmap() -> the gated sync deadlocked. Finalizer cleanup now uses close_from_finalizer(): it syncs and frees under a non-blocking try of the capture lock with no capture recording, else queues the close, drained at the next synchronize_outside_capture or capture exit. Explicit unmaps keep the gated sync.
Problem
Studio records its whole-step diffusion CUDA graphs with
torch.cuda.graph(...)in its defaultcapture_error_mode="global"(and_graph_without_flushpasses"global"explicitly). The PyTorch docs fortorch.cuda.graph/CUDAGraph.capture_beginsay: "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 raisesoperation not permitted when stream is capturingon 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 underfit/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 #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 entrytorch.cuda.synchronize()(andtorch.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):
mem_get_info, new streamcublasCreatefails).item()/.cpu(), default or side streamevent.query(),event.synchronize(),stream.synchronize()pin_memory()empty_cache()with free cached blockstorch.cuda.synchronize()On main these races are real. The new tests fail there, and one of them fails because of the cross-thread call itself:
CUDNN_STATUS_INTERNAL_ERROR_DEVICE_ALLOCATION_FAILED.operation not permitted when stream is capturing ... cuCtxSynchronize. The load then runs eager.Fix
capture_error_mode="thread_local"(CAPTURE_MODE). This covers bothtorch.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._capturing()waits for any other thread's recording to end before it raises the depth. The wait is bounded byRETIRED_FLUSH_WAIT_S, after which it raisesCaptureRefusedand that step runs eager. A thread's own nested captures still nest.synchronize_outside_capture(device)replaces the baretorch.cuda.synchronizeat 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.clear_gpu_cache(unload beside the other backend).hold_off_capture, or inside the thread's own recording, it syncs directly, so it never re-takes the non-reentrant lock.threading.localsubclass, so hot-path reads take no missing-attribute path. CUDA graphs stay on by default, nothing new syncs, and the graphs are unchanged.Tests
tests/test_diffusion_capture_serialises.py.hold_off_captureor inside the thread's own recording runs straight away; a capture's own sync refuses while a plain sync still runs.torch.cuda.graphstub intests/test_diffusion_cuda_graph.pynow acceptscapture_error_mode.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.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.GraphedForward, one device sync per step, with global + bare sync and thread_local + gate interleaved in one process.synchronizestubbed.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:6b458f30b4b9c85f98(new tests overlaid)The first T4 pass on
6dc4fd37ffailedtest_a_recording_survives_another_threads_decode_tailwithOffset increment outside graph capture encountered unexpectedly. Cause: up to torch 2.11,CUDAGraph::capture_begincallscapture_prologue()on the device's default generator, which sets acapturing_flag on the generator state shared by every thread. A draw from that generator on a thread whose stream is not capturing then failsTORCH_CHECK(!capturing_, ...)inCUDAGeneratorState::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. Explicittorch.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 #14915, per-card capture streams) is merged in at
f906e1e98. The recorder call is nowrecorder(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.pyandtest_diffusion_multigpu_cuda.pygive 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):
torch.cuda.synchronize(1).item()empty_cache()(every card)torch.cuda.synchronize(0)torch.cuda.graphcapture on card 1So 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
do_benchinside 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 callstorch.cuda.synchronizedirectly. A finalizer can run on a thread that already holds the capture lock, so it must not take the gate.f906e1e98has not run on torch 2.11. The Kaggle T4x2 numbers above are from6b458f30b, 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).