Skip to content

Commit 675d4c2

Browse files
gilbyashhart
authored andcommitted
feat: spill evicted conversation prefixes to disk, and --checkpoint-slots
An evicted conversation costs a full prefill on its next turn: GDN state cannot be truncated to a shorter stored prefix, and conversations were only written to disk at shutdown (the newest two). Under several interleaved conversations that is a 20-70 s re-prefill each time one comes back. - CheckpointStore gains an on_evict hook, called outside the lock for each evicted conversation from both insert() (slot and byte budget) and evict_one() (memory pressure). An older checkpoint of a conversation that moved on (a strict prefix of a remaining entry) and pinned system blocks are skipped. - spill_conversation() writes the entry to the session-snapshot directory, which _read_disk_block already searches, and keeps this model's files there under a byte limit (oldest first). - --spill-gib N (default 0: off) turns it on; with it, the shutdown save keeps the whole directory within the same limit instead of the newest two. - --checkpoint-slots N: the store also caps entries at max(3 x lanes, 8), which with 30K-token conversations (~2 GiB each on Qwen3.8-27B) binds at ~16 GiB whatever --prompt-cache-gib says. Measured on an M5 Ultra, Vontra/Qwen3.8-27B-MLX-4bit + DFlash2, --prompt-cache-gib 6 --checkpoint-slots 4 --spill-gib 20: conversation A (35,583 tokens) evicted by three others; each spill wrote 2.2-2.4 GiB in 0.18-0.19 s; A's next turn read its prefix back in 0.24 s and answered in 2.3 s, against 26.2 s cold, with byte-identical output. Tests: tests/test_checkpoint_spill.py; full suite 1787 passed, 84 skipped (tests/cuda not run).
1 parent ad174a0 commit 675d4c2

4 files changed

Lines changed: 194 additions & 5 deletions

File tree

