Skip to content

feat(server): add idle TTLs for model weights - #2406

Merged
leejet merged 1 commit into
masterfrom
feat/server-weight-ttl
Nov 23, 2026
Merged

leejet merged 1 commit into
masterfrom
feat/server-weight-ttl

Conversation

@leejet

@leejet leejet commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Add --weight-staging-ttl to release idle GPU copies of RAM-backed weights while retaining the originals. This covers explicit CPU placement and auto-fit. The next request uploads the weights from RAM.
  • Add --weight-residency-ttl to unload cached model components from RAM and VRAM. The shared DGL context keeps its configuration and file-access callbacks so later requests can reload components on demand.
  • Both options use -1 to disable release by default, 0 for immediate release when idle, and positive integers for idle seconds. Running and queued jobs defer release. Status and progress polling leave the deadlines intact. When both deadlines are due, the server unloads the model once.

Related Issue / Discussion

Fix #2401.

Additional Information

N/A

Checklist

Summary by CodeRabbit

  • New Features
    • Added controls for automatically releasing idle GPU staging memory and unloading cached model components after configurable periods. Both settings are disabled by default.
    • Added API options to manually release idle staging memory or unload cached models. Models reload as needed; these operations return a busy status during generation or script execution.
    • Documented the new server settings, timing behavior, and API options.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The DGL context API adds operations to release idle GPU staging and unload cached models. The server adds TTL options and schedules these operations after jobs complete, while deferring release when jobs are active.

Changes: Idle release

