vllm_mlx.prompt_warmup¶
Prompt warm-up for vllm-mlx.
View the complete module source at #L1-L275.
API details¶
Each callable below includes its exact signature, type annotations, inputs, defaults, return contract, documented exceptions, implementation source, and parsed docstring sections when the source provides them.
vllm_mlx.prompt_warmup
¶
Prompt warm-up for vllm-mlx.
At server startup, pre-populates the prefix cache by running one short generation per warm-up prompt. The first user request that shares a prefix with a warmed prompt sees cache-hit TTFT instead of cold prefill latency.
File format (JSON): [ [{"role": "system", "content": "You are ..."}], [{"role": "system", "content": "..."}, {"role": "user", "content": "hi"}] ]
Each entry is a list of chat messages — same shape as a /v1/chat/completions
messages field. The warmer runs a max_tokens=1 chat completion for each,
which flows through the exact same path as a real request and writes the KV
state to the prefix cache.
Paths resolve from the current working directory. A single-message system prompt is sufficient if that is the shared prefix.
Sizing note: prompts are warmed concurrently via asyncio.gather, so N
entries fire N concurrent prefills at startup. Each prefill allocates KV
cache for its prompt length. For typical agent deployments 1–3 entries
(one per active persona) cover the hot paths; a very large warm-prompts
file on a memory-tight model can exhaust headroom at boot.
vllm_mlx.prompt_warmup.load_warmup_file
¶
Load and validate a warm-up prompts JSON file.
Raises:
-
FileNotFoundError–If the file does not exist.
-
ValueError–If the file shape is invalid.
Source code in vllm_mlx/prompt_warmup.py
vllm_mlx.prompt_warmup._ensure_user_terminator
¶
Ensure the message list ends with a user message.
Some chat templates (Qwen3.6, DeepSeek-VL, a handful of others) require
at least one user message or raise TemplateError: No user query found.
We prefer to cache just the system prefix, but when the template won't
render without a user, append a minimal placeholder. The common prefix
up to the start of user content still matches real requests, so the
system tokens still get cached.
Source code in vllm_mlx/prompt_warmup.py
vllm_mlx.prompt_warmup._build_strict_prefix_string
¶
_build_strict_prefix_string(tokenizer: Any, messages: list[dict[str, Any]], enable_thinking: bool = True) -> str | None
Build a STRING prefix that is a prefix of any real request's rendered chat template for the same system and empty chat history.
Strategy: render the chat template twice with two DIFFERENT user contents
and tokenize=False (matching what the server does). Truncate the
first output at the position where the two strings diverge — that's
where user content gets inserted.
We return a STRING (not tokens) because the engine's request path also
applies the template with tokenize=False and then lets the tokenizer
encode the result. Going through the same pipeline guarantees the warm
entry's tokens are a strict prefix of a real request's tokens.
This enables warm-prompts on hybrid SSM+attention models where LCP matching is disabled (SSM state can't be trimmed) — they rely purely on strict PREFIX match.
Returns None if rendering fails or the two probes don't diverge past a reasonable prefix length (unusual template).
Source code in vllm_mlx/prompt_warmup.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
vllm_mlx.prompt_warmup.warm_prefix_cache
async
¶
warm_prefix_cache(engine: Any, prompts: list[list[dict[str, Any]]], *, max_tokens: int = 1) -> dict[str, Any]
Run each prompt through the engine to populate the prefix cache.
Prefers the strict-prefix path when the engine exposes a tokenizer:
manually tokenize with add_generation_prompt=False and feed the
raw token IDs to the engine's stream_generate (which accepts
prompt: str | list[int]). Real requests — which always use
add_generation_prompt=True — will then find the warm entry as an
exact strict prefix, independent of the engine's LCP matcher.
This is the difference between warm-prompts helping dense models only and helping hybrid SSM+attention models too.
Falls back to engine.stream_chat with a placeholder user message
appended if no tokenizer is exposed — strict-prefix match won't apply
there, so the feature is effectively LCP-only for that engine.
Runs all prompts concurrently (asyncio.gather).
Parameters:
-
engine(Any) –The vllm-mlx engine (exposes
stream_chatand optionallytokenizer+stream_generate). -
prompts(list[list[dict[str, Any]]]) –List of message arrays.
-
max_tokens(int, default:1) –Tokens to generate per warm-up. 1 is enough.
Returns:
-
dict[str, Any]–Dict with
count,skipped,elapsed_ms, -
dict[str, Any]–total_prompt_tokens, andmode("strict-prefix"or -
dict[str, Any]–"chat-fallback") describing which path was used.
Source code in vllm_mlx/prompt_warmup.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
Complete contract reference¶
Expand any definition for its exact inputs, annotations, defaults, return contract, directly raised exceptions, source-grounded behavior, and immutable line link. This section includes private and nested definitions that ordinary API generators omit.
vllm_mlx.prompt_warmup.load_warmup_file · function
Load and validate a warm-up prompts JSON file.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
path |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[list[dict[str, Any]]] - Direct return expressions:
data
Exceptions and behavior
Function load_warmup_file calls Path(path).expanduser, Path, p.exists, FileNotFoundError; can raise FileNotFoundError, ValueError; returns data.
Directly raised exceptions: FileNotFoundError, ValueError.
vllm_mlx.prompt_warmup._ensure_user_terminator · function
vllm_mlx.prompt_warmup._ensure_user_terminator(messages: list[dict[str, Any]]) -> list[dict[str, Any]]
Ensure the message list ends with a user message.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
messages |
list[dict[str, Any]] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict[str, Any]] - Direct return expressions:
messages;[*messages, {'role': 'user', 'content': ' '}]
Exceptions and behavior
Function _ensure_user_terminator calls messages[-1].get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prompt_warmup._build_strict_prefix_string · function
vllm_mlx.prompt_warmup._build_strict_prefix_string(tokenizer: Any, messages: list[dict[str, Any]], enable_thinking: bool = True) -> str | None
Build a STRING prefix that is a prefix of any real request's rendered chat template for the same system and empty chat history.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokenizer |
Any |
yes |
none |
Required positional or keyword input. |
messages |
list[dict[str, Any]] |
yes |
none |
Required positional or keyword input. |
enable_thinking |
bool |
no |
True |
Optional positional or keyword input; defaults to True. |
Returns
- Type:
str | None - Direct return expressions:
None;a[:boundary]
Exceptions and behavior
Function _build_strict_prefix_string calls getattr, apply, _with_user, kwargs.pop; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prompt_warmup._build_strict_prefix_string._with_user · nested function
vllm_mlx.prompt_warmup._build_strict_prefix_string._with_user(user_content: str) -> list[dict[str, Any]]
Nested Function _build_strict_prefix_string._with_user calls dict, msgs[-1].get; returns msgs.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
user_content |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[dict[str, Any]] - Direct return expressions:
msgs
Exceptions and behavior
Nested Function _build_strict_prefix_string._with_user calls dict, msgs[-1].get; returns msgs.
No direct raise statement appears in this definition.
vllm_mlx.prompt_warmup.warm_prefix_cache · function
async vllm_mlx.prompt_warmup.warm_prefix_cache(engine: Any, prompts: list[list[dict[str, Any]]], *, max_tokens: int = 1) -> dict[str, Any]
Run each prompt through the engine to populate the prefix cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
engine |
Any |
yes |
none |
The vllm-mlx engine (exposes stream_chat and optionally tokenizer + stream_generate). |
prompts |
list[list[dict[str, Any]]] |
yes |
none |
List of message arrays. |
max_tokens |
int |
no |
1 |
Tokens to generate per warm-up. 1 is enough. |
Returns
- Type:
dict[str, Any] - Direct return expressions:
{'count': completed, 'skipped': skipped, 'elapsed_ms': elapsed_ms, 'total_prompt_tokens': total_prompt_tokens, 'mode': …
Exceptions and behavior
Function warm_prefix_cache calls getattr, hasattr, time.perf_counter, asyncio.gather; awaits asynchronous work; returns {'count': completed, 'skipped': skipped, 'elapsed_ms': elapsed_ms, 'total_prompt_tokens': total_prompt_tokens, 'mode': ….
No direct raise statement appears in this definition.
vllm_mlx.prompt_warmup.warm_prefix_cache._one_strict · nested function
async vllm_mlx.prompt_warmup.warm_prefix_cache._one_strict(idx: int, messages: list[dict[str, Any]]) -> tuple[int, int, str | None]
Nested Function warm_prefix_cache._one_strict calls _build_strict_prefix_string, _one_chat, engine.stream_generate, int; awaits asynchronous work; has 3 explicit return paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
idx |
int |
yes |
none |
Required positional or keyword input. |
messages |
list[dict[str, Any]] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[int, int, str | None] - Direct return expressions:
await _one_chat(idx, messages);(1, int(output.prompt_tokens or 0), None);(0, 0, 'no finished output')
Exceptions and behavior
Nested Function warm_prefix_cache._one_strict calls _build_strict_prefix_string, _one_chat, engine.stream_generate, int; awaits asynchronous work; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prompt_warmup.warm_prefix_cache._one_chat · nested function
async vllm_mlx.prompt_warmup.warm_prefix_cache._one_chat(idx: int, messages: list[dict[str, Any]]) -> tuple[int, int, str | None]
Nested Function warm_prefix_cache._one_chat calls _ensure_user_terminator, engine.stream_chat, int, type; has 3 explicit return paths.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
idx |
int |
yes |
none |
Required positional or keyword input. |
messages |
list[dict[str, Any]] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
tuple[int, int, str | None] - Direct return expressions:
(1, int(output.prompt_tokens or 0), None);(0, 0, 'no finished output');(0, 0, err)
Exceptions and behavior
Nested Function warm_prefix_cache._one_chat calls _ensure_user_terminator, engine.stream_chat, int, type; has 3 explicit return paths.
No direct raise statement appears in this definition.
Complete symbol map¶
This map also includes private definitions and nested helpers. The signature column exposes every explicit input even when an internal helper has no dedicated parameter prose.
| Symbol | Kind | Signature and inputs | What it does | Source |
|---|---|---|---|---|
load_warmup_file |
function | load_warmup_file(path: str) -> list[list[dict[str, Any]]] |
Load and validate a warm-up prompts JSON file. | #L41-L76 |
_ensure_user_terminator |
function | _ensure_user_terminator(messages: list[dict[str, Any]]) -> list[dict[str, Any]] |
Ensure the message list ends with a user message. | #L79-L91 |
_build_strict_prefix_string |
function | _build_strict_prefix_string(tokenizer: Any, messages: list[dict[str, Any]], enable_thinking: bool = True) -> str \| None |
Build a STRING prefix that is a prefix of any real request's rendered chat template for the same system and empty chat history. | #L94-L176 |
_build_strict_prefix_string._with_user |
nested function | _build_strict_prefix_string._with_user(user_content: str) -> list[dict[str, Any]] |
Nested Function _build_strict_prefix_string._with_user calls dict, msgs[-1].get; returns msgs. |
#L121-L127 |
warm_prefix_cache |
function | async warm_prefix_cache(engine: Any, prompts: list[list[dict[str, Any]]], *, max_tokens: int = 1) -> dict[str, Any] |
Run each prompt through the engine to populate the prefix cache. | #L179-L275 |
warm_prefix_cache._one_strict |
nested function | async warm_prefix_cache._one_strict(idx: int, messages: list[dict[str, Any]]) -> tuple[int, int, str \| None] |
Nested Function warm_prefix_cache._one_strict calls _build_strict_prefix_string, _one_chat, engine.stream_generate, int; awaits asynchronous work; has 3 explicit return paths. |
#L217-L235 |
warm_prefix_cache._one_chat |
nested function | async warm_prefix_cache._one_chat(idx: int, messages: list[dict[str, Any]]) -> tuple[int, int, str \| None] |
Nested Function warm_prefix_cache._one_chat calls _ensure_user_terminator, engine.stream_chat, int, type; has 3 explicit return paths. |
#L237-L253 |