siddhm11 Claude Opus 5.5 commited on
Commit
d97a774
·
1 Parent(s): fddee41

perf(search): keep the search models in RAM while nobody searches

Browse files

Measured on the Space 2026-11-02: after a quiet spell the process held
0.45 GB (peak 3.1 GB), so the model weights had left RAM. The next search
took 9.9 s on the server (cross-encoder 4.8 s) while they were read back;
the searches after it took 1.4-2.1 s. Nothing in the app unloads a model.

app/keep_warm.py (switch MODEL_KEEP_WARM, off by default) runs one uncached
encode and one reranked pair through the inference pool after
MODEL_KEEP_WARM_INTERVAL_S (120) seconds without model work, so a reader's
search never queues behind it. About 50 ms per pass on the laptop.

Each pass records its time and major page faults (keep_warm_cold when the
weights had left RAM anyway), and /healthz/runtime memory now reports
anonymous, file-backed and swapped memory plus the process's major faults,
to show which way the weights left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

.env.example CHANGED
@@ -43,6 +43,9 @@ SEARCH_BGE_RERANK=1
43
  # GIL_SWITCH_INTERVAL_MS=0.5
44
  # Put the paper a short search names first (app/named_paper.py): off | shadow | on.
45
  # SEARCH_NAMED_PAPER=shadow
 
 
 
46
  SEARCH_RERANK_TOP_N=10
47
 
48
  # Optional companion map; configure a dedicated map store for isolation.
 
43
  # GIL_SWITCH_INTERVAL_MS=0.5
44
  # Put the paper a short search names first (app/named_paper.py): off | shadow | on.
45
  # SEARCH_NAMED_PAPER=shadow
46
+ # Keep the search models in RAM while nobody searches (app/keep_warm.py): off | on.
47
+ # MODEL_KEEP_WARM=on
48
+ # MODEL_KEEP_WARM_INTERVAL_S=120
49
  SEARCH_RERANK_TOP_N=10
50
 
51
  # Optional companion map; configure a dedicated map store for isolation.
app/compute_pool.py CHANGED
@@ -22,6 +22,7 @@ Two pools now:
22
 
23
  `pending()` reports queued + running inference jobs; search uses it to rerank
24
  deeper when nobody else is waiting (see config.SEARCH_RERANK_TOP_N_IDLE).
 
25
  """
26
  from __future__ import annotations
27
 
@@ -31,6 +32,7 @@ import math
31
  import os
32
  import sys
33
  import threading
 
34
  from concurrent.futures import ThreadPoolExecutor
35
 
36
  from app import config
@@ -81,6 +83,7 @@ _io = ThreadPoolExecutor(max_workers=config.IO_POOL_WORKERS, thread_name_prefix=
81
 
82
  _pending = 0
83
  _pending_lock = threading.Lock()
 
84
  _torch_configured = False
85
 
86
 
@@ -114,9 +117,14 @@ def pending() -> int:
114
  return _pending
115
 
116
 
 
 
 
 
 
117
  async def run_inference(fn, *args):
118
  """Run a model forward pass on the inference pool."""
119
- global _pending
120
  with _pending_lock:
121
  _pending += 1
122
  try:
@@ -125,6 +133,7 @@ async def run_inference(fn, *args):
125
  finally:
126
  with _pending_lock:
127
  _pending -= 1
 
128
 
129
 
130
  async def run_io(fn, *args):
 
22
 
23
  `pending()` reports queued + running inference jobs; search uses it to rerank
24
  deeper when nobody else is waiting (see config.SEARCH_RERANK_TOP_N_IDLE).
25
+ `idle_s()` is how long the models have gone unused; app/keep_warm.py uses it.
26
  """
27
  from __future__ import annotations
28
 
 
32
  import os
33
  import sys
34
  import threading
35
+ import time
36
  from concurrent.futures import ThreadPoolExecutor
37
 
38
  from app import config
 
83
 
84
  _pending = 0
85
  _pending_lock = threading.Lock()
86
+ _last_done = time.monotonic()
87
  _torch_configured = False
88
 
89
 
 
117
  return _pending
118
 
119
 
120
+ def idle_s() -> float:
121
+ """Seconds since the last inference job finished; 0 while one is queued or running."""
122
+ return 0.0 if _pending else time.monotonic() - _last_done
123
+
124
+
125
  async def run_inference(fn, *args):
126
  """Run a model forward pass on the inference pool."""
127
+ global _pending, _last_done
128
  with _pending_lock:
