Skip to content

Studio diffusion: record CUDA graphs thread-locally and keep other threads' syncs out of a recording - #14964

Merged
danielhanchen merged 9 commits into
mainfrom
studio-capture-serialises-gpu-work
Oct 23, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
studio-capture-serialises-gpu-work

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

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 #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 #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).

…, 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.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-23T17:19:20.975371Z fb2d512 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 6dc4fd37fd

ℹ️ 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".

…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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: f906e1e987

ℹ️ 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".

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@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.
@danielhanchen
danielhanchen merged commit 9dfd045 into main Oct 23, 2026
39 of 47 checks passed
@danielhanchen
danielhanchen deleted the studio-capture-serialises-gpu-work branch October 23, 2026 22:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant