Skip to content

Studio: return freed host memory to the OS after diffusion and video unload - #11795

Merged
danielhanchen merged 2 commits into
mainfrom
fix-diffusion-host-ram-release
Sep 25, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix-diffusion-host-ram-release

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Unloading an image or video model in Studio leaves most of its host memory mapped. Host RSS grows by about 6 GiB per SDXL-Turbo load / unload cycle and stays 14+ GiB high after unloading Wan2.2-TI2V-5B, until the process exits. This returns those pages to the OS at the end of every unload.

Root cause

Loading a pipeline stages every weight through host memory. After unload the tensors are gone (torch allocated memory is about 9 MiB), but glibc keeps the freed pages in its arenas instead of returning them. A malloc_trim(0) probe after two cycles dropped anonymous RSS from 19.3 GiB to 3.3 GiB, so nothing is holding a reference; this is allocator retention.

#10184 added a trim, but only after a generation under the model offload policy. A GPU-resident load never uses that policy, and unload never trims, so the pages stay mapped.

Fix

  • diffusion_memory.reclaim_host_memory(): the same allocator call and once-only logging as reclaim_offload_host_memory(), without the offload-policy gate. reclaim_offload_host_memory() now calls it after its policy check, so its behaviour is unchanged.
  • Call it at the end of DiffusionBackend._unload_locked() (unload, and before a replacement load) and VideoBackend._teardown_state_locked(), after clear_gpu_cache() has run gc.

It never touches live tensors, device caches or generation, and unsupported allocators or failures are non-fatal, as before.

Results

Host anonymous RSS in GiB, from the Studio diffusion edge suite, fast tier, SDXL-Turbo and Wan2.2-TI2V-5B, one B200. Base is main at 9a8f246.

Check Surface main this PR
Idle, then after load / render / unload cycles 1 and 2 in-process 8.63, 14.48, 19.34 2.33, 2.66, 2.82
Idle, then after load / render / unload cycles 1 and 2 HTTP server 8.07, 14.10, 14.45 2.00, 2.32, 2.47
Nothing loaded after image, video, image in-process 28.42 4.00
Nothing loaded after image, video, image HTTP server 30.21 3.23

image.leak_cycles and switch.video_to_image fail on main and pass with this change on both surfaces. Across the 50 fast-tier checks the summed check time was 881 s on main and 837 s here, so the trim adds no visible cost to unload.

Testing

  • New unit tests: reclaim_host_memory() ignores the offload policy and stays best-effort, and both the image unload and the video teardown trim after clear_gpu_cache() with the state already dropped.
  • tests/test_diffusion_memory.py, tests/test_diffusion_backend.py, tests/test_video_backend.py: 910 passed.
  • Diffusion edge suite, fast tier, both surfaces, on main and on this branch: 44 pass / 6 fail on main, 48 / 2 here. The two left are the mid-render VRAM case and a 1536x1536 render refused for lack of free VRAM on a shared GPU; the same check fails on main under the same load.
  • Tiny tier on this branch: image.leak_cycles and switch.video_to_image pass on both surfaces.

image.unload_during_generate (VRAM held after unloading mid-render) is a separate issue, fixed in #11790.

Risk

Low. The trim runs once per unload, after the model is gone, on the same code path #10184 already uses after generation, including its Linux, macOS and Windows handling.

Overlap with #11766

#11766 changes the same two lines (it wraps clear_gpu_cache() in a try and releases pinned host memory in the finally), so whichever merges second has a small conflict. The resolution is to keep both, with reclaim_host_memory() after release_pinned_host_memory() so the trim runs once the pinned chunks are gone.

…unload

Loading a diffusion or video pipeline stages every weight through host
memory. Once the model is unloaded, glibc keeps those freed pages mapped,
so host RSS grew by about 6 GiB per SDXL-Turbo load / unload cycle and
stayed 14+ GiB high after unloading Wan2.2-TI2V-5B. torch allocated
memory after unload was about 9 MiB, and a malloc_trim(0) probe dropped
RSS from 19.3 GiB to 3.3 GiB, so this is allocator retention, not a live
reference.

The trim added in #10184 only runs after a generation under the model
offload policy, so it never fires for a GPU-resident model or on unload.
Add reclaim_host_memory(), the same allocator call without the policy
gate, and call it at the end of the image unload (_unload_locked, also
used before a replacement load) and the video teardown, after
clear_gpu_cache() has run gc.
@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-25T14:59:29.852557Z 3135911 Manual request
🔒 Security Review ✅ Completed 2026-09-25T15:00:05.325344Z 3135911 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 Summary

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

Review Status Commit Review trigger
🔒 Security Review 🔄 Running since 2026-09-24T09:55:00.372136Z c79b4ab 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: c79b4ab700

ℹ️ 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 7756 to +7759
clear_gpu_cache()
# clear_gpu_cache() ran gc, so the pipeline's host staging buffers are freed but still mapped by
# the allocator; return them, or host RSS grows by several GiB per load / unload cycle.
reclaim_host_memory(logger = logger)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reclaim host pages even when GPU cache clearing fails

When clear_gpu_cache() raises—an intentional behavior for sticky CUDA faults that is explicitly covered by the existing unload tests—execution never reaches this new reclamation call, even though the model state has already been deleted and its host pages are eligible for trimming. The same ordering exists in VideoBackend._teardown_state_locked, so an unload following such a fault can still retain the multi-GiB host RSS this change is intended to release; invoke the best-effort reclaimer from a finally around the cache-clearing step.

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.

Not changing this. clear_gpu_cache() only raises on a sticky CUDA fault, which leaves the CUDA context unusable until the process restarts, and the restart returns every host page anyway. Trimming in that state changes nothing a user can act on, and the unload still surfaces the fault as before.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 24, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c79b4ab700

ℹ️ 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 self-assigned this Sep 25, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex security review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3135911c6c

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 3135911c6c

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
@danielhanchen
danielhanchen merged commit 3d2e576 into main Sep 25, 2026
46 checks passed
@danielhanchen
danielhanchen deleted the fix-diffusion-host-ram-release branch September 25, 2026 16:59
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…unload (unslothai#11795)

* Studio: return freed host memory to the OS after diffusion and video unload

Loading a diffusion or video pipeline stages every weight through host
memory. Once the model is unloaded, glibc keeps those freed pages mapped,
so host RSS grew by about 6 GiB per SDXL-Turbo load / unload cycle and
stayed 14+ GiB high after unloading Wan2.2-TI2V-5B. torch allocated
memory after unload was about 9 MiB, and a malloc_trim(0) probe dropped
RSS from 19.3 GiB to 3.3 GiB, so this is allocator retention, not a live
reference.

The trim added in unslothai#10184 only runs after a generation under the model
offload policy, so it never fires for a GPU-resident model or on unload.
Add reclaim_host_memory(), the same allocator call without the policy
gate, and call it at the end of the image unload (_unload_locked, also
used before a replacement load) and the video teardown, after
clear_gpu_cache() has run gc.

* Trim comments on host memory reclaim
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.

2 participants