129
  _pending += 1
130
  try:
 
133
  finally:
134
  with _pending_lock:
135
  _pending -= 1
136
+ _last_done = time.monotonic()
137
 
138
 
139
  async def run_io(fn, *args):
app/keep_warm.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Keep the search models in memory while nobody is searching (switch MODEL_KEEP_WARM).
3
+
4
+ Measured on the Space 2026-11-02: after a quiet spell the process held 0.45 GB
5
+ (peak 3.1 GB), so the model weights were no longer in RAM. The next search took
6
+ 9.9 s on the server (cross-encoder 4.8 s) while they were read back, and the
7
+ process returned to 1.85 GB; the searches after it took 1.4-2.1 s. Of the 20
8
+ searches before that, the slowest took 9.1 s. Nothing here unloads a model:
9
+ the system reclaimed the memory.
10
+
11
+ A forward pass reads every weight of every layer (the word-embedding table only
12
+ row by row, which costs a search just a few pages), so one uncached encode and
13
+ one reranked pair keep both models in recent use. A pass runs through the
14
+ inference pool like a search, and only after INTERVAL_S without any model work:
15
+ a reader's search is never queued behind one, and a busy Space runs none.
16
+
17
+ Each pass records its time and the major page faults it caused. A warm pass
18
+ takes well under a second with almost no faults; a slow pass with many faults
19
+ means the weights left RAM within the interval anyway, and /healthz/runtime
20
+ counts those as keep_warm_cold.
21
+
22
+ Modes: off; on.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import os
28
+ import resource
29
+ import time
30
+
31
+ from app import compute_pool, embed_svc, errors, features, reranker_bge_svc, runtime_stats
32
+
33
+ SWITCH = "MODEL_KEEP_WARM"
34
+ INTERVAL_S = int(os.getenv("MODEL_KEEP_WARM_INTERVAL_S", "120"))
35
+ COLD_FAULTS = 256 # pages read back from disk or swap (1 MB) before a pass counts as cold
36
+ TEXT = "keeping the search models in memory"
37
+ DOC = "Title: Keeping models in memory\nAbstract: A short passage, scored so the reranker's weights stay in RAM."
38
+
39
+ _state: dict = {"scheduler": "off", "passes": 0, "cold": 0, "last_at": None,
40
+ "last_encode_ms": None, "last_rerank_ms": None, "last_major_faults": None}
41
+ _task: asyncio.Task | None = None
42
+
43
+
44
+ def _faults() -> int:
45
+ """Major page faults of the calling thread (Linux), else of the whole process."""
46
+ return resource.getrusage(getattr(resource, "RUSAGE_THREAD", resource.RUSAGE_SELF)).ru_majflt
47
+
48
+
49
+ def _pass() -> dict:
50
+ """One encode and one reranked pair, on the inference thread, for whichever
51
+ model is loaded (never loads one)."""
52
+ f0, t0 = _faults(), time.perf_counter()
53
+ if embed_svc._model is not None:
54
+ # Around the LRU cache: an answer from the cache would read no weights.
55
+ embed_svc._encode_cached.__wrapped__(TEXT)
56
+ t1 = time.perf_counter()
57
+ if reranker_bge_svc._reranker is not None:
58
+ reranker_bge_svc._score_in_length_groups(reranker_bge_svc._reranker, [[TEXT, DOC]])
59
+ t2 = time.perf_counter()
60
+ return {"encode_ms": round((t1 - t0) * 1000), "rerank_ms": round((t2 - t1) * 1000),
61
+ "major_faults": _faults() - f0}
62
+
63
+
64
+ def due() -> bool:
65
+ """Whether to run a pass now: switch on and no model work for INTERVAL_S."""
66
+ return features.mode(SWITCH) == "on" and compute_pool.idle_s() >= INTERVAL_S
67
+
68
+
69
+ async def run_once() -> dict | None:
70
+ """Run one pass and record it. None when neither model is loaded."""
71
+ if embed_svc._model is None and reranker_bge_svc._reranker is None:
72
+ return None
73
+ out = await compute_pool.run_inference(_pass)
74
+ runtime_stats.record("keep_warm", out)
75
+ runtime_stats.count("keep_warm_pass")
76
+ _state["passes"] += 1
77
+ if out["major_faults"] >= COLD_FAULTS:
78
+ runtime_stats.count("keep_warm_cold")
79
+ _state["cold"] += 1
80
+ _state.update(last_at=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
81
+ last_encode_ms=out["encode_ms"], last_rerank_ms=out["rerank_ms"],
82
+ last_major_faults=out["major_faults"])
83
+ return out
84
+
85
+
86
+ async def _loop() -> None:
87
+ # Checking every half interval keeps the longest gap without model work
88
+ # under 1.5 x INTERVAL_S.
89
+ while True:
90
+ _state["scheduler"] = "running"
91
+ await asyncio.sleep(INTERVAL_S / 2)
92
+ if not due():
93
+ continue
94
+ try:
95
+ await run_once()
96
+ except Exception as e: # a failed pass never stops the loop
97
+ errors.report("keep_warm", "a keep-warm pass failed", e)
98
+
99
+
100
+ async def start() -> None:
101
+ global _task
102
+ if features.mode(SWITCH) != "on" or _task is not None:
103
+ return
104
+ _task = asyncio.create_task(_loop(), name="keep-warm")
105
+
106
+
107
+ async def stop() -> None:
108
+ global _task
109
+ if _task is not None:
110
+ _task.cancel()
111
+ try:
112
+ await _task
113
+ except (asyncio.CancelledError, Exception):
114
+ pass
115
+ _task = None
116
+ _state["scheduler"] = "off"
117
+
118
+
119
+ def status() -> dict:
120
+ return {"switch": features.mode(SWITCH), "interval_s": INTERVAL_S,
121
+ "idle_s": round(compute_pool.idle_s()), **_state}
app/main.py CHANGED
@@ -93,7 +93,8 @@ async def lifespan(app: FastAPI):
93
  from app.discovery_runtime import DiscoveryRuntime
94
  app.state.discovery = DiscoveryRuntime()
95
  await app.state.discovery.start()
96
- from app import ai_usage, analytics, figure_prewarm, trending_shelf, trending_topics
 
97
  await figure_prewarm.start()
98
  await trending_shelf.start()
99
  await trending_topics.start()
@@ -103,7 +104,8 @@ async def lifespan(app: FastAPI):
103
  yield
104
  finally:
105
  await app.state.discovery.stop()
106
- from app import abstract_svc, figure_prewarm, paper_source_svc, trending_shelf, trending_topics
 
107
  await figure_prewarm.stop()
108
  await trending_shelf.stop()
109
  await trending_topics.stop()
 
93
  from app.discovery_runtime import DiscoveryRuntime
94
  app.state.discovery = DiscoveryRuntime()
95
  await app.state.discovery.start()
96
+ from app import ai_usage, analytics, figure_prewarm, keep_warm, trending_shelf, trending_topics
97
+ await keep_warm.start()
98
  await figure_prewarm.start()
99
  await trending_shelf.start()
100
  await trending_topics.start()
 
104
  yield
105
  finally:
106
  await app.state.discovery.stop()
107
+ from app import abstract_svc, figure_prewarm, keep_warm, paper_source_svc, trending_shelf, trending_topics
108
+ await keep_warm.stop()
109
  await figure_prewarm.stop()
110
  await trending_shelf.stop()
111
  await trending_topics.stop()
app/runtime_stats.py CHANGED
@@ -68,6 +68,14 @@ def _read(path: str) -> str | None:
68
  return None
69
 
70
 
 
 
 
 
 
 
 
 
71
  def memory() -> dict:
72
  """Resident and peak memory of this process, and the container's limit."""
73
  out: dict = {}
@@ -75,13 +83,14 @@ def memory() -> dict:
75
  if status:
76
  for line in status.splitlines():
77
  key, _, val = line.partition(":")
78
- if key in ("VmRSS", "VmHWM"):
79
- out[{"VmRSS": "rss_gb", "VmHWM": "peak_rss_gb"}[key]] = round(
80
- int(val.split()[0]) / 1e6, 3)
81
  else:
82
  # macOS reports bytes, Linux kilobytes; only the peak is available here.
83
  peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
84
  out["peak_rss_gb"] = round(peak / (1e9 if sys.platform == "darwin" else 1e6), 3)
 
 
85
  # cgroup v2, then v1. memory.current includes reclaimable page cache (the
86
  # metadata sidecar, any memory-mapped vectors), so it overstates pressure.
87
  for cur, lim in (("/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.max"),
@@ -92,11 +101,14 @@ def memory() -> dict:
92
  out["container_used_gb"] = round(int(c) / 1e9, 3)
93
  out["container_limit_gb"] = None if l_ in (None, "max") else round(int(l_) / 1e9, 3)
94
  break
 
 
 
95
  return out
96
 
97
 
98
  def models() -> dict:
99
- from app import config, embed_svc, model_trace, reranker_bge_svc
100
  try:
101
  import torch
102
  torch_threads = torch.get_num_threads()
@@ -112,4 +124,5 @@ def models() -> dict:
112
  "idle": config.SEARCH_RERANK_TOP_N_IDLE},
