Pidoku

Model Lifecycle: Loading, Warmup, Unloading

Module 20 Lesson 20.h 1h Difficulty 3/5

Prerequisites 3.g, 20.g


Before you start: words you need#

WordPlain meaning
CheckpointThe files that hold a model’s weights, plus its config and tokenizer.
safetensorsThe standard weight file format: a plain header and raw tensor bytes, safe to load (no code runs) and easy to read in parallel.
WarmupRunning dummy work before real traffic, so that one-time costs (compiling, tuning, allocating) are not paid by a user.
JITJust-in-time: compiled or loaded the first time it is used, not before.
CUDA graphA recorded sequence of GPU kernels replayed with one launch (5.f). Engines capture them at startup.
ReadinessThe signal that a replica may receive traffic (20.b).
Sleep modevLLM’s way to release GPU memory while the process stays alive, so it can wake in seconds instead of starting again.

1. What is it?#

Everything that happens to a model between “it exists in storage” and “it is serving traffic correctly”, and back again:

STORED → FETCHED → LOADED → INITIALIZED → WARMED → READY → DRAINING → ASLEEP or UNLOADED

Each step has a cost, a way to fail, and a decision to make. This lesson walks through them for one replica. How a fleet uses them to scale is 20.g; how several models share GPUs is 20.i.

Facts checked on 12 November 2026.


2. Why does it matter?#

  • Cold start is the sum of these steps, and cold start decides how useful autoscaling is, which decides how much headroom you pay for (20.g).
  • “Mysterious slowness on the first request” is almost always an unfinished warmup.
  • Silent wrong answers often come from this stage too: a corrupted shard, a mismatched tokenizer, the wrong revision of a checkpoint. They produce plausible output, not errors.

3. Simple analogy#

Opening a restaurant for the evening.

Deliveries arrive (fetch), go into the fridges (load), the stations are set up (initialize), the cooks make a test plate of every dish on the menu (warm up), and only then does the host start seating guests (ready). At closing, the host stops seating, the last tables finish (drain), and the kitchen is cleaned down or simply left ready for tomorrow (asleep).

A restaurant that seats guests before the test plates finds out about the broken grill from a customer.


4. Tiny example: timing the phases#

This program starts a server, then marks when it answers its health check, how long the first request takes, and how long ten more take.

Go
// coldstart.go — start a server process and time each phase of its cold start.
//
//	go run coldstart.go vllm serve Qwen/Qwen3-1.7B
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"time"
)

const base = "http://localhost:8000"

func generate(model string, maxTokens int) error {
	body := fmt.Sprintf(`{"model":%q,"prompt":"test","max_tokens":%d}`, model, maxTokens)
	resp, err := http.Post(base+"/v1/completions", "application/json", bytes.NewBufferString(body))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	_, err = io.Copy(io.Discard, resp.Body)
	return err
}

func main() {
	model := os.Args[len(os.Args)-1]
	marks := []struct {
		name string
		at   time.Time
	}{{"start", time.Now()}}
	mark := func(name string) {
		marks = append(marks, struct {
			name string
			at   time.Time
		}{name, time.Now()})
	}

	srv := exec.Command(os.Args[1], os.Args[2:]...)
	srv.Stdout, srv.Stderr = os.Stderr, os.Stderr
	if err := srv.Start(); err != nil {
		panic(err)
	}
	defer srv.Process.Kill()
	mark("process started")

	for { // the health endpoint answers once weights are loaded and the engine is up
		if resp, err := http.Get(base + "/health"); err == nil && resp.StatusCode == 200 {
			break
		}
		time.Sleep(200 * time.Millisecond)
	}
	mark("healthy (loaded)")

	generate(model, 1)
	mark("first request")
	for i := 0; i < 10; i++ {
		generate(model, 32)
	}
	mark("steady (10 more)")

	for i := 1; i < len(marks); i++ {
		fmt.Printf("%-18s %7.1f s\n", marks[i].name, marks[i].at.Sub(marks[i-1].at).Seconds())
	}
}

It needs a GPU and a model, so we cannot print one fixed output here. What to look for when you run it:

  • “healthy (loaded)” is most of the time: tens of seconds for a small model with weights on local disk, minutes for a large one or a cold download. The server log breaks it down: weight loading, memory profiling, torch.compile, CUDA graph capture (16.b).
  • “first request” should be close to a normal request, because vLLM warms up before it opens its port. If it is several times slower than the steady requests, something on the request path was left for first use (section 6).
  • “steady” is your baseline.