‎src/tensorfold/cli.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ def build_parser() -> argparse.ArgumentParser:
6969
help="lane kernels for Qwen3.8 dense (auto: on GPUs with tensor units)")
7070
speed.add_argument("--prompt-cache-gib", type=float, default=None,
7171
help="memory for cached conversation prefixes (0: off; default: an eighth of RAM, at most 16)")
72+
speed.add_argument("--checkpoint-slots", type=int, default=None,
73+
help="cached conversation prefixes kept in memory (default: 3 per parallel lane, at least 8); "
74+
"with long conversations this, not --prompt-cache-gib, is usually the limit")
75+
speed.add_argument("--spill-gib", type=float, default=0.0,
76+
help="write evicted conversation prefixes to disk, up to this many GiB, and read them back on "
77+
"demand instead of prefilling again (0: off; needs --snapshot-dir)")
7278
speed.add_argument("--snapshot-dir", default=str(Path.home() / ".cache" / "tensorfold" / "prefix-snapshots"),
7379
help="where system-block and conversation snapshots are kept ('none': in memory only)")
7480
speed.add_argument("--max-snapshots", type=int, default=3, help="system-block snapshots loaded at start")
@@ -547,8 +553,9 @@ def _serve_mlx(args: argparse.Namespace, family: Any, model_dir: Path, context:
547553
thinking_budget=int(args.thinking_budget),
548554
default_sampling=sampling,
549555
max_snapshots=int(args.max_snapshots),
550-
checkpoint_slots=0 if budget <= 0 else None,
556+
checkpoint_slots=0 if budget <= 0 else args.checkpoint_slots,
551557
checkpoint_budget_bytes=budget if budget > 0 else None,
558+
spill_bytes=int(float(args.spill_gib) * 1024**3),
552559
memory_budget_bytes=memory_limit,
553560
fit_context=args.context is None,
554561
use_proposer=not args.no_drafts,

‎src/tensorfold/server/app.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from tensorfold.engine.lane_engine import LaneEngine, SuffixLookupProposer
1313
from tensorfold.server.admission import concurrency
14-
from tensorfold.server.checkpoints import CheckpointStore, longest_common_prefix, save_conversations
14+
from tensorfold.server.checkpoints import CheckpointStore, longest_common_prefix, save_conversations, spill_conversation
1515
from tensorfold.server.cancellation import Cancellation
1616
from tensorfold.server.errors import RequestError
1717
from tensorfold.server.request_options import RequestOptions
@@ -79,6 +79,7 @@ def __init__(
7979
max_snapshots: int = 3,
8080
checkpoint_slots: int | None = None,
8181
checkpoint_budget_bytes: int | None = 16 * 1024**3,
82+
spill_bytes: int = 0,
8283
memory_budget_bytes: int | None = None,
8384
memory_runtime: Any = None,
8485
model_aliases: list[str] | None = None,
@@ -168,6 +169,12 @@ def __init__(
168169
model_id=model_id,
169170
prompt_memory=self.prompt_memory,
170171
)
172+
# evicted conversations go to disk (``spill_bytes`` of this model's files at most) and come back on demand
173+
self.spill_bytes = int(spill_bytes) if self.checkpoints is not None and self.scheduler.session_dir else 0
174+
if self.spill_bytes > 0:
175+
session_dir, spill_limit = Path(self.scheduler.session_dir), self.spill_bytes
176+
self.checkpoints.on_evict = lambda entry: spill_conversation(entry, session_dir, model_id,
177+
limit_bytes=spill_limit)
171178
loaded_count = 0
172179
if snapshot_dir is not None and self.checkpoints is not None:
173180
from tensorfold.engine.prefix_snapshots import load_snapshots
@@ -576,4 +583,8 @@ def save_sessions(self) -> int:
576583

577584
if self.scheduler.session_dir is None or self.checkpoints is None:
578585
return 0
586+
if self.spill_bytes > 0:
587+
# the session directory is a disk tier under its own byte budget, not the newest two conversations
588+
return save_conversations(self.checkpoints, Path(self.scheduler.session_dir), self.scheduler.model_id,
589+
keep=1 << 30, limit_bytes=self.spill_bytes)
579590
return save_conversations(self.checkpoints, Path(self.scheduler.session_dir), self.scheduler.model_id)

‎src/tensorfold/server/checkpoints.py‎

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,45 @@ def save_conversations(store: "CheckpointStore", directory: Path, model_id: str,
6767
return saved
6868

6969

70+
def spill_conversation(entry: CheckpointEntry, directory: Path, model_id: str, *, limit_bytes: int) -> bool:
71+
"""Write an evicted conversation where ``_read_disk_block`` finds saved conversations, keeping this model's files
72+
in ``directory`` under ``limit_bytes`` (oldest first); False when it was not written.
73+
74+
An evicted conversation otherwise costs a full prefill on its next turn (GDN state cannot be truncated to a shorter
75+
stored prefix). Measured on an M5 Ultra with Qwen3.8-27B: a 30,720-token entry (2.0 GiB) wrote in 0.17 s and read
76+
back in 0.05 s, against 20 s to prefill it again.
77+
"""
78+
79+
from tensorfold.engine.prefix_snapshots import read_metadata, save_snapshot
80+
81+
if entry.nbytes > limit_bytes:
82+
return False
83+
started = time.perf_counter()
84+
try:
85+
save_snapshot(directory, model_id, entry.tokens, entry.cache, keep=1 << 30) # pruned by bytes below
86+
except Exception as exc: # noqa: BLE001 - a full disk costs a later prefill, never the request
87+
print(f"[tensorfold] conversation spill failed: {type(exc).__name__}: {exc}", flush=True)
88+
return False
89+
ours = []
90+
for path in sorted(directory.glob("*.safetensors"), key=lambda p: p.stat().st_mtime, reverse=True):
91+
if path.name.endswith(".partial.safetensors"):
92+
continue
93+
try:
94+
same = str(read_metadata(path).get("model", "")).split("|")[0] == model_id.split("|")[0]
95+
except Exception: # noqa: BLE001 - an unreadable file is left alone
96+
continue
97+
if same:
98+
ours.append(path)
99+
total = 0
100+
for path in ours:
101+
total += path.stat().st_size
102+
if total > limit_bytes:
103+
path.unlink(missing_ok=True)
104+
print(f"[tensorfold] spilled conversation tokens={len(entry.tokens)} ({entry.nbytes / 1024**3:.1f} GiB) "
105+
f"in {time.perf_counter() - started:.2f}s", flush=True)
106+
return True
107+
108+
70109
class CheckpointStore:
71110
"""LRU caches require strict-prefix hits because GDN state cannot truncate; pinned system blocks bypass slot limits and outlast conversations."""
72111

@@ -78,6 +117,7 @@ def __init__(
78117
budget_bytes: int | None = None,
79118
sizer: Callable[[list[Any]], int] | None = None,
80119
pinned_slots: int = 3,
120+
on_evict: Callable[[CheckpointEntry], Any] | None = None,
81121
) -> None:
82122
if slots < 1:
83123
raise ValueError("slots must be positive")
@@ -95,6 +135,26 @@ def __init__(
95135
self.evictions = 0
96136
# set when a memory controller evicts on demand: the newest entry may then exceed the byte budget
97137
self.admit_oversize = False
138+
# called, outside the lock and on the thread that inserts or evicts (the scheduler's, which owns the arrays),
139+
# with each evicted conversation that no remaining entry extends (``spill_conversation``)
140+
self.on_evict = on_evict
141+
self.spilled = 0
142+
143+
def _evicted(self, gone: list[CheckpointEntry]) -> None:
144+
if self.on_evict is None:
145+
return
146+
with self._lock:
147+
remaining = [entry.tokens for entry in self._entries]
148+
for entry in gone:
149+
# an older checkpoint of a conversation that moved on: it continues from the newer entry, so skip the write
150+
n = len(entry.tokens)
151+
if entry.pinned or any(len(t) > n and t[:n] == entry.tokens for t in remaining):
152+
continue
153+
try:
154+
if self.on_evict(entry) is not False:
155+
self.spilled += 1
156+
except Exception as exc: # noqa: BLE001 - a failed spill costs a later prefill, never the request
157+
print(f"[tensorfold] eviction hook failed: {type(exc).__name__}: {exc}", flush=True)
98158

99159
@property
100160
def nbytes(self) -> int:
@@ -163,6 +223,7 @@ def insert(self, tokens: list[int], cache: list[Any], *, last_prompt: list[int],
163223
if oversize:
164224
limit = nbytes + sum(e.nbytes for e in entries[1:] if e.pinned)
165225
# Never evict the new entry; evict least recently used conversations before system blocks.
226+
gone: list[CheckpointEntry] = []
166227
while True:
167228
over_slots = sum(1 for e in entries if not e.pinned) > self.slots
168229
over_budget = (limit is not None and len(entries) > 1
@@ -171,13 +232,14 @@ def insert(self, tokens: list[int], cache: list[Any], *, last_prompt: list[int],
171232
break
172233
unpinned = [i for i in range(1, len(entries)) if not entries[i].pinned]
173234
if unpinned:
174-
entries.pop(unpinned[-1])
235+
gone.append(entries.pop(unpinned[-1]))
175236
elif over_budget:
176237
entries.pop()
177238
else:
178239
break
179240
self.evictions += 1
180241
self._entries = entries
242+
self._evicted(gone)
181243

182244
def __len__(self) -> int:
183245
return len(self._entries)
@@ -190,6 +252,7 @@ def evict_one(self, keep: CheckpointEntry | None = None) -> bool:
190252
if not candidates:
191253
return False
192254
ordinary = [i for i in candidates if not self._entries[i].pinned]
193-
self._entries.pop(ordinary[-1] if ordinary else candidates[-1])
255+
gone = self._entries.pop(ordinary[-1] if ordinary else candidates[-1])
194256
self.evictions += 1
195-
return True
257+
self._evicted([gone])
258+
return True

‎tests/test_checkpoint_spill.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
"""Evicted conversations go to disk and come back instead of a full prefill; older checkpoints of a live one do not."""
2+
3+
from __future__ import annotations
4+
5+
import pytest
6+
7+
from tensorfold.server.checkpoints import CheckpointStore
8+
9+
10+
def _store(slots=2, budget=None, spilled=None):
11+
return CheckpointStore(slots, copier=lambda c: c, budget_bytes=budget, sizer=lambda c: c[0],
12+
on_evict=(lambda entry: spilled.append(list(entry.tokens))) if spilled is not None else None)
13+
14+
15+
def test_an_evicted_conversation_is_handed_to_the_hook():
16+
spilled = []
17+
store = _store(slots=2, spilled=spilled)
18+
store.insert([1, 2], [10], last_prompt=[1, 2])
19+
store.insert([5, 6], [10], last_prompt=[5, 6])
20+
store.insert([8, 9], [10], last_prompt=[8, 9])
21+
assert spilled == [[1, 2]] and store.spilled == 1
22+
23+
24+
def test_an_older_checkpoint_of_a_conversation_that_moved_on_is_not_spilled():
25+
spilled = []
26+
store = _store(slots=2, spilled=spilled)
27+
store.insert([1, 2], [10], last_prompt=[1, 2])
28+
store.insert([1, 2, 3, 4], [10], last_prompt=[1, 2, 3, 4]) # the same conversation, one turn on
29+
store.insert([7, 8], [10], last_prompt=[7, 8]) # evicts [1, 2], which [1, 2, 3, 4] extends
30+
assert spilled == []
31+
32+
33+
def test_budget_evictions_are_spilled_too():
34+
spilled = []
35+
store = _store(slots=8, budget=25, spilled=spilled)
36+
store.insert([1], [10], last_prompt=[1])
37+
store.insert([2], [10], last_prompt=[2])
38+
store.insert([3], [10], last_prompt=[3])
39+
assert spilled == [[1]]
40+
41+
42+
def test_memory_pressure_evictions_are_spilled():
43+
spilled = []
44+
store = _store(slots=4, spilled=spilled)
45+
store.insert([1], [10], last_prompt=[1])
46+
store.insert([2], [10], last_prompt=[2])
47+
assert store.evict_one() and spilled == [[1]]
48+
49+
50+
def test_system_blocks_are_never_spilled():
51+
spilled = []
52+
store = _store(slots=4, spilled=spilled)
53+
store.insert([1, 2, 3], [10], last_prompt=[1, 2, 3], pinned=True)
54+
assert store.evict_one() and spilled == []
55+
56+
57+
def test_a_failing_hook_never_fails_the_insert():
58+
def boom(entry):
59+
raise OSError("disk full")
60+
61+
store = CheckpointStore(1, copier=lambda c: c, sizer=lambda c: c[0], on_evict=boom)
62+
store.insert([1], [10], last_prompt=[1])
63+
store.insert([2], [10], last_prompt=[2])
64+
assert len(store) == 1 and store.spilled == 0
65+
66+
67+
class Layer:
68+
def __init__(self, n: int) -> None:
69+
import mlx.core as mx
70+
71+
self.keys = mx.ones((1, 2, n, 4))
72+
self.offset = n
73+
74+
75+
def test_a_spilled_conversation_is_found_and_read_back(tmp_path):
76+
mx = pytest.importorskip("mlx.core")
77+
from tensorfold.engine.prefix_snapshots import DiskBlocks, load_snapshot
78+
from tensorfold.server.checkpoints import spill_conversation
79+
80+
model = "/models/qwen|mlx=1"
81+
store = CheckpointStore(1, copier=lambda c: c, sizer=lambda c: sum(int(x.keys.nbytes) for x in c),
82+
on_evict=lambda e: spill_conversation(e, tmp_path, model, limit_bytes=1 << 30))
83+
store.insert([1, 2, 3], [Layer(3)], last_prompt=[1, 2, 3])
84+
store.insert([9, 9], [Layer(2)], last_prompt=[9, 9]) # evicts and writes [1, 2, 3]
85+
hit = DiskBlocks(tmp_path, model).best([1, 2, 3, 4], 0)
86+
assert hit is not None and hit[1] == [1, 2, 3]
87+
tokens, cache = load_snapshot(hit[0], model)
88+
assert tokens == [1, 2, 3] and cache[0].offset == 3 and bool(mx.array_equal(cache[0].keys, Layer(3).keys).item())
89+
90+
91+
def test_the_spill_directory_keeps_the_newest_within_its_byte_limit(tmp_path):
92+
import os
93+
94+
pytest.importorskip("mlx.core")
95+
96+
from tensorfold.server.checkpoints import CheckpointEntry, spill_conversation
97+
98+
model = "/models/qwen|mlx=1"
99+
for i in range(3):
100+
spill_conversation(CheckpointEntry([i, 1], [Layer(64)], [i, 1], nbytes=10), tmp_path, model, limit_bytes=1 << 30)
101+
files = sorted(tmp_path.glob("*.safetensors"), key=lambda p: p.stat().st_mtime)
102+
for n, path in enumerate(files): # distinct mtimes, oldest first
103+
os.utime(path, (1_000_000 + n, 1_000_000 + n))
104+
one = files[0].stat().st_size
105+
spill_conversation(CheckpointEntry([7, 1], [Layer(64)], [7, 1], nbytes=10), tmp_path, model,
106+
limit_bytes=int(2.5 * one))
107+
assert len(list(tmp_path.glob("*.safetensors"))) == 2
108+
assert not files[0].exists() and not files[1].exists()

0 commit comments

Comments
 (0)