Skip to content

fix: clear backend buffer caches after idle weight release - #2418

Merged
leejet merged 1 commit into
masterfrom
fix/idle-weight-buffer-cache
Nov 25, 2026
Merged

leejet merged 1 commit into
masterfrom
fix/idle-weight-buffer-cache

Conversation

@leejet

@leejet leejet commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Clear idle backend buffer caches after --weight-staging-ttl releases GPU staging copies or --weight-residency-ttl unloads model components. This returns VRAM held by buffers that re-entered the cache during weight release.
  • Document the behavior in the server and C API guides.

Related Issue / Discussion

Fix #2411.

Additional Information

N/A

Checklist

Summary by CodeRabbit

  • New Features
    • Releasing idle GPU staging or unloading cached models now also clears idle reusable buffers on supported backends.
  • Documentation
    • Updated the C API guide, API reference, and server guide to describe the buffer-clearing behavior. The existing busy status during active execution or generation remains unchanged.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

DGL staging release and model unloading now clear idle backend buffer caches. The API and server documentation describes this behavior. The existing busy condition remains unchanged.

Changes: DGL cleanup behavior

Layer / File(s) Summary
Clear backend caches during cleanup
include/stable-diffusion.h, src/dgl/dgl.cpp, docs/guides/c_api.md, examples/server/README.md
The DGL cleanup functions clear backend buffer caches after releasing idle GPU staging or unloading models. The API and server documentation describes the behavior and retains the existing busy condition.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

Possibly related PRs

Suggested reviewers: stduhpf, wbruna

Merge Risk: Minimal · up to f4189

After idle weight release, the server now also clears backend buffer caches, which should return VRAM held by cached buffers. The change is small and the docs match it. No concrete merge-blocking risk was found. The exact amount of VRAM returned is not measured here.

Pre-merge checks: Passed 3 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive Issue #2411 asks that idle usage return close to the fresh-start footprint (about 128 MiB versus about 4.2 GiB after idle unload). The reviewed head adds clear_backend_buffer_caches in src/dgl/dgl.c… Provide evidence that the idle VRAM drops near the fresh-start level after the change. Such evidence can be a measurement on a CUDA backend with --weight-residency-ttl or a test that checks buffer cache release. If the change releases onl…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names the main change: after idle weight release, the code clears backend buffer caches. The raw summary confirms that clear_backend_buffer_caches is added to src/dgl/dgl.cpp and called from…
Description check Passed The description follows the template. It has Summary, Related Issue / Discussion, Additional Information, and Checklist sections. The Summary explains what changed and why: idle backend buffer caches …
Out of Scope Changes check Passed All changed areas relate to the linked issue. The code change in src/dgl/dgl.cpp adds backend buffer cache clearing only to the two existing idle release entry points, sd_dgl_ctx_release_staging and…
Full details: Title check

Explanation

The title names the main change: after idle weight release, the code clears backend buffer caches. The raw summary confirms that clear_backend_buffer_caches is added to src/dgl/dgl.cpp and called from sd_dgl_ctx_release_staging and sd_dgl_ctx_unload_models. The title uses the conventional fix: prefix and is concise and specific.

Full details: Description check

Explanation

The description follows the template. It has Summary, Related Issue / Discussion, Additional Information, and Checklist sections. The Summary explains what changed and why: idle backend buffer caches are cleared after --weight-staging-ttl or --weight-residency-ttl releases memory, returning VRAM. It links issue #2411 and notes that the docs were updated. Both checklist items are checked. The Additional Information section says N/A, which is acceptable. The description does not mention that the proposed full-context unload from the linked issue is not implemented, so a reviewer could read 'Fix #2411' as a complete fix. That gap is minor and does not block the check.

Full details: Out of Scope Changes check

Explanation

All changed areas relate to the linked issue. The code change in src/dgl/dgl.cpp adds backend buffer cache clearing only to the two existing idle release entry points, sd_dgl_ctx_release_staging and sd_dgl_ctx_unload_models. Both keep the existing lock_idle busy check. The documentation changes in docs/guides/c_api.md, examples/server/README.md, and include/stable-diffusion.h describe this same behavior. The summary reports no changes to exported declarations. No unrelated change is evident.

