Skip to content

Studio: release VRAM when an image model is unloaded mid-render - #11790

Merged
danielhanchen merged 10 commits into
mainfrom
fix-unload-mid-generate-vram
Sep 25, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
fix-unload-mid-generate-vram

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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() raises Diffusion generation was cancelled. out of _generation_slot. The exception's traceback still holds generate()'s frame, and that frame holds state and pipe. 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(), drops self._state and calls clear_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 calls empty_cache() again. nvidia-smi and the process VRAM stay at the loaded level.

Direct probe on SDXL-Turbo, resident, unload at step 3 of 80:

stage allocated reserved
mid render 6746 MiB 7302 MiB
after unload() returns 6744 MiB 7030 MiB
after dropping the exception 18 MiB 7030 MiB
after empty_cache() 18 MiB 44 MiB

Fix

generate() gets a small wrapper, _release_render_on_unload:

  1. On any exception, clear the finished frames of the escaping exception and its cause / context chain (traceback.clear_frames). This drops state and pipe before the exception reaches the caller, so the unload's own clear_gpu_cache() frees the weights.
  2. If _load_token moved during the call (an unload or a replacing load ran under this render), call clear_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:

surface base fix
in-process FAIL, 7840 MiB (7010 reserved) flat from 0.1 s to 21.8 s, unloaded level 850 MiB PASS, 854 MiB (22 reserved) at 0.1 s
HTTP FAIL, 7904 MiB flat from 1.5 s to 20.9 s, unloaded level 822 MiB PASS, 1014 MiB at 0.1 s, unloaded level 1014 MiB

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

  • New 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 (three test_diffusion_h3_trainer rotation tests and one test_diffusion_single_file_registry Q8_0 case), unrelated to this change.
  • Edge suite image.* on both surfaces: determinism, progress_cancel, concurrent, generate_while_loading and 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.py is not touched; tests/test_video_backend.py passes.

Risk

Low. The wrapper only does work when generate() raises or when a load token changed under it. traceback.clear_frames skips 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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 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-09-25T10:11:36.077344Z bb223ab Manual request
🔒 Security Review ⚠️ Failed 2026-09-24T08:49:00.242636Z 100ca6a PR opened
ℹ️ 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 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: 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".

Comment on lines +1062 to +1064
if self._load_token != token:
try:
clear_gpu_cache()

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 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 👍 / 👎.

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

Copy link
Copy Markdown
Member Author

@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.

@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: 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:

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 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 👍 / 👎.

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

pre-commit-ci Bot and others added 2 commits September 24, 2026 13:55
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 36f97d8276

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 24, 2026
@danielhanchen danielhanchen self-assigned this Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: bb223abb34

ℹ️ 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 merged commit 676a801 into main Sep 25, 2026
43 of 46 checks passed
@danielhanchen
danielhanchen deleted the fix-unload-mid-generate-vram branch September 25, 2026 18:16
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant