kv-routing-sim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of kv-routing-sim might be problematic. Click here for more details.

Files changed (61) hide show
  1. kv_routing_sim/__init__.py +18 -0
  2. kv_routing_sim/browser.py +163 -0
  3. kv_routing_sim/cache/__init__.py +6 -0
  4. kv_routing_sim/cache/block_pool.py +351 -0
  5. kv_routing_sim/cache/block_trie.py +117 -0
  6. kv_routing_sim/cache/capacity.py +70 -0
  7. kv_routing_sim/calib/__init__.py +7 -0
  8. kv_routing_sim/calib/calibrate.py +678 -0
  9. kv_routing_sim/calib/fit.py +96 -0
  10. kv_routing_sim/cli.py +313 -0
  11. kv_routing_sim/data/__init__.py +31 -0
  12. kv_routing_sim/data/cost_model.yaml +73 -0
  13. kv_routing_sim/data/profiles/index.yaml +25 -0
  14. kv_routing_sim/data/profiles/t4-qwen3-4b-vllm0.30.0-ctx.json +53 -0
  15. kv_routing_sim/data/profiles/t4-qwen3-4b-vllm0.30.0.json +33 -0
  16. kv_routing_sim/eval/__init__.py +21 -0
  17. kv_routing_sim/eval/bootstrap.py +131 -0
  18. kv_routing_sim/eval/cost.py +115 -0
  19. kv_routing_sim/eval/edge.py +97 -0
  20. kv_routing_sim/eval/pareto.py +101 -0
  21. kv_routing_sim/eval/rank.py +42 -0
  22. kv_routing_sim/eval/recommend.py +113 -0
  23. kv_routing_sim/eval/spread.py +68 -0
  24. kv_routing_sim/eval/sweep.py +125 -0
  25. kv_routing_sim/policies/__init__.py +11 -0
  26. kv_routing_sim/policies/base.py +95 -0
  27. kv_routing_sim/policies/consistent_hash_prefix.py +48 -0
  28. kv_routing_sim/policies/least_loaded.py +15 -0
  29. kv_routing_sim/policies/lmetric.py +111 -0
  30. kv_routing_sim/policies/power_of_two.py +27 -0
  31. kv_routing_sim/policies/radix_affinity.py +92 -0
  32. kv_routing_sim/policies/radix_affinity_balanced.py +24 -0
  33. kv_routing_sim/policies/registry.py +62 -0
  34. kv_routing_sim/policies/round_robin.py +21 -0
  35. kv_routing_sim/policies/session_sticky.py +36 -0
  36. kv_routing_sim/policies/smetric_local.py +139 -0
  37. kv_routing_sim/profiles.py +168 -0
  38. kv_routing_sim/report.py +186 -0
  39. kv_routing_sim/service.py +340 -0
  40. kv_routing_sim/sim/__init__.py +6 -0
  41. kv_routing_sim/sim/cost_model.py +175 -0
  42. kv_routing_sim/sim/engine.py +250 -0
  43. kv_routing_sim/sim/metrics.py +153 -0
  44. kv_routing_sim/sim/replica.py +226 -0
  45. kv_routing_sim/traces/__init__.py +7 -0
  46. kv_routing_sim/traces/adapters/__init__.py +20 -0
  47. kv_routing_sim/traces/adapters/agentx.py +178 -0
  48. kv_routing_sim/traces/adapters/bailian.py +141 -0
  49. kv_routing_sim/traces/adapters/base.py +102 -0
  50. kv_routing_sim/traces/adapters/mooncake.py +160 -0
  51. kv_routing_sim/traces/adapters/openai_log.py +80 -0
  52. kv_routing_sim/traces/adapters/vllm_jsonl.py +56 -0
  53. kv_routing_sim/traces/generator.py +252 -0
  54. kv_routing_sim/traces/hashing.py +112 -0
  55. kv_routing_sim/traces/schema.py +62 -0
  56. kv_routing_sim-0.1.0.dist-info/METADATA +685 -0
  57. kv_routing_sim-0.1.0.dist-info/RECORD +61 -0
  58. kv_routing_sim-0.1.0.dist-info/WHEEL +5 -0
  59. kv_routing_sim-0.1.0.dist-info/entry_points.txt +2 -0
  60. kv_routing_sim-0.1.0.dist-info/licenses/LICENSE +21 -0
  61. kv_routing_sim-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,18 @@
