Home / AI & GenAI

AI & GenAIHow-toAdvanced

vLLM sleep mode: swapping several rarely used models on one GPU without cold starts

Run several vLLM servers on one GPU and keep only one awake. Covers level 1 and level 2 sleep, host RAM sizing, a safe swap controller, stale cache risks and failure modes.

Deepak Bhardwaj8 min read

Applies tovLLM with sleep mode (GPU builds), NVIDIA GPUs, Linux, Docker or Kubernetes

You have three models that each get a few requests an hour, and one GPU that fits only one of them at a time. Restarting vLLM for every switch means loading weights, capturing CUDA graphs and possibly compiling again. Sleep mode keeps the process alive and frees most of its GPU memory, so a switch is mainly a memory copy.

This post sets up two servers on one GPU, swaps them safely, and covers what breaks.

What sleep does

Level 1 Level 2
Weights Copied to CPU memory Discarded
KV cache Discarded Discarded
Host RAM cost About the size of the weights Small
Wake Copy back to GPU Reload from disk or a trainer
Use when You will wake the same model Host RAM is tight, or the weights will change

Neither level frees everything. The CUDA context, captured CUDA graphs and some library allocations stay on the GPU. That residue is the number that decides how many sleepers fit beside one awake model, so measure it.

Sleep mode is a poor fit when two models get steady traffic. Each swap blocks one of them, and every wake starts with an empty prefix cache.

Check the host first

nvidia-smi --query-gpu=memory.total,memory.used --format=csv
free -g
# Weight size per model, a good estimate of level 1 RAM cost
du -shL /models/model-a /models/model-b

For level 1, plan host RAM for the weights of every model that can be asleep at the same time, plus the page cache and the normal process memory. In Kubernetes this memory counts against the container's memory limit, so a limit sized for a normal vLLM pod gets OOMKilled on its first sleep.

Start the servers one at a time

--gpu-memory-utilization is applied per server, and startup checks and profiling look at the memory on the device. If server A is awake when B starts, B fails to allocate. Start A, sleep it, then start B.

export VLLM_SERVER_DEV_MODE=1

vllm serve /models/model-a --served-model-name model-a \
  --host 127.0.0.1 --port 8001 \
  --enable-sleep-mode --gpu-memory-utilization 0.85 &

until curl -sf http://127.0.0.1:8001/health; do sleep 5; done
curl -sf -X POST 'http://127.0.0.1:8001/sleep?level=1'
nvidia-smi --query-compute-apps=pid,used_memory --format=csv

vllm serve /models/model-b --served-model-name model-b \
  --host 127.0.0.1 --port 8002 \
  --enable-sleep-mode --gpu-memory-utilization 0.85 &

Record what nvidia-smi shows for the sleeping process. Keep --gpu-memory-utilization low enough that one awake model plus the residue of all the others fits, with some margin.

Caution

