Repository navigation
Studio: release VRAM when an image model is unloaded mid-render - #11790
Conversation
A cancelled generate() re-raises out of the generation slot with its frame, and so the loaded state and pipeline, still pinned by the traceback. The unload waiting on that slot tears down while the pipeline is still referenced, so its cache clear frees nothing, and once the exception is dropped the weights sit reserved in the CUDA caching allocator (about 7 GiB for SDXL) until the next load. Clear the finished frames of the escaping exception and, when an unload or replacing load ran during the render, empty the cache after the last reference is gone.
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 100ca6a4c4
ℹ️ 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".
| if self._load_token != token: | ||
| try: | ||
| clear_gpu_cache() |
There was a problem hiding this comment.
Clear the cache when a pending replacement cancels the render
When begin_load() has already started a replacement, it increments _load_token before its potentially long prefetch, so a render started during that prefetch captures the replacement's token here. Later, load_pipeline() cancels that render and tears down the old pipeline without incrementing the token again. If the load thread acquires the generation slot and runs _unload_locked() after the slot is released but before this wrapper clears the exception frames, its cache clear still sees the traceback-held pipeline; after frame cleanup, this condition is false and no second clear occurs, reproducing the multi-GiB VRAM leak for mid-render model replacements. The final clear must be keyed to the teardown/cancellation that affected the render rather than solely to an epoch change after wrapper entry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 765d38a: the render now also clears the cache after dropping its frames while a teardown is pending or owns the slot, not only when the token moved. New test forces that order with a replacing load and fails without the fix.
begin_load bumps the load token before its prefetch, so a render started during the prefetch keeps that token while load_pipeline cancels it and tears down. Clear the cache after the render's frames are dropped whenever a teardown is pending or owns the slot, not only when the token moved.
|
@codex review |
diffusion.py already defines _clear_exception_frames further down, and that later definition is the one every caller, including the new render wrapper, resolves at call time. The copy added here was dead and failed the duplicate-definition lint.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 765d38abae
ℹ️ 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".
| finally: | ||
| # A replacing load whose begin_load bumped the token before this render began cancels it | ||
| # without moving the token again, so a pending or running teardown counts too. | ||
| if self._load_token != token or self._teardown_waiters or self._transition_owns_slot: |
There was a problem hiding this comment.
Persist teardown evidence until render cleanup
When begin_load() advances _load_token before this render starts, these predicates are only transient: after the cancelled render releases the generation slot, the replacement thread can run _unload_locked() and leave _model_transition_slot() before the wrapper resumes, making the token equal and both teardown flags false. Fresh evidence beyond the earlier report is the synchronous assert_flux2_gguf_matches_base(...) immediately after _unload_locked(), which can fail and release the transition this quickly; the unload's cache clear then ran while the traceback still held the old pipeline, and this condition skips the required second clear after _clear_exception_frames() drops it. Record a durable teardown epoch/result that remains observable by the affected render.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 36f97d8: every teardown reservation now bumps a counter that only grows, and the render clears again when it moved since entry. The replacing-load test now also forces the transition to finish before the frames are dropped; that case fails without the fix.
The pending-teardown flags are transient: a replacing load can finish its teardown and leave the model transition before the cancelled render drops its frames. Count every teardown reservation and clear again whenever one happened since the render started.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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. You're on a roll. 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". |
…othai#11790) * Studio: release VRAM when an image model is unloaded mid-render A cancelled generate() re-raises out of the generation slot with its frame, and so the loaded state and pipeline, still pinned by the traceback. The unload waiting on that slot tears down while the pipeline is still referenced, so its cache clear frees nothing, and once the exception is dropped the weights sit reserved in the CUDA caching allocator (about 7 GiB for SDXL) until the next load. Clear the finished frames of the escaping exception and, when an unload or replacing load ran during the render, empty the cache after the last reference is gone. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: also release VRAM when a replacing load cancels the render begin_load bumps the load token before its prefetch, so a render started during the prefetch keeps that token while load_pipeline cancels it and tears down. Clear the cache after the render's frames are dropped whenever a teardown is pending or owns the slot, not only when the token moved. * Studio: drop the duplicate _clear_exception_frames diffusion.py already defines _clear_exception_frames further down, and that later definition is the one every caller, including the new render wrapper, resolves at call time. The copy added here was dead and failed the duplicate-definition lint. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: key the render's cache release on a durable teardown count The pending-teardown flags are transient: a replacing load can finish its teardown and leave the model transition before the cancelled render drops its frames. Count every teardown reservation and clear again whenever one happened since the render started. * Studio: trim comments in the unload VRAM release * Studio: give the mid-render unload tests time to reach step 0 on a busy host * Studio: stub the device probe in the mid-render unload tests instead of racing it * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Unloading an image model while a render is running leaves the pipeline's weights on the GPU. With SDXL-Turbo the Studio process stays at about 7.8 GiB (7 GiB of it reserved by the CUDA caching allocator) after the unload returns, and it stays there until the next load. The render itself is cancelled correctly and the model reports as unloaded, only the memory is not given back.
This makes
unload()actually free the VRAM in that case, with no change to the normal render or cancel paths.Root cause
A cancelled
generate()raisesDiffusion generation was cancelled.out of_generation_slot. The exception's traceback still holdsgenerate()'s frame, and that frame holdsstateandpipe. So after the slot is released the pipeline is still referenced by the exception the caller is holding.unload()is waiting on exactly that slot. It wakes up, runs_unload_locked(), dropsself._stateand callsclear_gpu_cache(), but the weights are still alive through the traceback, so nothing is freed. A moment later the caller drops the exception, the tensors are released into the caching allocator, and nobody callsempty_cache()again.nvidia-smiand the process VRAM stay at the loaded level.Direct probe on SDXL-Turbo, resident, unload at step 3 of 80:
unload()returnsempty_cache()Fix
generate()gets a small wrapper,_release_render_on_unload:traceback.clear_frames). This dropsstateandpipebefore the exception reaches the caller, so the unload's ownclear_gpu_cache()frees the weights._load_tokenmoved during the call (an unload or a replacing load ran under this render), callclear_gpu_cache()once more after the render's references are gone. That covers either ordering between the render thread and the unload thread. A failure there is only logged, so it never masks the render's own result.Nothing changes when no unload happens: no extra
gc.collect(), no extra sync, same outputs and speed. The unload path, locks and cancel protocol are untouched.Before / after
Studio edge suite
image.unload_during_generate(SDXL-Turbo, 1024x1024 80 steps, unload mid-render, VRAM measured per process, must return to the unloaded level + 512 MiB within 20 s). Base is 9a8f246, fix is this branch, same GPU and same placement:Probe, same setup: after
unload()returns the process holds 18 MiB allocated / 44 MiB reserved, down from 6744 / 7030 MiB, while the caller still holds the cancelled exception.Testing
test_unload_mid_render_releases_the_pipeline: a stepping fake pipe is unloaded mid-render, and the pipeline must be collected, and the cache cleared after that, while the caller still holds the exception. It fails on main (the pipe is still pinned) and passes here.tests/test_diffusion_*.py,tests/test_video_backend.py,tests/test_account_native_diffusion_load_rollback.py: 3321 passed on this branch, 3320 on main. The same 4 tests fail on both (threetest_diffusion_h3_trainerrotation tests and onetest_diffusion_single_file_registryQ8_0 case), unrelated to this change.image.*on both surfaces:determinism,progress_cancel,concurrent,generate_while_loadingand the rest pass as on main (HTTP on this branch: 15 of 16).leak_cycles(host RAM) fails the same way on both and is a separate fix. The GPU was shared with other jobs, so the loads were pinned resident for both arms, and a couple of size / memory-mode cases hit a real device OOM from the other tenants on one arm or the other.video.pyis not touched;tests/test_video_backend.pypasses.Risk
Low. The wrapper only does work when
generate()raises or when a load token changed under it.traceback.clear_framesskips frames that are still executing, so it cannot clear the wrapper's own frame or the caller's. Clearing the finished frames only affects debugging by locals of an already reported exception, and the message and traceback lines are unchanged.