bots-garden/razorbillpublic Fork
⑂ v0.2.0
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP
model-lifecycle.md · 62 lines · 7.3 KBmarkdown
Blame HistoryOpen raw

Model lifecycle and concurrency — explanation

What is this about?

A model is gigabytes of weights in the Mac's unified memory, and generating with it keeps the GPU busy. The server has to decide when to load a model, who may use it, what to do when several clients arrive at once, and when to give the memory back. All of that lives in one place, the model manager (ModelManager, an actor in RazorbillServer). This page explains its rules and why they were chosen.

One load, shared

A model is loaded on the first request that needs it — or at start-up when it is declared with preload: true — and then shared by every request. Two names that point to the same repository (a declared id and its Hugging Face id, or two declared entries with different settings) share one load: the manager keys models by repository and revision, not by the name the client sent. A chat load and an embedding load of the same repository are different models, because they are loaded by different engines.

One generation at a time per model

Requests for one model are served one at a time, in arrival order. The others wait in a queue of at most limits.max_queue requests; beyond it, the server answers 429 at once rather than letting clients pile up.

Why not run several generations of one model at once? Token generation on Apple Silicon is mostly limited by memory bandwidth, so interleaving independent generations gains little: each answer arrives later, and each needs its own KV cache in memory. Batching several sequences in one forward pass is what would raise throughput, and razorbill does not do it (yet). A queue is simple, fair, and gives each client the full speed of the GPU when its turn comes.

Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues.

Reusing the previous prompt

An OpenAI client keeps no state on the server: every request carries the whole conversation, system prompt, tool definitions and earlier turns included. Before it writes the first word of an answer, a model has to read the prompt and fill its KV cache, which holds the attention keys and values of every token read so far. On a long conversation this reading dominates: about 25 to 30 seconds for 4,000 tokens with Qwen3-4B on the Mac used to measure it.

The chat engine therefore keeps the KV cache of the last request on each model. That cache holds the previous prompt followed by the answer generated for it. The next request of the same conversation repeats that prompt and adds the answer, as the client received it, and a new question. The engine compares the tokens, cuts the cache back to the part both prompts share, and reads only the rest. On the same 4,000-token conversation the first word then comes in under a second. The answer is the one a fresh cache would give: with greedy decoding the two are identical, apart from the rare token where computing the prompt in different chunks changes a rounding.

The answer itself is always read again, because the client sends back only the visible text: the reasoning of thinking models is not in it, and the chat template renders earlier turns its own way. This costs a few dozen tokens per turn.

Some caches cannot be cut back. Hybrid models (Qwen3.5, Qwen3-Next, LFM2…) keep a recurrent state that cannot be rewound, and models with a sliding window (Gemma 3…) lose the start of a long conversation once the window has moved past it. For those the engine starts from an empty cache, as it does when the conversation changes (another client, another system prompt): only the shared start is ever reused, so a different conversation simply shares little or nothing.

Only one conversation per model is kept. Two clients that alternate on the same model each find the other's cache and reuse only what their prompts have in common, often just the system prompt. The cache is freed with the model, and it lives in the memory left outside the weight budget, as every KV cache already did while a request was running. Responses report the reused tokens in usage.prompt_tokens_details.cached_tokens, and the request log adds cached=N.

Making room

Two limits decide how many models stay loaded:

  • limits.max_loaded_models (default 1): a count, easy to reason about.
  • a memory budget of 75 % of the Mac's memory: the weights of the loaded models, read from the size of their .safetensors files, may not exceed it. The remaining quarter is for macOS, other applications, and the KV caches.

When a model must be loaded and one of the limits would be exceeded, the manager unloads the least recently used idle model, then the next, until the new one fits. A model that is answering is never unloaded. If every loaded model is busy, the request gets a 503 server_busy; if the model is larger than the whole budget, a 503 insufficient_memory. Failing fast was preferred to waiting: the client can retry, or the operator can change the limits, whereas a silent wait looks like a hung server.

Unloading idle models

A background service checks regularly (every quarter of keep_alive, at most every 30 seconds) and unloads models unused for limits.keep_alive (default 10 minutes). The next request loads the model again, which costs a few seconds for a small model. When the server stops (Ctrl-C, SIGTERM), every model is unloaded before the process exits.

When the client leaves

A generation nobody will read wastes the GPU and delays everyone in the queue. The server therefore watches the connection while it answers: when the client disconnects, the generation task is cancelled, the model's turn is released, and the next request starts. A request still waiting in the queue is simply removed from it.

During a stream, a client that vanishes is noticed only when a write fails. While the model is silent (loading, reading a long prompt, thinking with hidden reasoning), the server writes a : keep-alive comment every five seconds, so a departed client is noticed within seconds. Watching the connection requires reading the request to its end, which is why generation endpoints answer with Connection: close.

