Skip to content

Studio: the SDXL background compile runs only while no render runs - #16312

Merged
danielhanchen merged 4 commits into
mainfrom
studio-sdxl-compile-never-stalls
Oct 31, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-sdxl-compile-never-stalls

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

SDXL sessions in Studio were slower than eager (speed_mode=off) while the deferred per-block U-Net compile was still running. Each render waited for a slice of that compile. On L4, renders 3-10 took 12.0-19.6 s against 9.5-10.0 s eager. On A100 the compile never finished within 20 back-to-back renders, and the session took 91-95 s against 56 s eager.

With this change the background compile runs only while no render is running. A back-to-back session now runs at eager speed or better from the 3rd image on. A session with idle time between images still reaches the compiled speed. Its renders stay at eager speed until the compile is done.

Root cause

_wait_or_pause_bg_compile (diffusion.py) called BackgroundCompile.pause(budget_s=slice). That call made each render wait for three things, one after another, before it could start:

  1. The slice itself (UNSLOTH_DIFFUSION_BG_COMPILE_SLICE_S, default = the load's fastest eager render: 9.4-9.7 s on L4, 2.7 s on A100).
  2. The block graph in flight. The compile could only park at a block boundary (yield_point), so the render waited for that graph to finish: 0.3-5.3 s per render on L4 with the slice set to 0 (logs from the earlier round).
  3. One more block graph after every resume (_owe_graph), the guard that kept back-to-back renders from starving the compile.

Running the render next to the compile is not an option. That compile is pure-Python dynamo / inductor work holding the GIL, and an earlier attempt measured renders 11-15x slower next to it. This is also why a shorter slice did not help: the render still waited at a block boundary.

Change

diffusion_bg_compile.py, idle-only mode (default on):

  • No slice, no wait, nothing owed. A render stops the compile right away. The compile resumes only once no render has run for UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_S (1 s). The kick itself also waits that long, so the response of the 3rd image is not slowed. Back-to-back renders (the next request arrives within 1 s) leave the compile parked. With idle time between images, the compile runs during the gaps.
  • Mid-trace freeze (resident denoiser, Python 3.12+). The compile thread no longer runs on to the end of its block graph. It is frozen at its next Python call through sys.monitoring PY_START, typically 1-13 ms after the render asks. Safety rules:
    • The callback only acts on the compile thread, and only inside torch's compile (torch._dynamo / _inductor / _functorch frames).
    • It never parks with a lock-taking module on the stack (logging, structlog, tqdm, imports, warnings, threading / concurrent, the inductor compile-worker pool, Studio's compile config).
    • It never parks in a Studio frame that is inside one of its lock blocks. Those blocks are found from the function's AST, so the CUDA-graph wrapper the sample replay runs through is not refused as a whole.
    • Frame verdicts are memoised per pause, so a refused region stays cheap.
    • The event is switched off as soon as the thread parks.
  • compile_lock. dynamo's compile_lock is wrapped (same RLock). A thread that needs it while the frozen compile holds it lets the compile finish that one frame, and the compile then freezes again, instead of deadlocking.
  • Blocked compile thread. A compile thread blocked without the GIL (a Triton / C++ build in the pool, a subprocess) costs the render nothing. The render does not wait for it: if the thread's innermost frame does not change for 20 ms, the render goes ahead.
  • Offloaded denoisers are not frozen (their eager forward moves weights). For them, and on older Python, the compile parks at the next block boundary with no slice and nothing owed.
  • Diagnostics. A render that took more than 0.1 s to stop the compile logs where and why. describe() gains idle_only, freezes, thaws, pause_wait_s.

Kill switches:

  • UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0 restores the previous slice behaviour exactly. The old tests run under it.
  • UNSLOTH_DIFFUSION_BG_COMPILE_FREEZE=0 keeps idle-only but stops only at block boundaries.

LoRA renders still wait for the whole compile, as before. Whole-module compiles (DiT families, UNSLOTH_DIFFUSION_UNET_REGIONAL=0) do not yield, so they keep their current wait path.

Results

SDXL 1024^2, 25 steps, dpmpp_2m karras, a fresh Studio home and inductor cache per cell, 20 new prompts per cell, one warm-up render first. The base is the PR's merge base at the time of each run (b1b286c9b7 for L4 #1 / A100 #1, d6ab4f64ac for the rest; the commits in between do not touch these files); head is base plus this change. Eager is base with speed_mode=off. Gap = 8 s idle before each render after the first, not counted in the time. rN = repeat N.

Back-to-back, total seconds for 20 images (same VM per row)

VM base default head default base eager head renders 3-20 eager renders 3-20
L4 #1 241.73 / 236.47 191.90 / 191.86 193.14 / 192.33 9.33-9.69 9.49-9.89
L4 #2 242.05 / 242.07 196.95 / 196.76 197.80 / 198.11 9.57-9.81 9.74-10.01
L4 #3 - 195.25 195.50 / 196.21 9.53-9.68 9.67-9.90
A100 #1 94.66 / 91.48 56.05 / 55.97 55.88 / 56.26 2.66-2.71 2.77-3.03
A100 #2 - 55.87 55.79 / 56.16 2.66-2.69 2.77-2.87

On base, L4 renders 3-10 take 12.0-19.6 s. A100 base renders take 3.0-8.3 s across all 20, because its compile never finishes.

With idle gaps (the compile gets idle time)

VM base default head default r1 / r2 base eager head: first compiled render head renders 3-9 (eager at the same index) then
L4 #3 211.77 (renders 3-5: 17.2-19.6 s) 196.10 / 189.42 198.09 (eager, same gaps) render 10 (compile 136 s, 7 pauses) 9.70-9.89 (9.85-9.97) 8.86-8.95
A100 #2 58.45 (renders 2-7: 3.4-4.8 s) 57.70 / 52.42 56.08 (eager, same gaps) render 10 (compile 74 s, 6 pauses) 2.67-2.94 (2.79-2.81) 2.25-2.30
  • Stop latency: 23 of 26 pauses froze the compile mid-trace within 0.001-0.013 s. The other 3 stopped it within 0.16 s.
  • On A100, 3 of the 14 head renders in that window ran above eager, by 0.03, 0.13 and 0.14 s (2.83 / 2.92 / 2.94 s). The other 11 were at or below eager.
  • The first compiled render (L4 10.13-10.16 s) includes the first CUDA-graph capture. Base pays the same cost (10.33 s).

A/A

  • Repeated eager arms: within 0.4 s per session on L4 and 0.4 s on A100.
  • Repeated head arms: within 0.2 s per session back-to-back.
  • Head r1 / r2 back-to-back: pixel-identical images (LPIPS 0 on all 20, both cards).

Images

  • Head back-to-back vs base, A100: identical on all 20 (LPIPS 0). Base never compiled there.
  • Head back-to-back vs base, L4: identical before base's compile finished (9 of 20), compiled-vs-eager differences after (mean LPIPS 0.033, max 0.098). Base A/A shows the same split.
  • With gaps on L4: head vs base 13 of 20 identical, mean 0.022.

Another compiled family: FLUX.2-klein-4B (4 steps, whole-model compile path). Head and base give identical images (LPIPS 0, 6 of 6) and the same times, 2 repeats each on A100 and L4:

  • A100: 0.75-0.77 s per image on both.
  • L4: 2.11-2.17 s per image on both.

Tests

  • New tests/test_diffusion_bg_compile_idle.py. Every test errors on base (IDLE_ENV / pause(freeze=) do not exist there). Real dynamo traces on CPU check that:
    • a render freezes the compile inside a running trace within 0.2 s, with no progress while the render holds the pause;
    • the event is off once parked;
    • the compiled output after resume matches eager;
    • the resume waits out the idle grace;
    • back-to-back pauses never wait and owe nothing;
    • without freeze, the compile parks at the next block boundary;
    • close ends a parked or a frozen compile;
    • another thread compiling while the trace is frozen does not deadlock: one thaw, then the compile freezes again;
    • the frame refusal rules hold (a Studio frame is refused only inside its lock block; GraphedForward._eager is not a lock block; the memoised walk matches a fresh one);
    • the compile_lock proxy behaves like the RLock it wraps;
    • the render-side routing is right (resident freezes, offloaded does not, LoRA still waits).
  • tests/test_diffusion_unet_block_compile.py: the slice-mode tests now run with UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0 and still pass.
  • Related suites (bg compile float seeds / state objects, U-Net block compile, Z-Image CFG split, cold start, speed, block graph, CUDA graph, offload CUDA graph, video i2v): 610 passed, 7 failed. The same 7 fail on base: test_diffusion_cuda_graph.py::test_capture_then_replay_uses_one_graph_and_copies_statics (passes alone, order-dependent) and 6 in test_video_i2v.py.

Not proven

  • Renders 1-2 of a session are still slower than eager on base and head alike: about +0.3 s at the 2nd image and +1.7-2.0 s at the 3rd (L4 11.7 s vs 9.8 s eager, A100 4.8 s vs 2.8 s). This is the deferred profile's own cost: it warms the compile pool at the 2nd image, then at the 3rd engages channels_last / fused QKV / fused VAE and pays a first fused VAE decode of 1.5 s. It is not the background compile, and this change does not touch it.
  • The first head cell on each VM ran its engagement render at 17.1-17.5 s (L4) and 10.5 s (A100). Later head cells ran it at 11.7 s and 4.8 s. This points to the first use of a fresh source tree on the VM, not to this change. It was not isolated.
  • A back-to-back client never gives the compile idle time, so it stays at eager speed for the whole session (it never gets the compiled speedup, 9.7 vs 8.9 s on L4).
  • Freeze safety rests on a deny list of lock-taking modules and an AST scan of Studio functions for with ...lock... blocks. Locks held by C++ code or by modules outside that list are not covered.
  • Not every row ran the final code:
  • With the final code, no hang or slow render beyond the numbers above was seen across the 9 SDXL cells of L4 RAM Offloading does not work (yet) #3 / A100 Support for training Mistral 7B  #2 (180 renders).
  • One A100 run lost its disk mid-run (OSError: [Errno 5] Input/output error), and its last cell hung with no output. It was counted as infrastructure and rerun on a fresh VM (A100 Support for training Mistral 7B  #2). That hang was not root-caused.
  • Measured on L4 and A100 (Colab, Python 3.13, torch 2.13) only. Not run: T4, H100, B200, AMD, Mac, Windows, Python 3.11 (where the block-boundary fallback applies), offloaded SDXL budgets, LoRA sessions, the HTTP server path (cells call DiffusionBackend.generate in process).

A render that found the per-block U-Net compile in flight let it run for one
slice (the load's fastest eager render), then waited for the block graph in
flight to end, and each resume owed one more graph. On L4 renders 2-10 took
14.7-19.7 s against 9.9 s eager; on A100 the compile never ended in 20
back-to-back renders.

Idle-only mode (default): a render stops the compile without a slice and
nothing is owed. It resumes once no render has run for
UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_S (1 s), so back-to-back renders run at
eager speed and the compile finishes in idle time.

For a resident denoiser on Python 3.12+ the compile thread is frozen inside
the trace at its next Python call (sys.monitoring PY_START), not at the next
block boundary. It parks only inside torch's compile, never with a lock-taking
module on its stack, nor in a Studio frame inside one of its lock blocks (the
sample replay runs through the CUDA-graph wrapper). Frame verdicts are memoised
so a refused region stays cheap. dynamo's compile_lock is wrapped: a thread that
needs it while the frozen compile holds it lets that frame finish, then the
compile freezes again. A compile blocked without the GIL (a Triton or C++
build) is not waited for.

UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0 restores the slice behaviour;
UNSLOTH_DIFFUSION_BG_COMPILE_FREEZE=0 keeps idle-only but stops only at block
boundaries.
@danielhanchen danielhanchen self-assigned this Oct 31, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 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 ✅ Completed 2026-10-31T17:00:49.640685Z 64a3396 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1884062702

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

Comment on lines +1032 to +1033
elif now - quiet_since >= _FREEZE_QUIET_S:
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for a block boundary when mid-trace freezing is disabled

For an offloaded per-block denoiser, _wait_or_pause_bg_compile explicitly passes freeze=False, but this branch still returns after 20 ms with an unchanged frame even when the compile has not parked. When that blocking operation completes, the background thread continues through the current block alongside the render; nothing stops it until the next yield point. This permits concurrent forwards through the same offload hooks, which mutate shared weight placement (for example, onload_ and offload_ in diffusion_memory.py replace tensor.data), potentially moving weights to CPU while the other forward needs them on CUDA. A barrier-based reproduction confirms that the in-flight block progresses after pause(freeze=False) returns while the pause remains held. Keep waiting for an acknowledged block-boundary park when mid-trace freezing is unavailable rather than treating a temporarily blocked thread as safely paused.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 341870e. The 20 ms quiet-thread shortcut in _pause_now now applies only when the mid-trace freeze is armed (_freeze_ok), since only then does the freeze stop the thread the moment it wakes. Without it (offloaded denoisers, freeze=False, older Python or UNSLOTH_DIFFUSION_BG_COMPILE_FREEZE=0) pause waits until the compile has parked at the block boundary, so no offloaded block forward runs beside the render. test_without_freeze_the_compile_parks_at_the_next_block_boundary now asserts the compile is parked when pause(freeze=False) returns while the in-flight block is blocked; it fails on the previous head and passes now. The resident path (freeze armed) is unchanged.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 341870ecbd

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 64a3396b74

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

@danielhanchen

danielhanchen commented Oct 31, 2026 •

Copy link
Copy Markdown
Member Author

On the staging run for this PR (danielhanchen#3659), (Python 3.13, a-f) failed in this PR's new test:

studio/backend/tests/test_diffusion_bg_compile_idle.py:138: in test_a_render_freezes_the_compile_mid_trace_without_waiting
    assert job._frozen and job.freezes == 1
E   assert (False)

The other 29728 tests in the shard passed. The earlier asserts held: paused was true and waited < 0.2. So the pause succeeded, but without a freeze. The test waits until the compile thread is inside torch._dynamo, then sleeps 0.05 s before calling pause(freeze = True). If the first block graph's trace finishes inside that window on a loaded runner (this shard runs under -n auto), the job is parked at a block boundary instead of mid-trace, and _frozen stays false. Calling pause right after _wait_for(lambda: _in_dynamo(job)), or making the traced block large enough that 0.05 s cannot cover it, would remove the race. It is also worth checking that the freeze path does not decline silently when the trace ends just as the pause arrives, since that would be a product bug rather than a test one.

@danielhanchen
danielhanchen merged commit d6950ad into main Oct 31, 2026
@danielhanchen
danielhanchen deleted the studio-sdxl-compile-never-stalls branch October 31, 2026 19:09
danielhanchen added a commit that referenced this pull request Nov 1, 2026
…e for one waiting compile (#16364)

## Problem


`studio/backend/tests/test_diffusion_bg_compile_idle.py::test_a_compile_elsewhere_thaws_a_frozen_compile_instead_of_deadlocking`,
added in #16312, failed in `(Python 3.13, a-f)` on #16353, which only
changes a training route:

```
tests/test_diffusion_bg_compile_idle.py:270
    assert job.thaws == 1
E   assert 2 == 1
```

The deadlock check right above it passed: the render's compile finished,
and the output was correct. Only the exact thaw count was off.

A second thaw is legitimate. `_thaw_for_lock` lets the frozen compile
run to the end of the frame that holds dynamo's `compile_lock`, where it
releases the lock. `_maybe_freeze` declines to refreeze only while the
lock is owned and a thread is waiting on it. So if the background
compile reaches its next safe call after that release, but before the
waiting thread's next 50 ms `acquire(True, 0.05)` poll, it freezes again
without holding the lock. The waiter's poll then thaws it once more and
takes the lock. No deadlock and no lost progress, but `thaws` reads 2.
That depends only on scheduling, which is why it shows up on a loaded
runner.

## Change

`assert job.thaws == 1` becomes `assert job.thaws >= 1`, with a comment
saying why. The guard this test exists for, `assert not
worker.is_alive()`, which catches a render compile waiting forever on
the frozen trace, is unchanged. So is the later `freezes >= 2` check.

## Verification

- Reproduced on main: 1 of 96 runs failed with `assert 2 == 1` under `-n
12 --count 96` pinned to 2 CPUs.
- This branch: 192/192 pass under `-n 12 --count 192` on 2 CPUs. The
whole file passes 16/16.
- Sabotage: with `_thaw_for_lock` turned into a no-op, so a frozen
compile is never thawed for a waiter, the test does not pass. The
waiting compile deadlocks and the run hung until it was killed. The
assertion still guards what it was written for.
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 1, 2026
…uality (#2336)

## Problem


`tests/test_chunked_logprob.py::test_grpo_switches_keep_entropy_policy_and_reference_on_one_scorer[UNSLOTH_GRPO_CHUNKED_LOGPROBS]`
fails on some GitHub runners in unsloth's `Core zoo (HF=latest +
TRL=latest)` job, which runs this suite. It failed on
unslothai/unsloth#16350 (an orchestrator change) and earlier on
unslothai/unsloth#16312's staging run (a diffusion change), both at zoo
`604c131a`. Both times the result was identical:

```
AssertionError: {'equal': False, 'maxdiff': 3.0040740966796875e-05}
```

The same value twice means the runner hardware determines it, not
chance. The test runs the reference scorer (fully eager) and the
recompute scorer (eager matmul, with an Inductor-compiled
`post_forward`) on CPU, and asserts bit equality. On this host the two
agree exactly at every thread count (1 to 4), every Inductor `simdlen`
tried (1, 4, 8, 16), and with ATen pinned to AVX2. On those runners the
two most likely reduce in a different order. I could not reproduce it
here, so the exact cause is unconfirmed.

Bit equality was also the only way this test could catch the regression
it guards. On CPU, when the switch is off but the policy is still scored
by the fused kernel, the drift from the old reference scorer is only
9.5e-7. That is smaller than the 3e-5 the two old-scorer paths differ by
on those runners, so no tolerance separates the bug from the noise.

## Change

The child process now wraps the two fused entry points,
`fused_linear.fused_linear_logprobs` and
`chunked_logprob.unsloth_chunked_logprobs`, and records every call. With
either switch off, the test asserts that neither one ran, which is the
actual meaning of "on one scorer". It also keeps a sanity bound of
`maxdiff < 1e-3` on the values.

## Verification

- Both parametrisations pass. The whole file passes, with 77 passed and
3 skipped under `-n 8`.
- Sabotage 1: the recompute scorer's `fused_linear` default ignores the
switches. The `UNSLOTH_GRPO_CHUNKED_LOGPROBS` case fails with `{'calls':
['fused_linear_logprobs'], 'maxdiff': 9.5367431640625e-07}`.
- Sabotage 2: the reference scorer ignores the switches. That case fails
with `{'calls': ['unsloth_chunked_logprobs', 'fused_linear_logprobs'],
...}`.
- In both sabotages the `UNSLOTH_FUSED_LINEAR` case still passes, as it
should: that flag also disables `chunked_logprob._FUSED_LINEAR` at
import, which gates the fused path on its own.
- The sabotage drift of 9.5e-7 shows that a plain tolerance in place of
the old `torch.equal` would have let both regressions through.
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