Run it twice. The second run reuses the compile cache in ~/.cache/vllm and the operating system’s page cache for the weights, and is much faster: that difference is what a warm node cache buys.


5. Technical explanation#

Fetch#

Object storage or model hub → node (local disk, or straight into memory)

Decisions:
  - Cache on the node?        yes: node-local NVMe shared by pods, or an OCI image volume
  - Stream instead of copy?   Run:ai Model Streamer reads straight to the GPU (3.g)
  - Copy from a peer GPU?     NVIDIA ModelExpress, when a replica already holds the weights
  - Pin the exact revision?   YES: a hub name without a commit hash can change under you
  - Verify integrity?         YES: checksums; a corrupted shard gives garbage, not an error
  - Which format?             safetensors: no code runs on load, parallel reads are easy

Load#

disk or network → host memory → GPU memory

  - read shards in parallel, through pinned (page-locked) buffers
  - with tensor parallelism each GPU loads only its own slice
  - GPUDirect Storage can skip host memory where supported (3.g)

Layout conversion happens here, ONCE:
  - repacking weights for quantized kernels (Marlin and similar)
  - concatenating Q/K/V and gate/up weights for fused matrix multiplies
  - dtype conversion if the checkpoint does not match

Initialize#

  - set up NCCL communicators between GPUs (tensor / pipeline parallel, 9.f)
  - build the tokenizer and chat template
  - PROFILE MEMORY: run one dummy batch of the full token budget to find peak activation
    memory, then give the rest of the allowed memory to the KV cache (17.h)
  - compile (torch.compile) and capture CUDA graphs for a ladder of batch sizes (18.d)

The memory profile uses the token budget (max_num_batched_tokens), not the longest request, so the budget changes how much cache you get and max_model_len does not (20.d).

Warm up#