Full details: Linked Issues check

Explanation

Issue #2411 asks that idle usage return close to the fresh-start footprint (about 128 MiB versus about 4.2 GiB after idle unload). The reviewed head adds clear_backend_buffer_caches in src/dgl/dgl.cpp. It calls sd_backend_clear_buffer_cache for each backend in ctx.backends after release_idle_gpu_staging() in sd_dgl_ctx_release_staging and after ctx->unload_models() in sd_dgl_ctx_unload_models. The code path is consistent with the stated fix. However, the diff text was unavailable, so the change was read only from the head file blob. The code does not show which allocations make up the remaining ~4 GiB, such as CUDA pool or runtime allocations. No test or measurement in the supplied evidence shows that clearing these caches releases that memory. The PR description also states that it does not implement the full-context unload the issue proposes as the alternative. The coding requirement to release near-fresh-start VRAM is therefore not established.

Resolution

Provide evidence that the idle VRAM drops near the fresh-start level after the change. Such evidence can be a measurement on a CUDA backend with --weight-residency-ttl or a test that checks buffer cache release. If the change releases only part of the 4.2 GiB, the remaining gap must be stated. The issue then needs either a further release mechanism or a maintainer decision on the opt-in context-idle unload that the issue proposes.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d00aa45b-7ae6-4ec8-b8cd-a2e1d853c3bb
Commits

Reviewing files that changed from the base of the PR and between 79dc7ca and f418983.

Files selected for processing: 4

  • docs/guides/c_api.md
  • examples/server/README.md
  • include/stable-diffusion.h
  • src/dgl/dgl.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@leejet