Layer / File(s) Summary
DGL release operations
include/stable-diffusion.h, src/dgl/*, src/model_manager.*, docs/guides/c_api.md
The DGL API adds idle staging release and model unloading. ModelManager releases eligible staging blocks, and Context unloads cached model resources.
Server TTL options
examples/server/runtime.*, examples/server/model_catalog.cpp
The server adds --weight-staging-ttl and --weight-residency-ttl. Both default to -1; the parser accepts values of -1 or greater.
Idle release scheduling
examples/server/async_jobs.*, examples/server/routes_models.cpp, examples/server/README.md
AsyncJobManager records deadlines after context jobs complete and processes due releases while idle. Synchronous jobs defer release. The README documents the options and timing rules.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant RuntimeRoutes
  participant AsyncJobManager
  participant DGLContext
  participant ModelManager
  RuntimeRoutes->>AsyncJobManager: Record synchronous job completion
  AsyncJobManager->>DGLContext: Request staging release or model unload at deadline
  DGLContext->>ModelManager: Release eligible GPU staging blocks
Loading

Possibly related issues

Possibly related PRs

Merge Risk: Minimal · up to 1f715

Adds opt-in idle weight release options for the server, both disabled by default, so existing deployments are unaffected. No concrete merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "feat(server): add idle TTLs for model weights" matches the main change. The PR adds --weight-staging-ttl and --weight-residency-ttl to sd-server, which release idle weights after a configur…
Description check Passed The description follows the repository template. It has Summary, Related Issue / Discussion, Additional Information, and Checklist sections. The Summary explains both options, their defaults (-1, 0, p…
Linked Issues check Passed Directly linked issue #2401 asks for either (a) an option that releases offloaded GPU weight copies and per-run caches when a job ends, or (b) making that behavior the default for --offload-to-cpu i…
Out of Scope Changes check Passed All changes connect to the TTL release feature requested in #2401. The new sd_dgl_ctx_release_staging and sd_dgl_ctx_unload_models C API functions (include/stable-diffusion.h, src/dgl/dgl.cpp) pro…
Full details: Title check

Explanation

The title "feat(server): add idle TTLs for model weights" matches the main change. The PR adds --weight-staging-ttl and --weight-residency-ttl to sd-server, which release idle weights after a configurable idle time. The title is concise and uses a conventional commit prefix. It does not name the two distinct TTL options, but it accurately summarizes the primary change.

Full details: Description check

Explanation

The description follows the repository template. It has Summary, Related Issue / Discussion, Additional Information, and Checklist sections. The Summary explains both options, their defaults (-1, 0, positive seconds), deferral rules for running and queued jobs, and the single unload when both deadlines are due. It links issue #2401. Additional Information is filled with N/A. Both checklist items are checked. The model-documentation checklist item does not clearly apply to this server change, but the template includes it, so this is not a gap. The description does not mention the docs/guides/c_api.md changes or the new C API functions, but those are secondary to the server feature.

Full details: Linked Issues check

Explanation

Directly linked issue #2401 asks for either (a) an option that releases offloaded GPU weight copies and per-run caches when a job ends, or (b) making that behavior the default for --offload-to-cpu in sd-server. The PR implements option (a). --weight-staging-ttl releases idle GPU copies of RAM-backed weights while keeping the RAM originals. A value of 0 releases them immediately when idle, and running or queued jobs defer release. --weight-residency-ttl unloads cached model components from RAM and VRAM, which covers the per-run cache request. The default is -1 (disabled), so alternative (b) is not met. The issue allows either alternative, so this does not fail the check. The Qwen Image 2.1 slowdown is a reported symptom with an unconfirmed explanation (prefix cache). The objectives state it is not a confirmed requirement, so it is not assessed. Evidence is the PR summary and raw summary of changes (runtime.cpp option parsing, async_jobs.cpp deadline handling, model_manager.cpp release_idle_gpu_staging, dgl.cpp and stable-diffusion.h C API additions). I did not inspect the diff directly, so the exact release behavior rests on the summary.

Full details: Out of Scope Changes check

Explanation

All changes connect to the TTL release feature requested in #2401. The new sd_dgl_ctx_release_staging and sd_dgl_ctx_unload_models C API functions (include/stable-diffusion.h, src/dgl/dgl.cpp) provide the server's release hooks. Context::unload_models (src/dgl/context.cpp/.h) is a refactor that the residency unload uses. The protect_prefetched_states and release_idle_gpu_staging changes (src/model_manager.cpp/.h) implement the staging release. The SynchronousContextJob (routes_models.cpp) and AsyncJobManager deadline changes (async_jobs.cpp/.h) implement job-based deferral. The runtime.cpp and runtime.h changes add the options. The documentation changes (docs/guides/c_api.md, examples/server/README.md) describe these options and functions. The whitespace-only edits in model_catalog.cpp, api.cpp, and generation.h do not change behavior. They are minor, incidental edits and do not indicate unrelated work. No unrelated feature is evident in the summary.

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: ee0ee6ba-7198-40e4-9272-12ab2dcd7c4b
Commits

Reviewing files that changed from the base of the PR and between 8187e47 and 1f71578.

Files selected for processing: 16

  • docs/guides/c_api.md
  • examples/server/README.md
  • examples/server/async_jobs.cpp
  • examples/server/async_jobs.h
  • examples/server/model_catalog.cpp
  • examples/server/routes_models.cpp
  • examples/server/runtime.cpp
  • examples/server/runtime.h
  • include/stable-diffusion.h
  • src/api/api.cpp
  • src/api/generation.h
  • src/dgl/context.cpp
  • src/dgl/context.h
  • src/dgl/dgl.cpp
  • src/model_manager.cpp
  • src/model_manager.h

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

@leejet
leejet merged commit 3b12781 into master Nov 23, 2026
11 checks passed
@leejet
leejet deleted the feat/server-weight-ttl branch November 23, 2026 17:19
filve pushed a commit to filve/diffusione-in-tempo-reale that referenced this pull request Nov 24, 2026
…art 2)

Brings in the Diffusion Graph Language runtime (leejet#2396) and the commits
after it: MOSS-Image edit LoRAs (leejet#2203), runtime LoRA counts (leejet#2400),
immediate LoRA merges for INT8 weights (leejet#2403), one server context with
on-demand model loading (leejet#2404), Qwen Image 2.1 prefix caching (leejet#2405)
and idle TTLs for model weights (leejet#2406). The server changes of leejet#2404
and leejet#2406 come in the same merge so that sd-server is ported once.

src/pipeline and src/stable-diffusion.cpp are gone; the fork's
additions move into the graph runtime:
- CPU fallback: ModelRuntime::configure_backends() falls back to the cpu
  backend, with a warning, when a module's backend cannot be
  initialized; disable_backend_fallback (also a DGL context option)
  makes it fail with SD_ERROR_BACKEND instead.
- memory_guard is a DGL context option for the context's ModelManager.
  ModelManager::ResourceHandle, the residency manager the models use,
  forwards the guard hooks and honours the prefetch suspension.
- layer_split_fill is applied when the context is created; multi_gpu is
  checked there. The multi-GPU planner, which upstream no longer calls,
  picks the device of each module when auto-fit is on, more than one
  GPU is present and no backend was given (planned_backend_spec() in
  src/api/generation_program.cpp); the run plan places the weights.
- The SD2 v-parameterization probe reports a failed compute instead of
  aborting.
- sd_ctx_create, sd_ctx_set_model_options*, sd_generate_image and
  sd_generate_video record the error code again; a load failure with no
  deeper cause is model_file.

sd-server keeps the ContextKeeper as the owner of the context:
- requests pick their model as upstream does (recipe and models in the
  body); the switch goes through ContextKeeper::load(), so the profile
  ladder and the recovery cover it too;
- sd_ctx_mutex serializes model switches, generations and DGL scripts;
  a DGL script runs on the keeper's context, or on a temporary one while
  no model is loaded (ContextKeeper::with_context()); the idle TTL
  release does not wait for a running generation (try_with_context());
- every context the keeper creates gets the server's file-access policy
  (create_context_from_params() + apply_server_file_access());
- /sdcpp/v1/models/load and /unload stay, rebuilt on
  resolve_model_selection(), as do /sdcpp/v1/health and /resources;
- /sdcpp/v1/upscale and the server-side ADetailer go, as upstream did:
  both are DGL scripts now.

Tests: memory_guard_engine_test follows the new capacity hook;
server_recovery_test checks with_context() and try_with_context()
(red with both behaviours broken); api_robustness expects a missing
model file at the first generation, where the weights load now;
server_cancel_e2e.py uses 100 steps, the server's maximum.

docs: the C API section of docs/integrazione_progetti.md uses the
opaque options; backend.md says what the multi-GPU planner decides
with DGL; api.md documents the kept load/unload routes.

Verified with a CPU build: the library, sd-cli and sd-server build; all
nine unit-test programs pass, server_recovery_test eight times in a row
and twice under TSan with no warnings; with a synthetic SD 1.5 model
(random weights) sd-cli generates, falls back to the cpu backend for
--backend vulkan0 and fails as backend with --disable-backend-fallback,
and test/server_cancel_e2e.py passes its 35 checks against a real
sd-server. A scratch smoke test of the server (20 checks: no model, DGL
jobs with and without a model, models/load and unload, a job that picks
its model, the idle release) passes too.

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] sd-server keeps offloaded weights on the GPU between jobs since 1117 (#2321), and Qwen Image 2.1 edits run ~40% slower

1 participant