113
  "torch_threads": torch_threads,
114
  "traced": model_trace.status(),
 
115
  }
 
68
  return None
69
 
70
 
71
+ # /proc/self/status fields, in kB. RSS splits into anonymous memory (the
72
+ # Python heap, torch tensors) and file pages (anything read through mmap); swap
73
+ # is anonymous memory the system moved out of RAM. Together they say where model
74
+ # weights went when RSS fell from 3.1 GB to 0.45 GB on a quiet Space (2026-11-02).
75
+ _STATUS = {"VmRSS": "rss_gb", "VmHWM": "peak_rss_gb", "RssAnon": "anon_gb",
76
+ "RssFile": "file_gb", "VmSwap": "swap_gb"}
77
+
78
+
79
  def memory() -> dict:
80
  """Resident and peak memory of this process, and the container's limit."""
81
  out: dict = {}
 
83
  if status:
84
  for line in status.splitlines():
85
  key, _, val = line.partition(":")
86
+ if key in _STATUS:
87
+ out[_STATUS[key]] = round(int(val.split()[0]) / 1e6, 3)
 
88
  else:
89
  # macOS reports bytes, Linux kilobytes; only the peak is available here.
90
  peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
91
  out["peak_rss_gb"] = round(peak / (1e9 if sys.platform == "darwin" else 1e6), 3)
92
+ # Pages read back from disk or swap since the process started.
93
+ out["major_faults"] = resource.getrusage(resource.RUSAGE_SELF).ru_majflt
94
  # cgroup v2, then v1. memory.current includes reclaimable page cache (the
95
  # metadata sidecar, any memory-mapped vectors), so it overstates pressure.
96
  for cur, lim in (("/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.max"),
 
101
  out["container_used_gb"] = round(int(c) / 1e9, 3)
102
  out["container_limit_gb"] = None if l_ in (None, "max") else round(int(l_) / 1e9, 3)
103
  break
104
+ swap = _read("/sys/fs/cgroup/memory.swap.current")
105
+ if swap is not None:
106
+ out["container_swap_gb"] = round(int(swap) / 1e9, 3)
107
  return out
108
 
109
 
110
  def models() -> dict:
111
+ from app import config, embed_svc, keep_warm, model_trace, reranker_bge_svc
112
  try:
113
  import torch
114
  torch_threads = torch.get_num_threads()
 
124
  "idle": config.SEARCH_RERANK_TOP_N_IDLE},
125
  "torch_threads": torch_threads,
126
  "traced": model_trace.status(),
127
+ "keep_warm": keep_warm.status(),
128
  }