leejet merged commit 5303199 into master Nov 25, 2026
11 checks passed
@leejet
leejet deleted the fix/idle-weight-buffer-cache branch November 25, 2026 18:39
filve pushed a commit to filve/diffusione-in-tempo-reale that referenced this pull request Nov 25, 2026
Brings in the six upstream commits after 79dc7ca:
- idle weight release also clears the reusable buffers of the backends
  (leejet#2418);
- RelayVSR KV graph cuts, and DGL failures that say which memory ran out
  (leejet#2419);
- DGL jobs can be cancelled (leejet#2420);
- --api-key, --api-key-file and --cors-origins in server_access.{h,cpp}
  (leejet#2367);
- ClipProj-MiniMax-H3 without the MLP (leejet#2410);
- inline media previews in the DGL editor, GET /sdcpp/v1/view and
  --no-media-view (leejet#2423).

Conflicts, and how they were resolved:
- Server access. This fork had its own --api-key (one key) and
  --cors-origins (empty = reflect any origin) in a pre-routing handler in
  main.cpp. Upstream's SDHttpServer replaces them: the handler, its three
  helpers and the two string options are gone. What changes for clients:
  by default only the server's own origin is accepted, so a page of
  another origin gets 403, and so does a request whose Host is not
  localhost, the listen address or an IP; GET / and OPTIONS need no key;
  several keys and a key file are accepted. Programs that send no Origin
  (curl, Python, Node's fetch, termico.py) are not affected.
- Cancelling DGL jobs. Upstream stops a DGL job through the server's only
  context. Here a script runs on the keeper's context, or on a temporary
  one (ContextKeeper::with_context), so execute_dgl_job starts the
  JobCancellationMonitor inside with_context, with an action that calls
  sd_dgl_ctx_cancel on that context. The monitor takes its action as a
  callable, and the keeper-based monitor of the generation jobs is built
  on it. The fork's CancelToken (job.cancel.requested) stays in place of
  upstream's job.cancel_requested. The cancel route keeps ?wait= and now
  stops DGL jobs too.
- Console progress. Upstream turns console_progress on for the server's
  context; here the keeper's create_context hook turns it on for every
  context the keeper creates, after the file access policy.
- runtime.cpp: --disable-degradation and --no-media-view are both kept.
- include/stable-diffusion.h: the sd_dgl_ctx_set comment lists the fork's
  memory_guard and disable_backend_fallback and upstream's
  console_progress.
- api.md: the fork's description of the cancel route stays, and names DGL
  jobs.

Needed without a conflict: test/memory_guard_engine_test.cpp follows the
new ensure_compute_backend_capacity() signature.

test: test/server_cancel_e2e.py stops DGL jobs too: poll_url, progress,
a stop without ?wait=, a queued DGL job, ?wait=30, and a DGL job and an
image job that complete afterwards. The server it starts gets --model-dir
with the folder of the model, because a DGL script reads models only from
the model directories; --skip-dgl leaves the part out for models that are
not SD 1.x.

docs: docs/convivenza_applicazioni.md and docs/integrazione_progetti.md
describe the new default for origins and the 403; entry 25 of the fork
history describes this sync and what was tested; test/README.md lists
the new part of the cancel test.

Verified with a CPU build: the library, sd-cli and sd-server build
without warnings in the fork's files; all nine unit-test programs pass;
with the synthetic SD 1.5 model test/server_cancel_e2e.py passes its 46
checks (35 as before, 11 on DGL jobs), and against a server whose DGL
stop never reaches the script two of them fail; a scratch check of the
access control (31 checks: keys, key file, origins, a foreign Host,
GET /, preflight, /sdcpp/v1/view, bad options) and the scratch smoke test
of the server (22 checks) pass; Node's fetch, which an Electron main
process uses, still gets through; test/security_smoke.sh (19 checks),
termico_test.py (127) and agenti_guardiano_test.py (66, and 91 with a
real server once its jobs ask for 100 steps, as fix_to_claude already
does) pass; the DGL built-in catalog is current. Not tried: a real GPU,
Windows, a script that runs out of memory, a reverse proxy.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
filve pushed a commit to filve/diffusione-in-tempo-reale that referenced this pull request Nov 25, 2026
Brings in the sync 5 merge of fork-pull (1d95e26): upstream's access
control (SDHttpServer with --api-key, --api-key-file and --cors-origins,
same origin by default), DGL jobs that report their progress and can be
stopped through the job routes, GET /sdcpp/v1/view and --no-media-view,
and the library fixes of leejet#2418, leejet#2419 and leejet#2410.

Conflicts:
- examples/server/main.cpp: the guardian's halted hook of the keeper
  stays next to the create_context hook, which now also turns
  console_progress on.
- examples/server/routes_dgl.cpp: POST /sdcpp/v1/dgl/jobs keeps the
  guardian's refusal inside upstream's with_dgl_errors, which replaces
  local_dgl_route; common/media_io.h goes, as upstream, and guardian.h
  stays.
- test/README.md: this branch's rows, with the DGL part of the
  server_cancel_e2e.py row from fork-pull.
- docs/integrazione_progetti.md merged without a conflict, but git put
  the sync 5 paragraph after entry 27; it is back at the end of entry 25,
  where fork-pull has it.

What changes on this branch: the guardian now also stops a DGL job that
is running when it halts the server, and the job ends failed with the
code halted; before, a DGL script could not be stopped and ran to its
end. examples/server/api.md and entry 26 of the fork history say so.

Verified with a CPU build of this tree: all twelve unit-test programs
pass; with the synthetic SD 1.5 model server_guardian_e2e.py passes its
70 checks, server_cancel_e2e.py its 46, agenti_guardiano_test.py 66
without a server and 91 with one; a scratch check of the guardian with a
DGL job (6 checks: the running script ends halted within 0.2 s with the
reason, a new script is refused with 503, the server resumes, a script
after the resume completes), the scratch access check (31) and the
scratch smoke test of the server (22) pass; security_smoke.sh (19
checks) and termico_test.py (161) pass; the DGL built-in catalog is
current. Not tried: a real GPU, Windows, ThreadSanitizer on the server
itself.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
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.

[Bug/Feature] Idle weight TTL unloads components but retains ~4.2 GiB VRAM (128 MiB after restart)

1 participant