VLLM_SERVER_DEV_MODE=1 exposes /sleep, /wake_up, /collective_rpc and other administrative endpoints. Anyone who can reach the port can stop the model or call worker methods. Bind to localhost and expose only /v1/* through your proxy. Don't rely on the vLLM API key to protect these paths.

Swap with a controller, not a script

The controller has three jobs: allow only one awake model, drain requests before sleeping, and never wake B until A has really released memory.

import asyncio
import httpx

BACKENDS = {"model-a": "http://127.0.0.1:8001",
            "model-b": "http://127.0.0.1:8002"}
awake: str | None = None      # set from /is_sleeping at startup
inflight = 0
cond = asyncio.Condition()
client = httpx.AsyncClient(timeout=300)

async def sleeping(url: str) -> bool:
    r = await client.get(f"{url}/is_sleeping")
    r.raise_for_status()
    return r.json()["is_sleeping"]

async def swap_to(name: str) -> None:
    global awake
    # Reconcile with reality: a backend may have restarted awake.
    for other, url in BACKENDS.items():
        if other != name and not await sleeping(url):
            (await client.post(f"{url}/sleep", params={"level": 1})).raise_for_status()
            if not await sleeping(url):
                raise RuntimeError(f"{other} did not go to sleep")
    awake = None
    url = BACKENDS[name]
    if await sleeping(url):
        (await client.post(f"{url}/wake_up")).raise_for_status()
        if await sleeping(url):
            raise RuntimeError(f"{name} did not wake")
    awake = name

async def acquire(name: str) -> str:
    """Call before proxying a request. Waits for other model's requests to drain."""
    global inflight
    async with cond:
        while True:
            if awake == name:
                break
            if inflight == 0:
                await swap_to(name)
                break
            await cond.wait()
        inflight += 1
    return BACKENDS[name]

async def release() -> None:
    """Call in a finally block after the response stream closes."""
    global inflight
    async with cond:
        inflight -= 1
        cond.notify_all()

Run one controller process per GPU: this state is in memory, so two proxy workers would fight each other. For streams, call release() after the last byte or on client disconnect, not when headers are sent.

Stop thrashing and starvation

The code above lets a busy model starve the other, because new model-a requests keep inflight above zero. Add two limits before production:

  • Minimum residency: keep a model awake for a set time before another swap, so alternating requests don't cause a swap per request.
  • Maximum wait: once a request for another model has waited too long, stop admitting new requests to the awake model and let it drain.

Set the residency from measurement. If a swap takes S seconds and you accept a fraction f of time spent swapping, the average residency needs to be roughly S * (1 - f) / f.

Use level 2 when host RAM is short

Level 2 needs an explicit reload. Waking without it leaves parameters undefined, and the server can return fluent-looking garbage with HTTP 200.

B=http://127.0.0.1:8002
set -e
curl -sf -X POST "$B/sleep?level=2"
# later
curl -sf -X POST "$B/wake_up?tags=weights"
curl -sf -X POST "$B/collective_rpc" -H 'Content-Type: application/json' \
  -d '{"method":"reload_weights"}'
curl -sf -X POST "$B/wake_up?tags=kv_cache"
curl -sf "$B/is_sleeping"

is_sleeping stays true until every component is awake, so it is also your check for a half-finished wake.

After a level 2 wake, run a canary before admitting traffic:

curl -sf "$B/v1/completions" -H 'Content-Type: application/json' -d '{
  "model":"model-b","prompt":"The capital of France is","max_tokens":5,"temperature":0}' \
  | jq -e '.choices[0].text | test("Paris")'

Warning

If you change weights during sleep, local KV cache is discarded but an external KV store may not be. Block hashes don't include the weights, so old entries can match new requests. Use a different cache_salt per weight version, or clear the external cache. Sleeping resets an attached connector's cache by default; reset_connector=false keeps it.

Symptoms and fixes

Symptom Cause Fix
/sleep returns 404 Dev mode not set in the server's environment Set VLLM_SERVER_DEV_MODE=1 on the process and restart
Container OOMKilled on sleep Level 1 weights exceed the memory limit Raise the limit or use level 2
Second server fails at startup with CUDA OOM First server awake, or residue larger than planned Sleep it first, lower --gpu-memory-utilization
Wake fails with CUDA OOM Another model woke or restarted in the meantime Reconcile with /is_sleeping before each wake
Garbage output after wake Level 2 wake without reload_weights Sleep again, run the full sequence, canary
High TTFT for a while after wake Prefix cache is empty Expected; replay the shared system prompt once
Requests hang or fail during sleep Client reached vLLM without the controller Block direct access to backend ports

The restart trap

A crashed backend restarts awake and tries to take its full share of memory while another model holds the GPU. Under a restart policy it crash-loops, and it can disturb the healthy model. Make restart a controller action: sleep all others, start the process, wait for /health, then sleep it.

For the same reason, don't put the two servers in separate Kubernetes pods that each request nvidia.com/gpu: 1. The second pod stays Pending because the GPU is already allocated, sleeping or not. Run them as processes in one container, or use an explicit GPU sharing mechanism.

Probes

A sleeping server is healthy but can't serve. Probe the process for liveness and the controller for readiness. Don't use a completion request as a liveness probe, or the kubelet will kill every sleeper.

Prevent it next time

  • Record per-model residue, sleep time and wake time after every vLLM upgrade. They change with the build and with CUDA graph settings.
  • Alert on swaps per hour and on queue time waiting for a swap. Both rising means the models need separate GPUs.
  • Test the controller by killing a backend during a swap and confirming that the other model still answers.
  • Pin the vLLM version. Dev endpoints are not a stable public API, so check vllm serve --help and the sleep mode page before you upgrade.