Rejected alternatives

  • One process per model (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator.
  • Unloading on a memory-pressure signal from macOS instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable.
  • Waiting for room instead of answering 503: a request could wait indefinitely behind long generations; a clear error is easier to act on.
  • Several cached conversations per model (an LRU of caches, like llama-server slots or vLLM's prefix caching): more memory to account for, for a gain only when clients alternate. One cache covers the common case of one agent or one chat at a time.
  • Letting mlx-swift-lm's ChatSession reuse the cache: it does, but only within one session that owns the conversation, whereas each HTTP request brings its own copy of the conversation.

How it relates to the rest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Model lifecycle and concurrency — explanation

## What is this about?

A model is gigabytes of weights in the Mac's unified memory, and generating with it keeps the GPU busy. The server has to decide when to load a model, who may use it, what to do when several clients arrive at once, and when to give the memory back. All of that lives in one place, the **model manager** (`ModelManager`, an actor in `RazorbillServer`). This page explains its rules and why they were chosen.

## One load, shared

A model is loaded on the first request that needs it — or at start-up when it is declared with `preload: true` — and then shared by every request. Two names that point to the same repository (a declared `id` and its Hugging Face id, or two declared entries with different settings) share one load: the manager keys models by repository and revision, not by the name the client sent. A chat load and an embedding load of the same repository are different models, because they are loaded by different engines.

## One generation at a time per model

Requests for one model are served **one at a time, in arrival order**. The others wait in a queue of at most `limits.max_queue` requests; beyond it, the server answers 429 at once rather than letting clients pile up.

Why not run several generations of one model at once? Token generation on Apple Silicon is mostly limited by memory bandwidth, so interleaving independent generations gains little: each answer arrives later, and each needs its own KV cache in memory. Batching several sequences in one forward pass is what would raise throughput, and razorbill does not do it (yet). A queue is simple, fair, and gives each client the full speed of the GPU when its turn comes.

Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues.

## Reusing the previous prompt

An OpenAI client keeps no state on the server: every request carries the whole conversation, system prompt, tool definitions and earlier turns included. Before it writes the first word of an answer, a model has to read the prompt and fill its **KV cache**, which holds the attention keys and values of every token read so far. On a long conversation this reading dominates: about 25 to 30 seconds for 4,000 tokens with Qwen3-4B on the Mac used to measure it.

The chat engine therefore keeps the KV cache of the last request on each model. That cache holds the previous prompt followed by the answer generated for it. The next request of the same conversation repeats that prompt and adds the answer, as the client received it, and a new question. The engine compares the tokens, cuts the cache back to the part both prompts share, and reads only the rest. On the same 4,000-token conversation the first word then comes in under a second. The answer is the one a fresh cache would give: with greedy decoding the two are identical, apart from the rare token where computing the prompt in different chunks changes a rounding.

The answer itself is always read again, because the client sends back only the visible text: the reasoning of thinking models is not in it, and the chat template renders earlier turns its own way. This costs a few dozen tokens per turn.

Some caches cannot be cut back. Hybrid models (Qwen3.5, Qwen3-Next, LFM2…) keep a recurrent state that cannot be rewound, and models with a sliding window (Gemma 3…) lose the start of a long conversation once the window has moved past it. For those the engine starts from an empty cache, as it does when the conversation changes (another client, another system prompt): only the shared start is ever reused, so a different conversation simply shares little or nothing.

Only one conversation per model is kept. Two clients that alternate on the same model each find the other's cache and reuse only what their prompts have in common, often just the system prompt. The cache is freed with the model, and it lives in the memory left outside the weight budget, as every KV cache already did while a request was running. Responses report the reused tokens in `usage.prompt_tokens_details.cached_tokens`, and the request log adds `cached=N`.

## Making room

Two limits decide how many models stay loaded:

- `limits.max_loaded_models` (default 1): a count, easy to reason about.
- a memory budget of 75 % of the Mac's memory: the weights of the loaded models, read from the size of their `.safetensors` files, may not exceed it. The remaining quarter is for macOS, other applications, and the KV caches.

When a model must be loaded and one of the limits would be exceeded, the manager unloads the **least recently used idle** model, then the next, until the new one fits. A model that is answering is never unloaded. If every loaded model is busy, the request gets a 503 `server_busy`; if the model is larger than the whole budget, a 503 `insufficient_memory`. Failing fast was preferred to waiting: the client can retry, or the operator can change the limits, whereas a silent wait looks like a hung server.

## Unloading idle models

A background service checks regularly (every quarter of `keep_alive`, at most every 30 seconds) and unloads models unused for `limits.keep_alive` (default 10 minutes). The next request loads the model again, which costs a few seconds for a small model. When the server stops (Ctrl-C, SIGTERM), every model is unloaded before the process exits.

## When the client leaves

A generation nobody will read wastes the GPU and delays everyone in the queue. The server therefore watches the connection while it answers: when the client disconnects, the generation task is cancelled, the model's turn is released, and the next request starts. A request still waiting in the queue is simply removed from it.

During a stream, a client that vanishes is noticed only when a write fails. While the model is silent (loading, reading a long prompt, thinking with hidden reasoning), the server writes a `: keep-alive` comment every five seconds, so a departed client is noticed within seconds. Watching the connection requires reading the request to its end, which is why generation endpoints answer with `Connection: close`.

## Rejected alternatives

- **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator.
- **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable.
- **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on.
- **Several cached conversations per model** (an LRU of caches, like llama-server slots or vLLM's prefix caching): more memory to account for, for a gain only when clients alternate. One cache covers the common case of one agent or one chat at a time.
- **Letting mlx-swift-lm's `ChatSession` reuse the cache**: it does, but only within one session that owns the conversation, whereas each HTTP request brings its own copy of the conversation.

## How it relates to the rest

- The keys that set these limits: [configuration reference](../reference/configuration.md#limits).
- The errors a client sees: [errors reference](../reference/errors.md#codes).
- Where the manager sits in a request: [architecture](architecture.md#the-path-of-a-chat-request).