tests/test_keep_warm.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """app/keep_warm.py: a pass reads the model weights (never a cached answer), runs
2
+ only after the models have been idle, and records the faults that show whether
3
+ the weights had left RAM."""
4
+ import asyncio
5
+ import time
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from app import compute_pool, embed_svc, keep_warm, reranker_bge_svc, runtime_stats
11
+
12
+
13
+ class _Encoder:
14
+ def __init__(self):
15
+ self.calls = 0
16
+
17
+ def encode(self, texts, **kwargs):
18
+ self.calls += 1
19
+ return {"dense_vecs": [np.zeros(1024, dtype=np.float32)], "lexical_weights": [{7: 0.5}]}
20
+
21
+
22
+ class _CrossEncoder:
23
+ def __init__(self):
24
+ self.calls = 0
25
+
26
+ def predict(self, pairs, **kwargs):
27
+ self.calls += 1
28
+ return [0.0] * len(pairs)
29
+
30
+
31
+ @pytest.fixture
32
+ def models(monkeypatch):
33
+ enc, ce = _Encoder(), _CrossEncoder()
34
+ monkeypatch.setattr(embed_svc, "_model", enc)
35
+ monkeypatch.setattr(embed_svc, "get_model", lambda: enc)
36
+ monkeypatch.setattr(reranker_bge_svc, "_reranker", ce)
37
+ embed_svc._encode_cached.cache_clear()
38
+ yield enc, ce
39
+ embed_svc._encode_cached.cache_clear()
40
+
41
+
42
+ def test_a_pass_reads_the_weights_even_when_the_text_is_cached(models):
43
+ enc, ce = models
44
+ embed_svc.encode_query(keep_warm.TEXT)
45
+ embed_svc.encode_query(keep_warm.TEXT)
46
+ assert enc.calls == 1 # a search for the same text is cached
47
+ keep_warm._pass()
48
+ keep_warm._pass()
49
+ assert (enc.calls, ce.calls) == (3, 2)
50
+
51
+
52
+ def test_a_pass_never_loads_a_model(monkeypatch):
53
+ monkeypatch.setattr(embed_svc, "_model", None)
54
+ monkeypatch.setattr(embed_svc, "get_model", lambda: pytest.fail("loaded the encoder"))
55
+ monkeypatch.setattr(reranker_bge_svc, "_reranker", None)
56
+ assert keep_warm._pass()["major_faults"] >= 0
57
+
58
+
59
+ async def test_idle_time_restarts_after_any_model_work(monkeypatch):
60
+ monkeypatch.setattr(compute_pool, "_last_done", time.monotonic() - 500)
61
+ assert compute_pool.idle_s() >= 500
62
+ await compute_pool.run_inference(lambda: None)
63
+ assert compute_pool.idle_s() < 5
64
+ monkeypatch.setattr(compute_pool, "_pending", 1)
65
+ assert compute_pool.idle_s() == 0
66
+
67
+
68
+ @pytest.mark.parametrize("mode, idle, expected", [
69
+ ("on", keep_warm.INTERVAL_S, True), ("on", keep_warm.INTERVAL_S - 1, False), ("off", 10**6, False),
70
+ ])
71
+ def test_due(monkeypatch, mode, idle, expected):
72
+ monkeypatch.setenv(keep_warm.SWITCH, mode)
73
+ monkeypatch.setattr(compute_pool, "idle_s", lambda: idle)
74
+ assert keep_warm.due() is expected
75
+
76
+
77
+ async def test_a_pass_with_many_faults_counts_as_cold(models, monkeypatch):
78
+ before = runtime_stats.counters().get("keep_warm_cold", 0)
79
+ monkeypatch.setattr(keep_warm, "_pass", lambda: {"encode_ms": 4100, "rerank_ms": 2300, "major_faults": 9000})
80
+ out = await keep_warm.run_once()
81
+ assert out["major_faults"] == 9000
82
+ assert runtime_stats.counters()["keep_warm_cold"] == before + 1
83
+ assert keep_warm.status()["last_major_faults"] == 9000
84
+ assert runtime_stats.timings()["keep_warm"]["encode_ms"]["max"] >= 4100
85
+
86
+
87
+ async def test_nothing_runs_without_models(monkeypatch):
88
+ monkeypatch.setattr(embed_svc, "_model", None)
89
+ monkeypatch.setattr(reranker_bge_svc, "_reranker", None)
90
+ assert await keep_warm.run_once() is None
91
+
92
+
93
+ async def test_the_loop_starts_only_when_switched_on(monkeypatch):
94
+ monkeypatch.setenv(keep_warm.SWITCH, "off")
95
+ await keep_warm.start()
96
+ assert keep_warm._task is None
97
+ monkeypatch.setenv(keep_warm.SWITCH, "on")
98
+ await keep_warm.start()
99
+ try:
100
+ await asyncio.sleep(0)
101
+ assert keep_warm.status()["scheduler"] == "running"
102
+ finally:
103
+ await keep_warm.stop()
104
+ assert keep_warm._task is None and keep_warm.status()["scheduler"] == "off"
105
+
106
+
107
+ def test_memory_says_where_the_weights_went(monkeypatch):
108
+ files = {
109
+ "/proc/self/status": "VmHWM:\t3128000 kB\nVmRSS:\t 450000 kB\nRssAnon:\t 300000 kB\n"
110
+ "RssFile:\t 150000 kB\nVmSwap:\t2600000 kB\n",
111
+ "/sys/fs/cgroup/memory.current": "538000000",
112
+ "/sys/fs/cgroup/memory.max": "16000000000",
113
+ "/sys/fs/cgroup/memory.swap.current": "2700000000",
114
+ }
115
+ monkeypatch.setattr(runtime_stats, "_read", files.get)
116
+ m = runtime_stats.memory()
117
+ assert (m["rss_gb"], m["anon_gb"], m["file_gb"], m["swap_gb"]) == (0.45, 0.3, 0.15, 2.6)
118
+ assert m["container_swap_gb"] == 2.7 and m["major_faults"] >= 0