Repository navigation
Studio: the SDXL background compile runs only while no render runs - #16312
Conversation
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.
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 |
There was a problem hiding this comment.
💡 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".
| elif now - quiet_since >= _FREEZE_QUIET_S: | ||
| break |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
|
On the staging run for this PR (danielhanchen#3659), The other 29728 tests in the shard passed. The earlier asserts held: |
…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.
…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.
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) calledBackgroundCompile.pause(budget_s=slice). That call made each render wait for three things, one after another, before it could start: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).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)._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):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.sys.monitoringPY_START, typically 1-13 ms after the render asks. Safety rules:torch._dynamo/_inductor/_functorchframes).compile_lockis 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.describe()gainsidle_only,freezes,thaws,pause_wait_s.Kill switches:
UNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0restores the previous slice behaviour exactly. The old tests run under it.UNSLOTH_DIFFUSION_BG_COMPILE_FREEZE=0keeps 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 (
b1b286c9b7for L4 #1 / A100 #1,d6ab4f64acfor the rest; the commits in between do not touch these files); head is base plus this change. Eager is base withspeed_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)
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)
A/A
Images
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:
Tests
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:GraphedForward._eageris not a lock block; the memoised walk matches a fresh one);tests/test_diffusion_unet_block_compile.py: the slice-mode tests now run withUNSLOTH_DIFFUSION_BG_COMPILE_IDLE_ONLY=0and still pass.test_diffusion_cuda_graph.py::test_capture_then_replay_uses_one_graph_and_copies_statics(passes alone, order-dependent) and 6 intest_video_i2v.py.Not proven
with ...lock...blocks. Locks held by C++ code or by modules outside that list are not covered.d6ab4f64ac).d6ab4f64ac):torch._inductor.async_compilewas still refused, which kept the compile running beside 5 renders for 0.7-1.6 s, and structlog / rich were added later.b1b286c9b7). In that revision every Studio CUDA-graph frame was refused, so with idle gaps the compile was never frozen and ran beside the renders (30-370 s renders); that is fixed in the final code. Its back-to-back rows never reached that path: every pause found the compile already parked at a block boundary.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.DiffusionBackend.generatein process).