The first time any code path runs, it pays one-time costs:

  - GPU kernels are loaded on first launch (CUDA's default is lazy loading)
  - GEMM libraries pick and sometimes benchmark an algorithm per new shape
  - memory allocators grow their pools
  - kernels not covered by a captured CUDA graph run uncompiled the first time
  - a grammar for structured output is compiled the first time a schema is seen (18.e)
  - a LoRA adapter is loaded the first time it is requested (18.g)

Modern engines do most of this before they open their port: vLLM compiles, captures graphs for its batch-size ladder and runs dummy sampler and kernel warmups during initialization. What they cannot warm is what depends on your traffic: your JSON schemas, your adapters, your system prompts in the prefix cache. Warm those yourself before declaring ready:

Go
// Warmup sends requests through the paths the engine cannot know about,
// before the replica is marked ready.
func Warmup(ctx context.Context, c *Client, schemas []Schema, adapters []string, systemPrompts []string) error {
	for _, s := range schemas { // compile each structured-output grammar once
		if err := c.Generate(ctx, Request{Prompt: "warmup", MaxTokens: 4, JSONSchema: s}); err != nil {
			return err
		}
	}
	for _, a := range adapters { // load each hot LoRA adapter into a GPU slot
		if err := c.Generate(ctx, Request{Model: a, Prompt: "warmup", MaxTokens: 1}); err != nil {
			return err
		}
	}
	for _, p := range systemPrompts { // put shared prompt prefixes in the prefix cache
		if err := c.Generate(ctx, Request{System: p, Prompt: "warmup", MaxTokens: 1}); err != nil {
			return err
		}
	}
	return nil
}

Ready#

Readiness becomes true only after initialization and your warmup. vLLM’s /health is true as soon as the port opens, so if you warm up afterwards, put your own readiness check in front (a sidecar or the router’s view of the pod) rather than probing /health alone.

Drain#

1. Readiness → false; the router stops sending new requests
2. In-flight generations continue
3. After a deadline, abort whatever remains, with a clear error
4. Free memory and exit, or go to sleep

20.g covers grace periods and the Kubernetes side.

Asleep or unloaded#

Freeing GPU memory in a running process is hard: CUDA graphs, cached allocator blocks and communicators all point into it. For years the only reliable unload was to exit the process. vLLM’s sleep mode (--enable-sleep-mode) makes it possible in place:

LevelFreesKeepsWake-up
1KV cache; weights copied to host memoryThe process, compiled graphs, the weights in host RAMCopy weights back: seconds
2KV cache and weightsThe process and its compiled stateReload weights from storage, or receive new ones (used for reinforcement-learning weight updates)

The /sleep and /wake_up endpoints are development-mode endpoints (VLLM_SERVER_DEV_MODE=1); keep them off any network users can reach. Lesson 20.i uses sleep mode to switch between models on one GPU.


6. Under the hood: why the first request can still be slow#

1. Lazy kernel loading: CUDA loads each kernel's code on its first launch.
   CUDA_MODULE_LOADING=EAGER loads everything at start: slower startup, faster first request.
2. GEMM heuristics or autotuning on a shape not seen during warmup.
3. Allocator growth: cudaMalloc is slow and synchronizing until the pool is big enough.
4. NCCL: the first collective sets up its connections.
5. Shapes outside the captured CUDA graph ladder run without graphs.
6. Python modules imported lazily on the request path.
7. Traffic-dependent state: grammars, adapters, an empty prefix cache.

Items 1–5 are mostly handled by the engine’s own warmup. Items 6–7 are yours.


7. Performance implications#

  • Loading is usually the biggest phase, and the most improvable: streaming, node caches and peer-to-peer copies turn minutes into tens of seconds (3.g, 20.g).
  • Compilation is the second: a persisted compile cache turns a minute or more into seconds.
  • Graph capture trades startup for speed. Capturing fewer batch sizes starts faster and runs a little slower at the sizes left out (18.d).
  • Once loading is fast, warmup and autotuning dominate. For very large mixture-of-experts models NVIDIA reports they can take minutes.
  • Sleep turns a cold start into a wake-up at the cost of host memory: a 70B model at BF16 needs about 140 GB of host RAM to sleep at level 1.

8. Production implications#

  • Pin checkpoint revisions by commit hash and record them in the model version (20.j).
  • Verify checksums after download. A corrupted shard produces plausible garbage.
  • Cache or stream weights; never download per pod.
  • Ship pre-quantized, pre-converted checkpoints; do layout conversion at load, never per request.
  • Persist the compile cache on a volume shared by restarts.
  • Warm your traffic-specific paths (schemas, adapters, system prompts) and gate readiness on that warmup.
  • Log each phase’s duration and alert when one grows.
  • Drain before exit, with a grace period longer than your longest generation.

9. Common mistakes#

  1. Readiness before warmup. Real users pay the first-use costs.
  2. Warming only the generic path. The first structured-output request or the first request for an adapter is slow, and it is a customer’s.
  3. Unpinned revisions. A model update upstream silently changes your outputs.
  4. No checksum verification.
  5. Downloading weights from object storage in every pod. Minutes and money.
  6. Quantizing or compiling at every start.
  7. Exposing sleep or dev-mode endpoints to the network.

10. Hands-on exercise#

A. Time the phases. Run coldstart.go against a small model twice in a row. Explain the difference using the server log.

B. Prove warmup matters. Measure the first and tenth request for several paths: a short prompt, a long prompt, a structured-output request with a new JSON schema, and a request for a LoRA adapter. Which need your own warmup?

C. Load faster. Compare default loading with --load-format runai_streamer for a 7–8B model from local NVMe and from S3-compatible storage. How close to disk or network bandwidth do you get?

D. Sleep and wake. Start vLLM with --enable-sleep-mode (dev mode, on your own machine). Time /sleep?level=1 and /wake_up against a full restart. Watch GPU memory with nvidia-smi.

E. Drain test. Start long generations, trigger a drain, and check that none is truncated and that new requests are refused.


11. Interview questions#

  1. Walk through the lifecycle of a model replica from storage to serving and back.
  2. Why is the first request to a fresh replica sometimes slow, when the engine already warmed up?
  3. How does the engine decide how much KV cache to allocate?
  4. How would you make loading faster? Rank the techniques.
  5. Why pin checkpoint revisions and verify checksums?
  6. What does vLLM’s sleep mode free at levels 1 and 2, and when would you use each?
  7. What is the correct drain procedure for an LLM replica?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in