1
+ """kv-routing-sim: choose a KV-cache routing policy and a replica count for an LLM serving fleet.
2
+
3
+ A trace-driven simulator of a multi-replica vLLM fleet with a recommender on top. The cache model
4
+ follows vLLM 0.30.0's block pool and was checked against a live engine.
5
+
6
+ traces/ trace adapters and the agentic traffic generator; prompts become block hashes
7
+ cache/ the vLLM block-pool model and a plain LRU model kept as an ablation
8
+ policies/ routing policies, one class per file, behind a registry
9
+ sim/ replicas, the event loop and the timing profile
10
+ eval/ sweeps, cost, the Pareto frontier, bootstrap intervals and the recommendation
11
+ calib/ `kvsim calibrate`: fit a timing profile to a running engine
12
+ service the replay workflow shared by the command line and the browser page
13
+ cli the `kvsim` command line
14
+
15
+ See docs/05-codebase-map.md for the module contracts.
16
+ """
17
+
18
+ __version__ = "0.1.0" # keep in step with pyproject.toml
@@ -0,0 +1,163 @@
1
+ """Entry point for the in-browser page: run a replay from plain settings, return plain data.
2
+
3
+ The page runs this module under Pyodide in a web worker. Settings arrive as JSON from the page's
4
+ form. Traffic is either generated here or read from a file the page has written into Pyodide's
5
+ in-memory filesystem, so nothing the user provides leaves the browser.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import shlex
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from .report import recommendation_notes, render_markdown
16
+ from .service import ConfigError, ProgressCallback, ReplayOptions, replay
17
+ from .traces.generator import AgenticWorkload
18
+
19
+ SHIPPED_PROFILE = "t4-qwen3-4b-vllm0.30.0-ctx"
20
+ GENERATED_TRACE = "generated.jsonl"
21
+
22
+
23
+ def run(
24
+ settings: dict[str, Any],
25
+ progress: ProgressCallback | None = None,
26
+ *,
27
+ work_dir: str | Path = ".",
28
+ ) -> dict[str, Any]:
29
+ """Run one replay described by the page's settings.
30
+
31
+ Returns:
32
+ On success, {"report", "markdown", "notes", "generated", "command"}: the report as
33
+ `kvsim replay --format json` writes it, its Markdown rendering, the sentences that
34
+ qualify the recommendation, a summary of generated traffic (None for a file), and the
35
+ `kvsim` commands that reproduce the run. For invalid settings, {"error": message}.
36
+ """
37
+ try:
38
+ trace_path, trace_format, generated = _prepare_traffic(settings.get("traffic") or {},
39
+ Path(work_dir))
40
+ options = _replay_options(settings, trace_format)
41
+ report = replay(trace_path, options, progress=progress)
42
+ except ConfigError as exc:
43
+ return {"error": str(exc)}
44
+ payload = report.as_dict()
45
+ return {
46
+ "report": payload,
47
+ "markdown": render_markdown(payload),
48
+ "notes": [{"text": n.text, "warning": n.warning} for n in recommendation_notes(payload)],
49
+ "generated": generated,
50
+ "command": reproduce_command(settings),
51
+ }
52
+
53
+
54
+ def run_json(settings_json: str, progress: ProgressCallback | None = None,
55
+ work_dir: str = ".") -> str:
56
+ """JSON-in, JSON-out wrapper of `run`, which keeps None as null across the Pyodide boundary."""
57
+ return json.dumps(run(json.loads(settings_json), progress, work_dir=work_dir))
58
+
59
+
60
+ def reproduce_command(settings: dict[str, Any]) -> str:
61
+ """Return the shell commands that run the same replay with the `kvsim` command line."""
62
+ traffic = settings.get("traffic") or {}
63
+ lines = []
64
+ if traffic.get("source", "generate") == "generate":
65
+ generate = ["kvsim", "generate", "--out", GENERATED_TRACE,
66
+ "--sessions", str(traffic.get("sessions", 100)),
67
+ "--turns", str(traffic.get("turns", 6)),
68
+ "--sharing", str(traffic.get("sharing", 0.6)),
69
+ "--rate", str(traffic.get("rate", 0.25)),
70
+ "--seed", str(traffic.get("seed", 0))]
71
+ if int(traffic.get("system_prompts", 1)) != 1:
72
+ generate += ["--system-prompts", str(traffic["system_prompts"])]
73
+ lines.append(shlex.join(generate))
74
+ replay_args = ["kvsim", "replay", GENERATED_TRACE]
75
+ else:
76
+ replay_args = ["kvsim", "replay", traffic.get("name") or Path(traffic["path"]).name,
77
+ "--format-in", traffic.get("format", "vllm-jsonl")]
78
+ profile = settings.get("profile") or {}
79
+ if profile.get("source", "shipped") == "shipped":
80
+ replay_args += ["--profile", profile.get("name", SHIPPED_PROFILE)]
81
+ else:
82
+ replay_args += ["--profile", profile.get("name") or Path(profile["path"]).name]
83
+ replay_args += ["--cost-model", "default",
84
+ "--policies", str(settings.get("policies", "all")),
85
+ "--replicas", str(settings.get("replicas", "1-8")),
86
+ "--seeds", str(settings.get("seeds", 5))]
87
+ if settings.get("ttft_slo_ms") is not None:
88
+ replay_args += ["--ttft-slo-ms", str(settings["ttft_slo_ms"])]
89
+ replay_args += ["--tpot-slo-ms", str(settings.get("tpot_slo_ms", 100))]
90
+ if settings.get("gpu_price_per_hour_usd") is not None:
91
+ replay_args += ["--gpu-price-usd", str(settings["gpu_price_per_hour_usd"])]
92
+ if not settings.get("edge_check", True):
93
+ replay_args.append("--no-edge-check")
94
+ if not settings.get("spread", True):
95
+ replay_args.append("--no-spread")
96
+ lines.append(shlex.join(replay_args))
97
+ return "\n".join(lines)
98
+
99
+
100
+ def _prepare_traffic(traffic: dict[str, Any],
101
+ work_dir: Path) -> tuple[Path, str, dict[str, Any] | None]:
102
+ """Return the trace file to replay, its format, and a summary when it was generated."""
103
+ if traffic.get("source", "generate") == "file":
104
+ if not traffic.get("path"):
105
+ raise ConfigError("choose a trace file")
106
+ return Path(traffic["path"]), traffic.get("format", "vllm-jsonl"), None
107
+ try:
108
+ workload = AgenticWorkload(
109
+ n_sessions=_positive_int(traffic.get("sessions", 100), "sessions"),
110
+ turns_per_session=_positive_int(traffic.get("turns", 6), "turns per session"),
111
+ prefix_sharing_ratio=float(traffic.get("sharing", 0.6)),
112
+ arrival_rate=float(traffic.get("rate", 0.25)),
113
+ seed=int(traffic.get("seed", 0)),
114
+ n_shared_prefixes=_positive_int(traffic.get("system_prompts", 1), "system prompts"),
115
+ )
116
+ except (TypeError, ValueError) as exc:
117
+ raise ConfigError(str(exc)) from None
118
+ work_dir.mkdir(parents=True, exist_ok=True)
119
+ path = work_dir / GENERATED_TRACE
120
+ summary = workload.write_jsonl(str(path))
121
+ return path, "vllm-jsonl", summary
122
+
123
+
124
+ def _replay_options(settings: dict[str, Any], trace_format: str) -> ReplayOptions:
125
+ profile = settings.get("profile") or {}
126
+ if profile.get("source", "shipped") == "shipped":
127
+ profile_spec = profile.get("name", SHIPPED_PROFILE)
128
+ elif profile.get("path"):
129
+ profile_spec = str(profile["path"])
130
+ else:
131
+ raise ConfigError("choose a profile file")
132
+ try:
133
+ return ReplayOptions(
134
+ policies=str(settings.get("policies", "all")),
135
+ replicas=str(settings.get("replicas", "1-8")),
136
+ seeds=_positive_int(settings.get("seeds", 5), "seeds"),
137
+ trace_format=trace_format,
138
+ cost_model="default",
139
+ profile=profile_spec,
140
+ ttft_slo_ms=_optional_float(settings.get("ttft_slo_ms")),
141
+ tpot_slo_ms=float(settings.get("tpot_slo_ms", 100)),
142
+ gpu_price_per_hour_usd=_optional_float(settings.get("gpu_price_per_hour_usd")),
143
+ edge_check=bool(settings.get("edge_check", True)),
144
+ spread=bool(settings.get("spread", True)),
145
+ )
146
+ except (TypeError, ValueError) as exc:
147
+ raise ConfigError(str(exc)) from None
148
+
149
+
150
+ def _positive_int(value: Any, name: str) -> int:
151
+ try:
152
+ number = int(value)
153
+ except (TypeError, ValueError):
154
+ raise ConfigError(f"{name} must be a whole number") from None
155
+ if number < 1 or number != float(value):
156
+ raise ConfigError(f"{name} must be a whole number of at least 1")
157
+ return number
158
+
159
+
160
+ def _optional_float(value: Any) -> float | None:
161
+ if value is None or value == "":
162
+ return None
163
+ return float(value)
@@ -0,0 +1,6 @@
1
+ """Block-level KV cache models, one instance per replica (ADR-002).
2
+
3
+ `block_pool` models vLLM's block pool and is the default (`cache_model="vllm"`); `block_trie` is a
4
+ plain LRU kept as an ablation baseline (`cache_model="lru"`); `capacity` estimates how many KV
5
+ blocks a replica can hold from a model's shape and a memory budget.
6
+ """
@@ -0,0 +1,351 @@
1
+ """A model of vLLM's KV block pool, the default cache model (`cache_model="vllm"`).
2
+
3
+ It behaves differently from the plain LRU of `block_trie.py` once the cache fills, which is the
4
+ regime where routing matters. Each behaviour implements the vLLM source it cites, at the v0.30.0
5
+ tag, and is not tuned against measurements (ADR-002):
6
+
7
+ frees a finished request's blocks tail first single_type_kv_cache_manager.py:580
8
+ only blocks with ref_cnt 0 are evictable block_pool.py `free_blocks`, `touch`
9
+ uncached blocks are reused first (prepended, LIFO) block_pool.py:789, `prepend_n`
10
+ cached blocks are reused last (appended, FIFO) block_pool.py:792, `append_n`
11
+ capacity includes partial and decode blocks block_pool.py `get_new_blocks`
12
+ full decode blocks are cached too kv_cache_manager.py:595-599
13
+ a fully cached prompt still recomputes a block kv_cache_manager.py:295
14
+ an eviction event fires on any recycle block_pool.py:739, before the check at 741
15
+ one block is reserved as the null block block_pool.py:193
16
+
17
+ Assumptions not yet checked against a live engine:
18
+ * Hashes are committed at scheduling time (`cache_blocks` runs inside `allocate_slots`), so a
19
+ request admitted later in the same step can hit blocks an earlier one is about to compute.
20
+ * Decode-block hashes are unique per request. In an open-loop replay no later prompt contains a
21
+ request's output tokens, so only the same request, after preemption, can hit those blocks.
22
+ * There is no chunked prefill and no token budget: a prompt is allocated in one step. This affects
23
+ TTFT under load more than hit rate.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ from collections import OrderedDict, deque
30
+ from collections.abc import Sequence
31
+ from dataclasses import dataclass, field
32
+
33
+
34
+ def max_hit_blocks(num_tokens: int, block_size: int) -> int:
35
+ """Return how many full blocks a lookup may hit, by vLLM's rule; both cache models apply it.
36
+
37
+ When every prompt token is cached, vLLM still recomputes the last token to obtain logits, and
38
+ because computed tokens must be block-aligned it recomputes that whole block
39
+ (kv_cache_manager.py:290-295). A fully cached 512-token prompt hits 31 blocks, not 32.
40
+ """
41
+ return max(0, num_tokens - 1) // block_size
42
+
43
+
44
+ def _h64(data: bytes) -> int:
45
+ return int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), "big")
46
+
47
+
48
+ @dataclass(slots=True)
49
+ class _BlockMetrics:
50
+ """kv_cache_metrics.py `BlockMetricsState`: per-block metrics, in simulated time."""
51
+
52
+ birth: float
53
+ last_access: float
54
+ # Only the last four accesses are kept (kv_cache_metrics.py:24), so at most three reuse gaps
55
+ # per block, biased toward the end of its life.
56
+ history: deque[float] = field(default_factory=lambda: deque(maxlen=4))
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class EvictionEvent:
61
+ """One `KVCacheEvictionEvent`, the record behind the three `vllm:kv_block_*` histograms."""
62
+
63
+ lifetime_s: float
64
+ idle_s: float
65
+ reuse_gaps_s: tuple[float, ...]
66
+ # True only for a real eviction; vLLM emits the event either way (block_pool.py:739).
67
+ was_cached: bool
68
+
69
+
70
+ class VllmBlockPool:
71
+ """One replica's KV block pool, with vLLM's free-queue order, reference counts and eviction.
72
+
73
+ The free queue is an OrderedDict of block ids whose front is the next block to be reused. vLLM
74
+ hand-rolls a doubly linked list for O(1) removal from the middle (kv_cache_utils.py:246); an
75
+ OrderedDict gives the same O(1) popleft, append, prepend and remove.
76
+ """
77
+
78
+ def __init__(
79
+ self, num_blocks: int, block_size: int = 16, track_block_metrics: bool = False
80
+ ) -> None:
81
+ """Create a pool with every usable block free.
82
+
83
+ Args:
84
+ num_blocks: vLLM's `num_gpu_blocks`, as set by `--num-gpu-blocks-override` and reported
85
+ in the engine's log. One of them is the null block, so `num_blocks - 1` are usable.
86
+ """
87
+ if num_blocks <= 1:
88
+ raise ValueError(f"num_blocks must be > 1 (one is the null block), got {num_blocks}")
89
+ self.num_blocks = num_blocks
90
+ self.block_size = block_size
91
+
92
+ # The free queue starts ordered by block id (kv_cache_utils.py:255).
93
+ self._free: OrderedDict[int, None] = OrderedDict((b, None) for b in range(num_blocks))
94
+ # Block 0 is reserved as the null block and never allocated (block_pool.py:193). It only
95
+ # shows with a small cache, where it moves every prediction by one block.
96
+ self.null_block, _ = self._free.popitem(last=False)
97
+ self._ref = [0] * num_blocks
98
+ self._hash: list[int | None] = [None] * num_blocks
99
+ # cached hash -> its parent's hash, for the no-stranding invariant
100
+ self._parent: dict[int, int | None] = {}
101
+ # hash -> the block ids holding it. vLLM allows duplicates and returns the first
102
+ # (block_pool.py `get_cached_block`).
103
+ self._by_hash: dict[int, dict[int, None]] = {}
104
+
105
+ # Per request: its block table, how many of those blocks are committed (hashed), and the
106
+ # hash chain it has built, kept across preemption so the request can hit it again.
107
+ self._req_blocks: dict[str, list[int]] = {}
108
+ self._req_committed: dict[str, int] = {}
109
+ self._req_chain: dict[str, list[int]] = {}
110
+
111
+ # Counters in tokens, as vLLM counts (ADR-008). Lookups by preempted requests are kept
112
+ # separate, as vllm/v1/metrics/stats.py `PrefixCacheStats.record` does, because the
113
+ # Prometheus prefix-cache counters exclude them.
114
+ self.queries = 0
115
+ self.hits = 0
116
+ self.preempted_queries = 0
117
+ self.preempted_hits = 0
118
+ self.real_evictions = 0 # a popped block that held a hash
119
+
120
+ self.track_block_metrics = track_block_metrics
121
+ self._metrics: dict[int, _BlockMetrics] = {}
122
+ self.eviction_events: list[EvictionEvent] = []
123
+
124
+ @property
125
+ def num_free(self) -> int:
126
+ return len(self._free)
127
+
128
+ @property
129
+ def usable_blocks(self) -> int:
130
+ return self.num_blocks - 1 # the null block is never allocated
131
+
132
+ @property
133
+ def hit_rate(self) -> float:
134
+ return self.hits / self.queries if self.queries else 0.0
135
+
136
+ def is_cached(self, h: int) -> bool:
137
+ return h in self._by_hash
138
+
139
+ def blocks_of(self, request_id: str) -> list[int]:
140
+ return list(self._req_blocks.get(request_id, []))
141
+
142
+ def chain_for(self, request_id: str, prompt_hashes: Sequence[int]) -> Sequence[int]:
143
+ """Return the hashes to look up: a preempted request's own chain, else the prompt's.
144
+
145
+ vLLM's `_preempt_request` keeps a request's tokens and frees only its KV, so after
146
+ preemption the request looks up its prompt and decode blocks.
147
+ """
148
+ return self._req_chain.get(request_id) or prompt_hashes
149
+
150
+ def lookup(self, block_hashes: Sequence[int], num_tokens: int) -> list[int]:
151
+ """Return the longest cached prefix as block ids.
152
+
153
+ Stops at the first miss, as `FullAttentionManager.find_longest_cache_hit` does in
154
+ single_type_kv_cache_manager.py, and at the `max_hit_blocks` cap (kv_cache_manager.py:295).
155
+ Blocks are found whether they are in use or free.
156
+ """
157
+ limit = min(len(block_hashes), max_hit_blocks(num_tokens, self.block_size))
158
+ hit: list[int] = []
159
+ for h in block_hashes[:limit]:
160
+ holders = self._by_hash.get(h)
161
+ if not holders:
162
+ break
163
+ hit.append(next(iter(holders))) # the first, like get_one_block
164
+ return hit
165
+
166
+ def record_lookup(self, num_tokens: int, hit_blocks: int, preempted: bool) -> None:
167
+ """Count a lookup, in tokens.
168
+
169
+ Lookups by preempted requests go to separate counters (stats.py `PrefixCacheStats.record`).
170
+ """
171
+ hit_tokens = hit_blocks * self.block_size
172
+ if preempted:
173
+ self.preempted_queries += num_tokens
174
+ self.preempted_hits += hit_tokens
175
+ else:
176
+ self.queries += num_tokens
177
+ self.hits += hit_tokens
178
+
179
+ def blocks_needed(self, num_tokens: int) -> int:
180
+ return -(-num_tokens // self.block_size) # ceil
181
+
182
+ def can_admit(self, hit_blocks: Sequence[int], num_tokens: int) -> bool:
183
+ """Return whether `admit` would succeed, as vLLM's `allocate_slots` checks it.
184
+
185
+ A hit on a free block takes it out of the free queue (block_pool.py `touch`), so it counts
186
+ against the free pool as well.
187
+ """
188
+ new = self.blocks_needed(num_tokens) - len(hit_blocks)
189
+ evictable_hits = sum(1 for b in hit_blocks if self._ref[b] == 0)
190
+ return new + evictable_hits <= self.num_free
191
+
192
+ def admit(
193
+ self,
194
+ request_id: str,
195
+ hit_blocks: Sequence[int],
196
+ prompt_hashes: Sequence[int],
197
+ num_tokens: int,
198
+ now: float,
199
+ ) -> bool:
200
+ """Allocate a request's blocks for `num_tokens` and commit its full blocks.
201
+
202
+ As kv_cache_manager.py `allocate_slots` does: touch the hit blocks, get new ones, then
203
+ `cache_blocks` up to the tokens computed this step (lines 595-599). Returns False if there
204
+ is no room.
205
+ """
206
+ if not self.can_admit(hit_blocks, num_tokens):
207
+ return False
208
+ self._touch(hit_blocks, now)
209
+ new = self._get_new_blocks(self.blocks_needed(num_tokens) - len(hit_blocks), now)
210
+ self._req_blocks[request_id] = list(hit_blocks) + new
211
+ self._req_committed[request_id] = len(hit_blocks)
212
+ chain = self._req_chain.setdefault(request_id, [])
213
+ if not chain:
214
+ chain.extend(prompt_hashes)
215
+ self._commit(request_id, num_tokens)
216
+ return True
217
+
218
+ def grow(self, request_id: str, num_tokens: int, now: float) -> bool:
219
+ """Grow a request to `num_tokens` for a decode step and commit newly full blocks.
220
+
221
+ Returns False when no block is free; the caller must then preempt (scheduler.py:726-800).
222
+ """
223
+ blocks = self._req_blocks[request_id]
224
+ need = self.blocks_needed(num_tokens) - len(blocks)
225
+ if need > self.num_free:
226
+ return False
227
+ if need > 0:
228
+ blocks.extend(self._get_new_blocks(need, now))
229
+ self._commit(request_id, num_tokens)
230
+ return True
231
+
232
+ def free(self, request_id: str) -> None:
233
+ """Release a finished or preempted request's blocks; their hashes stay cached.
234
+
235
+ Blocks are freed tail first (single_type_kv_cache_manager.py:580). When ref_cnt reaches 0,
236
+ an uncached block is prepended to the free queue and reused first, and a cached block is
237
+ appended and evicted last (block_pool.py:770-799).
238
+ """
239
+ evict_first: list[int] = []
240
+ evict_last: list[int] = []
241
+ for b in reversed(self._req_blocks.pop(request_id, [])):
242
+ self._ref[b] -= 1
243
+ if self._ref[b] == 0:
244
+ (evict_first if self._hash[b] is None else evict_last).append(b)
245
+ # prepend_n keeps list order: evict_first[0] becomes the new front (kv_cache_utils.py:411)
246
+ for b in reversed(evict_first):
247
+ self._free[b] = None
248
+ self._free.move_to_end(b, last=False)
249
+ for b in evict_last:
250
+ self._free[b] = None
251
+ self._req_committed.pop(request_id, None)
252
+
253
+ def forget(self, request_id: str) -> None:
254
+ """Drop a finished request's hash chain; a preempted request keeps its chain."""
255
+ self._req_chain.pop(request_id, None)
256
+
257
+ def _touch(self, blocks: Sequence[int], now: float) -> None:
258
+ """block_pool.py `touch`: a free block that is hit leaves the free queue; ref_cnt += 1."""
259
+ for b in blocks:
260
+ if self._ref[b] == 0:
261
+ del self._free[b]
262
+ self._ref[b] += 1
263
+ m = self._metrics.get(b)
264
+ if m is not None: # kv_cache_metrics.py `on_block_accessed`
265
+ m.last_access = now
266
+ m.history.append(now)
267
+
268
+ def _get_new_blocks(self, n: int, now: float) -> list[int]:
269
+ """block_pool.py `get_new_blocks`: pop from the front, evict, allocate."""
270
+ out: list[int] = []
271
+ for _ in range(n):
272
+ b, _ = self._free.popitem(last=False)
273
+ self._maybe_evict(b, now)
274
+ self._ref[b] = 1
275
+ if self.track_block_metrics: # sample rate 1.0: every block is tracked
276
+ self._metrics[b] = _BlockMetrics(birth=now, last_access=now)
277
+ out.append(b)
278
+ return out
279
+
280
+ def _maybe_evict(self, b: int, now: float) -> None:
281
+ """block_pool.py `_maybe_evict_cached_block`, including its ordering quirk.
282
+
283
+ Line 739 records the metrics event before line 741 checks whether the block held a hash, so
284
+ recycling a block that never held a cached prefix is still reported as an eviction. The
285
+ model does the same so that its events and the engine's histograms count by the same rule.
286
+ vLLM pull request #47715 proposes the fix upstream.
287
+ """
288
+ m = self._metrics.pop(b, None)
289
+ if m is not None:
290
+ hist = list(m.history)
291
+ gaps = tuple(hist[i] - hist[i - 1] for i in range(1, len(hist)))
292
+ self.eviction_events.append(
293
+ EvictionEvent(now - m.birth, now - m.last_access, gaps, self._hash[b] is not None)
294
+ )
295
+ h = self._hash[b]
296
+ if h is not None:
297
+ holders = self._by_hash.get(h)
298
+ if holders is not None:
299
+ holders.pop(b, None)
300
+ if not holders:
301
+ del self._by_hash[h]
302
+ self._parent.pop(h, None)
303
+ self._hash[b] = None
304
+ self.real_evictions += 1
305
+
306
+ def _commit(self, request_id: str, num_tokens: int) -> None:
307
+ """kv_cache_manager.py:595-599 `cache_blocks`: hash every block that is now full.
308
+
309
+ Prompt blocks take their hash from the trace. Decode blocks, and the block straddling the
310
+ end of the prompt, get a hash that continues the chain and is unique to this request (see
311
+ the module's assumptions). The chain is extended in place so a preempted request can hit it
312
+ again.
313
+ """
314
+ full = num_tokens // self.block_size
315
+ blocks = self._req_blocks[request_id]
316
+ chain = self._req_chain[request_id]
317
+ done = self._req_committed[request_id]
318
+ upto = min(full, len(blocks))
319
+ for i in range(done, upto):
320
+ if i >= len(chain):
321
+ parent = chain[i - 1] if i > 0 else 0
322
+ payload = parent.to_bytes(8, "big") + request_id.encode() + i.to_bytes(4, "big")
323
+ chain.append(_h64(payload))
324
+ h = chain[i]
325
+ b = blocks[i]
326
+ if self._hash[b] is None:
327
+ self._hash[b] = h
328
+ self._by_hash.setdefault(h, {})[b] = None
329
+ self._parent.setdefault(h, chain[i - 1] if i > 0 else None)
330
+ self._req_committed[request_id] = max(done, upto)
331
+
332
+ def stranded_hashes(self) -> list[int]:
333
+ """Return cached hashes whose parent is not cached, which no lookup can reach.
334
+
335
+ Tail-first freeing and the prefix rule keep a parent at or behind its children in the free
336
+ queue, so a parent is never evicted before its child and this list should be empty.
337
+ """
338
+ return [h for h, p in self._parent.items() if p is not None and p not in self._by_hash]
339
+
340
+ def check_consistency(self) -> None:
341
+ """Assert that every block is either free (ref_cnt 0) or referenced, never both."""
342
+ for b in range(self.num_blocks):
343
+ if b == self.null_block:
344
+ if b in self._free or self._ref[b] != 0:
345
+ raise AssertionError("the null block must never be allocated or freed")
346
+ continue
347
+ in_free = b in self._free
348
+ if in_free and self._ref[b] != 0:
349
+ raise AssertionError(f"block {b} is in the free queue with ref_cnt {self._ref[b]}")
350
+ if not in_free and self._ref[b] <= 0:
351
+ raise AssertionError(f"block {b} is neither free nor referenced")
@@ -0,0 +1,117 @@
1
+ """The plain-LRU prefix cache, kept as the ablation baseline (`cache_model="lru"`).
2
+
3
+ Resident blocks are a flat dict rather than a tree: a block's hash is computed from its
4
+ predecessor's, so it identifies the whole path from the root, and walking a request's hashes until
5
+ the first miss gives radix-trie semantics at O(1) per block. When a block is evicted, the blocks
6
+ after it stay resident but unreachable until LRU order evicts them; they are not counted, since that
7
+ would need a parent pointer per block.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import OrderedDict
13
+ from collections.abc import Sequence
14
+
15
+ from .block_pool import max_hit_blocks
16
+
17
+
18
+ class BlockCache:
19
+ """A single replica's prefix cache: LRU over a bounded pool of blocks.
20
+
21
+ `queries` and `hits` count tokens, as vLLM's prefix-cache counters do (ADR-008). `queries` is
22
+ every prompt token, including a partial trailing block, while `hits` can only be full blocks, so
23
+ a 513-token prompt whose 32 full blocks are all cached scores 512/513, not 1.0. `queries_blocks`
24
+ and `hits_blocks` are internal; comparisons with the engine use the token counters.
25
+ """
26
+
27
+ __slots__ = (
28
+ "_resident",
29
+ "block_size",
30
+ "capacity_blocks",
31
+ "evictions",
32
+ "hits",
33
+ "hits_blocks",
34
+ "queries",
35
+ "queries_blocks",
36
+ )
37
+
38
+ def __init__(self, capacity_blocks: int, block_size: int = 16) -> None:
39
+ if capacity_blocks <= 0:
40
+ raise ValueError(f"capacity_blocks must be > 0, got {capacity_blocks}")
41
+ if block_size <= 0:
42
+ raise ValueError(f"block_size must be > 0, got {block_size}")
43
+ self.capacity_blocks = capacity_blocks
44
+ self.block_size = block_size
45
+ # OrderedDict as an LRU: leftmost is least-recently-used.
46
+ self._resident: OrderedDict[int, None] = OrderedDict()
47
+ self.queries = 0 # tokens: every prompt token, as vLLM counts
48
+ self.hits = 0 # tokens: cached full blocks x block_size
49
+ self.queries_blocks = 0
50
+ self.hits_blocks = 0
51
+ self.evictions = 0
52
+
53
+ def __len__(self) -> int:
54
+ return len(self._resident)
55
+
56
+ @property
57
+ def hit_rate(self) -> float:
58
+ """Cached tokens over all prompt tokens, derived from the counters as vLLM defines it."""
59
+ return self.hits / self.queries if self.queries else 0.0
60
+
61
+ def lookup(self, block_hashes: Sequence[int]) -> int:
62
+ """Return the longest resident prefix in blocks, touching every hit.
63
+
64
+ Stops at the first miss, since a prefix is usable only up to its first missing block.
65
+ Insertion is a separate step (`admit`) because an engine looks up at admission and adds the
66
+ newly computed blocks as the prefill runs.
67
+ """
68
+ matched = 0
69
+ for h in block_hashes:
70
+ if h in self._resident:
71
+ self._resident.move_to_end(h)
72
+ matched += 1
73
+ else:
74
+ break
75
+ return matched
76
+
77
+ def admit(self, block_hashes: Sequence[int], matched: int) -> None:
78
+ """Insert the blocks this request computed, those after the matched prefix."""
79
+ for h in block_hashes[matched:]:
80
+ if h in self._resident:
81
+ self._resident.move_to_end(h)
82
+ else:
83
+ self._resident[h] = None
84
+ if len(self._resident) > self.capacity_blocks:
85
+ self._evict_one()
86
+
87
+ def _evict_one(self) -> None:
88
+ self._resident.popitem(last=False) # drop the least-recently-used block
89
+ self.evictions += 1
90
+
91
+ def query(self, block_hashes: Sequence[int], prompt_tokens: int | None = None) -> int:
92
+ """Look up, admit and count one request; return the number of matched blocks.
93
+
94
+ Args:
95
+ prompt_tokens: The full prompt length, including any partial trailing block that
96
+ `block_hashes` omits, which vLLM counts as queried. Without it only full blocks are
97
+ counted: exact for block-aligned prompts, biased upward otherwise.
98
+ """
99
+ tokens = prompt_tokens if prompt_tokens is not None else len(block_hashes) * self.block_size
100
+ # vLLM's lookup cap (kv_cache_manager.py:295): a fully cached prompt still recomputes its
101
+ # last block. It is a lookup rule, so both cache models apply it and the ablation between
102
+ # them compares eviction alone.
103
+ matched = self.lookup(block_hashes[: max_hit_blocks(tokens, self.block_size)])
104
+ self.queries += tokens
105
+ self.hits += matched * self.block_size
106
+ self.queries_blocks += len(block_hashes)
107
+ self.hits_blocks += matched
108
+ self.admit(block_hashes, matched)
109
+ return matched
110
+
111
+ def reset_counters(self) -> None:
112
+ """Zero the counters but keep residency, to discard a warm-up period."""
113
+ self.queries = 0
114
+ self.hits = 0
115
+ self.queries_blocks = 0
116
+ self.hits_blocks = 0
117
+ self.evictions = 0