@simplexai/localmodels-linux-arm64 0.1.0-dev.100 → 0.1.0-dev.101
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +21 -19
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/auth_proxy.py +337 -14
- package/modules/localmodels/catalog.json +16 -10
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +94 -0
- package/modules/localmodels/guard-requirements.in +3 -0
- package/modules/localmodels/guard-requirements.lock +4 -4
- package/modules/localmodels/guard.py +2 -2
- package/modules/localmodels/program_scheduler.py +1198 -0
- package/modules/localmodels/slot_cache.py +71 -5
- package/modules/localmodels/speech_jobs.py +2 -0
- package/modules/localmodels/speech_workers.py +62 -10
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.6.txt → strata-poly-serve-0.2.20-poly.7.txt} +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/RECORD +18 -16
- package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/licenses/NOTICE +1 -1
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +0 -94
- /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev101.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,1198 @@
|
|
|
1
|
+
"""Hybrid-memory program-aware admission scheduler for concurrent multi-turn agents.
|
|
2
|
+
|
|
3
|
+
Clean-room Python 3.8+ standard-library implementation inspired by the MIT-licensed
|
|
4
|
+
ThunderAgent program scheduler and hybrid page accounting design (Copyright 2026
|
|
5
|
+
Hao Kang, MIT License). Keeps concurrent agent working sets inside an inference
|
|
6
|
+
engine's unified KV + recurrent/SWA state pool while bounding tail wait latency.
|
|
7
|
+
|
|
8
|
+
Opt-in only: ``auth_proxy.py`` and ``slot_cache.py`` preserve unchanged pass-through
|
|
9
|
+
behavior unless explicitly enabled via CLI flags or ``LOCALMODELS_PROGRAM_AWARE=1``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import os
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from collections import OrderedDict
|
|
20
|
+
from collections.abc import Callable, Sequence
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from enum import Enum
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
MIB = 1 << 20
|
|
27
|
+
DEFAULT_PAGE_BYTES = 16 * MIB
|
|
28
|
+
OBSERVER_LIMIT_BYTES = 4 * MIB
|
|
29
|
+
_RECURRENT_FALLBACK_PER_LAYER = 4 * MIB
|
|
30
|
+
_SWA_KV_PAD = 256
|
|
31
|
+
_KV_DTYPE_BPE = {"f16": 2.0, "q8_0": 34.0 / 32.0, "q4_0": 18.0 / 32.0}
|
|
32
|
+
_TRUTHY_ENV = frozenset({"1", "true", "yes", "on"})
|
|
33
|
+
|
|
34
|
+
PROGRAM_AWARE_ENV = "LOCALMODELS_PROGRAM_AWARE"
|
|
35
|
+
PROGRAM_MODEL_ENV = "LOCALMODELS_PROGRAM_MODEL"
|
|
36
|
+
PROGRAM_WINDOW_ENV = "LOCALMODELS_PROGRAM_WINDOW"
|
|
37
|
+
PROGRAM_SLOTS_ENV = "LOCALMODELS_PROGRAM_SLOTS"
|
|
38
|
+
PROGRAM_KV_K_ENV = "LOCALMODELS_PROGRAM_KV_K"
|
|
39
|
+
PROGRAM_KV_V_ENV = "LOCALMODELS_PROGRAM_KV_V"
|
|
40
|
+
PROGRAM_CACHE_MIB_ENV = "LOCALMODELS_PROGRAM_CACHE_MIB"
|
|
41
|
+
PROGRAM_MAX_RESIDENT_ENV = "LOCALMODELS_PROGRAM_MAX_RESIDENT"
|
|
42
|
+
|
|
43
|
+
_COUNTER_NAMES = (
|
|
44
|
+
"admitted_immediately",
|
|
45
|
+
"paused_on_admission",
|
|
46
|
+
"paused_resident_cap",
|
|
47
|
+
"paused_service_lag",
|
|
48
|
+
"paused_aged_reservation",
|
|
49
|
+
"paused_acting_eviction",
|
|
50
|
+
"marked_reasoning",
|
|
51
|
+
"resumed_normal",
|
|
52
|
+
"resumed_aged",
|
|
53
|
+
"resumed_aged_owner",
|
|
54
|
+
"resumed_acting",
|
|
55
|
+
"cancelled_waiters",
|
|
56
|
+
"capacity_timeouts",
|
|
57
|
+
"released",
|
|
58
|
+
"release_deferred",
|
|
59
|
+
"ticks",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ProgramStatus(str, Enum):
|
|
64
|
+
REASONING = "reasoning"
|
|
65
|
+
ACTING = "acting"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ProgramLifecycle(str, Enum):
|
|
69
|
+
ACTIVE = "active"
|
|
70
|
+
PAUSED = "paused"
|
|
71
|
+
TERMINATED = "terminated"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ProgramReleasedError(RuntimeError):
|
|
75
|
+
"""A lifecycle release raced a request that was waiting for admission."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ProgramAdmissionTimeoutError(RuntimeError):
|
|
79
|
+
"""A waiting request timed out while capacity stayed unavailable."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ProgramCancelledError(RuntimeError):
|
|
83
|
+
"""The waiting client disconnected before admission completed."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class PageBreakdown:
|
|
88
|
+
"""Self-consistent snapshot of active hybrid-page reservations."""
|
|
89
|
+
|
|
90
|
+
total_pages: int
|
|
91
|
+
attention_pages: int
|
|
92
|
+
resident_state_pages: int
|
|
93
|
+
transient_state_pages: int
|
|
94
|
+
reasoning_reserved_programs: int
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _kv_scale(kv_types: tuple[str, str], *, kv_k_only: bool) -> float:
|
|
98
|
+
k_bpe = _KV_DTYPE_BPE.get(kv_types[0], 2.0)
|
|
99
|
+
return k_bpe / 2.0 if kv_k_only else (k_bpe + _KV_DTYPE_BPE.get(kv_types[1], 2.0)) / 4.0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _profile_recurrent_bytes_1seq(profile: Any, rec_layers: int) -> int:
|
|
103
|
+
if rec_layers <= 0:
|
|
104
|
+
return 0
|
|
105
|
+
d_inner = int(getattr(profile, "ssm_d_inner", 0) or 0)
|
|
106
|
+
d_state = int(getattr(profile, "ssm_d_state", 0) or 0)
|
|
107
|
+
if d_inner > 0 and d_state > 0:
|
|
108
|
+
d_conv = int(getattr(profile, "ssm_d_conv", 0) or 0)
|
|
109
|
+
n_group = int(getattr(profile, "ssm_n_group", 0) or 0)
|
|
110
|
+
conv = max(0, d_conv - 1) * (d_inner + 2 * n_group * d_state)
|
|
111
|
+
return rec_layers * (conv + d_state * d_inner) * 4
|
|
112
|
+
return rec_layers * _RECURRENT_FALLBACK_PER_LAYER
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _catalog_entry_profile(found: dict[str, Any]) -> Any:
|
|
116
|
+
from types import SimpleNamespace
|
|
117
|
+
|
|
118
|
+
per_layer = int(found.get("per_layer_f16") or 0)
|
|
119
|
+
layers = (
|
|
120
|
+
[("full", per_layer)] * int(found.get("full_layers") or 0)
|
|
121
|
+
+ [("swa", per_layer)] * int(found.get("swa_layers") or 0)
|
|
122
|
+
+ [("recurrent", 0)] * int(found.get("recurrent_layers") or 0)
|
|
123
|
+
)
|
|
124
|
+
return SimpleNamespace(
|
|
125
|
+
layers=layers,
|
|
126
|
+
swa_window=int(found.get("swa_window") or 0),
|
|
127
|
+
architecture=str(found.get("architecture") or ""),
|
|
128
|
+
kv_k_only=bool(found.get("kv_k_only", False)),
|
|
129
|
+
ssm_d_inner=int(found.get("ssm_d_inner") or 0),
|
|
130
|
+
ssm_d_state=int(found.get("ssm_d_state") or 0),
|
|
131
|
+
ssm_d_conv=int(found.get("ssm_d_conv") or 0),
|
|
132
|
+
ssm_n_group=int(found.get("ssm_n_group") or 0),
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class HybridMemoryAccounting:
|
|
138
|
+
"""Translate per-program token and phase demand into discrete KV/state pages."""
|
|
139
|
+
|
|
140
|
+
capacity_pages: int
|
|
141
|
+
page_bytes: int
|
|
142
|
+
full_kv_bytes_per_token: float
|
|
143
|
+
resident_state_pages_per_seq: int
|
|
144
|
+
transient_state_pages_per_reasoning: int
|
|
145
|
+
model_id: str
|
|
146
|
+
architecture: str
|
|
147
|
+
kv_types: tuple[str, str] = ("q8_0", "q8_0")
|
|
148
|
+
pool_capacity_bytes: int = 0
|
|
149
|
+
resident_state_bytes_per_seq: int = 0
|
|
150
|
+
transient_state_bytes_per_reasoning: int = 0
|
|
151
|
+
|
|
152
|
+
def __post_init__(self) -> None:
|
|
153
|
+
if self.capacity_pages <= 0 or self.page_bytes <= 0 or self.full_kv_bytes_per_token <= 0:
|
|
154
|
+
raise ValueError("capacity_pages, page_bytes, and full_kv_bytes_per_token must be > 0")
|
|
155
|
+
if self.resident_state_pages_per_seq < 0 or self.transient_state_pages_per_reasoning < 0:
|
|
156
|
+
raise ValueError("state page counts must be non-negative")
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def from_profile(
|
|
160
|
+
cls,
|
|
161
|
+
profile: Any,
|
|
162
|
+
*,
|
|
163
|
+
model_id: str,
|
|
164
|
+
window_tokens: int = 65536,
|
|
165
|
+
slots: int = 2,
|
|
166
|
+
kv_types: tuple[str, str] = ("q8_0", "q8_0"),
|
|
167
|
+
ubatch: int = 512,
|
|
168
|
+
prompt_cache_mib: int = 0,
|
|
169
|
+
page_bytes: int = DEFAULT_PAGE_BYTES,
|
|
170
|
+
) -> HybridMemoryAccounting:
|
|
171
|
+
"""Build exact page accounting from a ``localmodels.estimator.ModelProfile``."""
|
|
172
|
+
if window_tokens <= 0 or slots <= 0 or page_bytes <= 0:
|
|
173
|
+
raise ValueError("window_tokens, slots, and page_bytes must be positive")
|
|
174
|
+
scale = _kv_scale(kv_types, kv_k_only=bool(getattr(profile, "kv_k_only", False)))
|
|
175
|
+
layers: Sequence[tuple[Any, int]] = getattr(profile, "layers", ())
|
|
176
|
+
full_f16 = swa_f16 = rec_layers = 0
|
|
177
|
+
for kind, per_tok in layers:
|
|
178
|
+
name = str(getattr(kind, "value", kind)).lower()
|
|
179
|
+
if name == "recurrent":
|
|
180
|
+
rec_layers += 1
|
|
181
|
+
elif name == "swa":
|
|
182
|
+
swa_f16 += int(per_tok)
|
|
183
|
+
else:
|
|
184
|
+
full_f16 += int(per_tok)
|
|
185
|
+
|
|
186
|
+
swa_window = int(getattr(profile, "swa_window", 0) or 0)
|
|
187
|
+
raw_swa = min(window_tokens, swa_window * slots + max(0, ubatch)) if swa_window > 0 else 0
|
|
188
|
+
swa_tokens = (
|
|
189
|
+
((raw_swa + _SWA_KV_PAD - 1) // _SWA_KV_PAD) * _SWA_KV_PAD if raw_swa > 0 else 0
|
|
190
|
+
)
|
|
191
|
+
kv_pool = int((full_f16 * window_tokens + swa_f16 * swa_tokens) * scale)
|
|
192
|
+
rec_1seq = _profile_recurrent_bytes_1seq(profile, rec_layers)
|
|
193
|
+
swa_resident = int(swa_f16 * swa_window * scale)
|
|
194
|
+
resident_state = rec_1seq + swa_resident
|
|
195
|
+
transient_state = rec_1seq if rec_layers > 0 else (swa_resident // 2)
|
|
196
|
+
pool_bytes = kv_pool + rec_1seq * slots + max(0, prompt_cache_mib) * MIB
|
|
197
|
+
|
|
198
|
+
return cls(
|
|
199
|
+
capacity_pages=max(1, pool_bytes // page_bytes),
|
|
200
|
+
page_bytes=page_bytes,
|
|
201
|
+
full_kv_bytes_per_token=max(1.0, full_f16 * scale),
|
|
202
|
+
resident_state_pages_per_seq=(
|
|
203
|
+
math.ceil(resident_state / page_bytes) if resident_state > 0 else 0
|
|
204
|
+
),
|
|
205
|
+
transient_state_pages_per_reasoning=(
|
|
206
|
+
math.ceil(transient_state / page_bytes) if transient_state > 0 else 0
|
|
207
|
+
),
|
|
208
|
+
model_id=model_id,
|
|
209
|
+
architecture=str(getattr(profile, "architecture", "") or "qwen35"),
|
|
210
|
+
kv_types=kv_types,
|
|
211
|
+
pool_capacity_bytes=pool_bytes,
|
|
212
|
+
resident_state_bytes_per_seq=resident_state,
|
|
213
|
+
transient_state_bytes_per_reasoning=transient_state,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
@classmethod
|
|
217
|
+
def from_catalog_model(
|
|
218
|
+
cls,
|
|
219
|
+
model_id: str,
|
|
220
|
+
*,
|
|
221
|
+
window_tokens: int = 65536,
|
|
222
|
+
slots: int = 2,
|
|
223
|
+
kv_types: tuple[str, str] = ("q8_0", "q8_0"),
|
|
224
|
+
ubatch: int = 512,
|
|
225
|
+
prompt_cache_mib: int = 0,
|
|
226
|
+
page_bytes: int = DEFAULT_PAGE_BYTES,
|
|
227
|
+
catalog_path: Path | None = None,
|
|
228
|
+
) -> HybridMemoryAccounting:
|
|
229
|
+
"""Load one model's geometry from ``catalog.json`` without higher-layer imports."""
|
|
230
|
+
path = (
|
|
231
|
+
catalog_path if catalog_path is not None else Path(__file__).with_name("catalog.json")
|
|
232
|
+
)
|
|
233
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
234
|
+
models = data.get("models", []) if isinstance(data, dict) else []
|
|
235
|
+
needle = model_id.strip().lower()
|
|
236
|
+
found = next(
|
|
237
|
+
(
|
|
238
|
+
item
|
|
239
|
+
for item in models
|
|
240
|
+
if isinstance(item, dict)
|
|
241
|
+
and needle
|
|
242
|
+
in (str(item.get("id", "")).lower(), str(item.get("display_name", "")).lower())
|
|
243
|
+
),
|
|
244
|
+
None,
|
|
245
|
+
)
|
|
246
|
+
if found is None:
|
|
247
|
+
raise KeyError(f"model_id not found in catalog: {model_id!r}")
|
|
248
|
+
return cls.from_profile(
|
|
249
|
+
_catalog_entry_profile(found),
|
|
250
|
+
model_id=str(found.get("id", model_id)),
|
|
251
|
+
window_tokens=window_tokens,
|
|
252
|
+
slots=slots,
|
|
253
|
+
kv_types=kv_types,
|
|
254
|
+
ubatch=ubatch,
|
|
255
|
+
prompt_cache_mib=prompt_cache_mib,
|
|
256
|
+
page_bytes=page_bytes,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
@classmethod
|
|
260
|
+
def default_for_window(
|
|
261
|
+
cls,
|
|
262
|
+
*,
|
|
263
|
+
model_id: str = "generic",
|
|
264
|
+
window_tokens: int = 65536,
|
|
265
|
+
slots: int = 2,
|
|
266
|
+
kv_types: tuple[str, str] = ("q8_0", "q8_0"),
|
|
267
|
+
prompt_cache_mib: int = 0,
|
|
268
|
+
page_bytes: int = DEFAULT_PAGE_BYTES,
|
|
269
|
+
) -> HybridMemoryAccounting:
|
|
270
|
+
"""Conservative pure-attention fallback when ``catalog.json`` is unavailable."""
|
|
271
|
+
if window_tokens <= 0 or slots <= 0 or page_bytes <= 0:
|
|
272
|
+
raise ValueError("window_tokens, slots, and page_bytes must be positive")
|
|
273
|
+
full_kv = max(1.0, 16 * 4096 * _kv_scale(kv_types, kv_k_only=False))
|
|
274
|
+
pool_bytes = int(full_kv * window_tokens) + max(0, prompt_cache_mib) * MIB
|
|
275
|
+
return cls(
|
|
276
|
+
capacity_pages=max(1, pool_bytes // page_bytes),
|
|
277
|
+
page_bytes=page_bytes,
|
|
278
|
+
full_kv_bytes_per_token=full_kv,
|
|
279
|
+
resident_state_pages_per_seq=0,
|
|
280
|
+
transient_state_pages_per_reasoning=0,
|
|
281
|
+
model_id=model_id,
|
|
282
|
+
architecture="generic",
|
|
283
|
+
kv_types=kv_types,
|
|
284
|
+
pool_capacity_bytes=pool_bytes,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def tokens_per_attention_page(self) -> int:
|
|
289
|
+
return max(1, int(self.page_bytes // self.full_kv_bytes_per_token))
|
|
290
|
+
|
|
291
|
+
def attention_pages(
|
|
292
|
+
self, total_tokens: int, *, decode_headroom_tokens: int = 128, token_weight: float = 1.0
|
|
293
|
+
) -> int:
|
|
294
|
+
if (
|
|
295
|
+
decode_headroom_tokens < 0
|
|
296
|
+
or not math.isfinite(token_weight)
|
|
297
|
+
or not 0.0 <= token_weight <= 1.0
|
|
298
|
+
):
|
|
299
|
+
raise ValueError("decode_headroom_tokens >= 0 and token_weight in [0, 1] required")
|
|
300
|
+
demand = (
|
|
301
|
+
max(0, total_tokens) * token_weight + decode_headroom_tokens
|
|
302
|
+
) * self.full_kv_bytes_per_token
|
|
303
|
+
return max(1, math.ceil(demand / self.page_bytes))
|
|
304
|
+
|
|
305
|
+
def program_pages(
|
|
306
|
+
self,
|
|
307
|
+
total_tokens: int,
|
|
308
|
+
*,
|
|
309
|
+
decode_headroom_tokens: int = 128,
|
|
310
|
+
reserve_transient_state: bool = True,
|
|
311
|
+
token_weight: float = 1.0,
|
|
312
|
+
) -> int:
|
|
313
|
+
transient = self.transient_state_pages_per_reasoning if reserve_transient_state else 0
|
|
314
|
+
attn = self.attention_pages(
|
|
315
|
+
total_tokens, decode_headroom_tokens=decode_headroom_tokens, token_weight=token_weight
|
|
316
|
+
)
|
|
317
|
+
return self.resident_state_pages_per_seq + transient + attn
|
|
318
|
+
|
|
319
|
+
def minimum_program_pages(self, *, decode_headroom_tokens: int = 128) -> int:
|
|
320
|
+
return self.program_pages(
|
|
321
|
+
1, decode_headroom_tokens=decode_headroom_tokens, reserve_transient_state=False
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
def contract(self) -> dict[str, Any]:
|
|
325
|
+
return {
|
|
326
|
+
"accounting_mode": "localmodels-hybrid-pages-v1",
|
|
327
|
+
"model_id": self.model_id,
|
|
328
|
+
"architecture": self.architecture,
|
|
329
|
+
"kv_types": list(self.kv_types),
|
|
330
|
+
"page_bytes": self.page_bytes,
|
|
331
|
+
"pool_capacity_bytes": self.pool_capacity_bytes,
|
|
332
|
+
"capacity_pages": self.capacity_pages,
|
|
333
|
+
"tokens_per_attention_page": self.tokens_per_attention_page,
|
|
334
|
+
"resident_state_pages_per_seq": self.resident_state_pages_per_seq,
|
|
335
|
+
"transient_state_pages_per_reasoning": self.transient_state_pages_per_reasoning,
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def resolve_accounting(
|
|
340
|
+
model_id: str | None = None,
|
|
341
|
+
*,
|
|
342
|
+
window_tokens: int = 65536,
|
|
343
|
+
slots: int = 2,
|
|
344
|
+
kv_types: tuple[str, str] = ("q8_0", "q8_0"),
|
|
345
|
+
ubatch: int = 512,
|
|
346
|
+
prompt_cache_mib: int = 0,
|
|
347
|
+
page_bytes: int = DEFAULT_PAGE_BYTES,
|
|
348
|
+
catalog_path: Path | None = None,
|
|
349
|
+
) -> HybridMemoryAccounting:
|
|
350
|
+
"""Resolve model accounting from ``catalog.json`` if available, else a safe window default."""
|
|
351
|
+
common: dict[str, Any] = {
|
|
352
|
+
"window_tokens": window_tokens,
|
|
353
|
+
"slots": slots,
|
|
354
|
+
"kv_types": kv_types,
|
|
355
|
+
"prompt_cache_mib": prompt_cache_mib,
|
|
356
|
+
"page_bytes": page_bytes,
|
|
357
|
+
}
|
|
358
|
+
if model_id:
|
|
359
|
+
try:
|
|
360
|
+
return HybridMemoryAccounting.from_catalog_model(
|
|
361
|
+
model_id, ubatch=ubatch, catalog_path=catalog_path, **common
|
|
362
|
+
)
|
|
363
|
+
except (OSError, ValueError, KeyError):
|
|
364
|
+
pass
|
|
365
|
+
return HybridMemoryAccounting.default_for_window(model_id=model_id or "generic", **common)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@dataclass
|
|
369
|
+
class ProgramState:
|
|
370
|
+
program_id: str
|
|
371
|
+
status: ProgramStatus = ProgramStatus.ACTING
|
|
372
|
+
lifecycle: ProgramLifecycle = ProgramLifecycle.ACTIVE
|
|
373
|
+
total_tokens: int = 0
|
|
374
|
+
context_chars: int = 0
|
|
375
|
+
step_count: int = 0
|
|
376
|
+
acting_since: float | None = None
|
|
377
|
+
marked_for_pause: bool = False
|
|
378
|
+
request_pending: bool = False
|
|
379
|
+
inflight_requests: int = 0
|
|
380
|
+
release_requested: bool = False
|
|
381
|
+
wait_started_monotonic: float | None = None
|
|
382
|
+
service_lag_blocked: bool = False
|
|
383
|
+
waiting_event: threading.Event | None = field(default=None, repr=False)
|
|
384
|
+
request_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
@dataclass(frozen=True)
|
|
388
|
+
class SchedulerConfig:
|
|
389
|
+
"""Tunable knobs for program-aware admission, slot residency, and fairness control."""
|
|
390
|
+
|
|
391
|
+
scheduler_interval_sec: float = 0.05
|
|
392
|
+
acting_decay_base: float = 4.0
|
|
393
|
+
decode_headroom_tokens: int = 128
|
|
394
|
+
high_watermark: float = 0.95
|
|
395
|
+
low_watermark: float = 0.88
|
|
396
|
+
force_resume_timeout_sec: float = 60.0
|
|
397
|
+
fair_wait_threshold_sec: float = 1.5
|
|
398
|
+
aged_resume_quota_per_tick: int = 4
|
|
399
|
+
fair_service_lag_steps: int = 2
|
|
400
|
+
fair_service_until_step: int = 4
|
|
401
|
+
enable_fairness: bool = False
|
|
402
|
+
enable_aged_reservation: bool = True
|
|
403
|
+
static_concurrency_cap: int = 0
|
|
404
|
+
max_resident_programs: int = 0
|
|
405
|
+
|
|
406
|
+
def __post_init__(self) -> None:
|
|
407
|
+
bad_time = (
|
|
408
|
+
self.scheduler_interval_sec <= 0
|
|
409
|
+
or self.force_resume_timeout_sec <= 0
|
|
410
|
+
or self.fair_wait_threshold_sec <= 0
|
|
411
|
+
or self.acting_decay_base <= 1.0
|
|
412
|
+
)
|
|
413
|
+
bad_bounds = (
|
|
414
|
+
not 0.0 < self.low_watermark <= self.high_watermark <= 1.0
|
|
415
|
+
or self.decode_headroom_tokens < 0
|
|
416
|
+
or self.aged_resume_quota_per_tick <= 0
|
|
417
|
+
or self.fair_service_lag_steps < 0
|
|
418
|
+
or self.fair_service_until_step <= 0
|
|
419
|
+
or self.static_concurrency_cap < 0
|
|
420
|
+
or self.max_resident_programs < 0
|
|
421
|
+
)
|
|
422
|
+
if bad_time or bad_bounds:
|
|
423
|
+
raise ValueError("invalid SchedulerConfig parameter bounds")
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass(frozen=True)
|
|
427
|
+
class ProgramOptions:
|
|
428
|
+
"""Opt-in CLI/env configuration for enabling program-aware scheduling in a proxy."""
|
|
429
|
+
|
|
430
|
+
enabled: bool = False
|
|
431
|
+
model_id: str | None = None
|
|
432
|
+
window_tokens: int = 65536
|
|
433
|
+
slots: int = 2
|
|
434
|
+
kv_k: str = "q8_0"
|
|
435
|
+
kv_v: str = "q8_0"
|
|
436
|
+
prompt_cache_mib: int = 0
|
|
437
|
+
max_resident_programs: int = 0
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _env_int(name: str, default: int, *, minimum: int = 0) -> int:
|
|
441
|
+
raw = os.environ.get(name)
|
|
442
|
+
if not raw:
|
|
443
|
+
return default
|
|
444
|
+
try:
|
|
445
|
+
parsed = int(raw.strip())
|
|
446
|
+
except ValueError:
|
|
447
|
+
return default
|
|
448
|
+
return parsed if parsed >= minimum else default
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _env_kv(name: str, default: str) -> str:
|
|
452
|
+
raw = (os.environ.get(name) or "").strip().lower()
|
|
453
|
+
return raw if raw in _KV_DTYPE_BPE else default
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def env_program_aware_enabled() -> bool:
|
|
457
|
+
"""Return True when ``LOCALMODELS_PROGRAM_AWARE`` is explicitly set to a truthy value."""
|
|
458
|
+
return (os.environ.get(PROGRAM_AWARE_ENV) or "").strip().lower() in _TRUTHY_ENV
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def options_from_env(
|
|
462
|
+
*,
|
|
463
|
+
enabled: bool = False,
|
|
464
|
+
model_id: str | None = None,
|
|
465
|
+
window_tokens: int | None = None,
|
|
466
|
+
slots: int | None = None,
|
|
467
|
+
kv_k: str | None = None,
|
|
468
|
+
kv_v: str | None = None,
|
|
469
|
+
prompt_cache_mib: int | None = None,
|
|
470
|
+
max_resident_programs: int | None = None,
|
|
471
|
+
) -> ProgramOptions:
|
|
472
|
+
"""Merge explicit CLI overrides over ``LOCALMODELS_PROGRAM_*`` environment variables."""
|
|
473
|
+
resolved_model = model_id if model_id is not None else (os.environ.get(PROGRAM_MODEL_ENV) or "")
|
|
474
|
+
return ProgramOptions(
|
|
475
|
+
enabled=enabled or env_program_aware_enabled(),
|
|
476
|
+
model_id=resolved_model.strip() or None,
|
|
477
|
+
window_tokens=window_tokens
|
|
478
|
+
if window_tokens is not None
|
|
479
|
+
else _env_int(PROGRAM_WINDOW_ENV, 65536, minimum=1),
|
|
480
|
+
slots=slots if slots is not None else _env_int(PROGRAM_SLOTS_ENV, 2, minimum=1),
|
|
481
|
+
kv_k=kv_k if kv_k is not None else _env_kv(PROGRAM_KV_K_ENV, "q8_0"),
|
|
482
|
+
kv_v=kv_v if kv_v is not None else _env_kv(PROGRAM_KV_V_ENV, "q8_0"),
|
|
483
|
+
prompt_cache_mib=prompt_cache_mib
|
|
484
|
+
if prompt_cache_mib is not None
|
|
485
|
+
else _env_int(PROGRAM_CACHE_MIB_ENV, 0),
|
|
486
|
+
max_resident_programs=max_resident_programs
|
|
487
|
+
if max_resident_programs is not None
|
|
488
|
+
else _env_int(PROGRAM_MAX_RESIDENT_ENV, 0),
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def extract_usage(payload: Any) -> tuple[int | None, int | None]:
|
|
493
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("usage"), dict):
|
|
494
|
+
return None, None
|
|
495
|
+
usage = payload["usage"]
|
|
496
|
+
|
|
497
|
+
def pos_int(key: str) -> int | None:
|
|
498
|
+
val = usage.get(key)
|
|
499
|
+
if isinstance(val, bool) or not (isinstance(val, int) or isinstance(val, float)):
|
|
500
|
+
return None
|
|
501
|
+
num = int(val)
|
|
502
|
+
return num if num > 0 else None
|
|
503
|
+
|
|
504
|
+
return pos_int("total_tokens"), pos_int("prompt_tokens")
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def request_is_streaming(body: bytes | None) -> bool:
|
|
508
|
+
if not body:
|
|
509
|
+
return False
|
|
510
|
+
try:
|
|
511
|
+
parsed = json.loads(body)
|
|
512
|
+
except (UnicodeDecodeError, ValueError):
|
|
513
|
+
return False
|
|
514
|
+
return isinstance(parsed, dict) and parsed.get("stream") is True
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
class UsageObserver:
|
|
518
|
+
"""Bounded read-only observer over relayed response bytes; never mutates payload data."""
|
|
519
|
+
|
|
520
|
+
def __init__(self, streaming: bool) -> None:
|
|
521
|
+
self.streaming = streaming
|
|
522
|
+
self._line_buf = bytearray()
|
|
523
|
+
self._body_buf = bytearray()
|
|
524
|
+
self.total_tokens: int | None = None
|
|
525
|
+
self.prompt_tokens: int | None = None
|
|
526
|
+
self._pending_events = 0
|
|
527
|
+
|
|
528
|
+
def _record(self, payload: Any) -> None:
|
|
529
|
+
total, prompt = extract_usage(payload)
|
|
530
|
+
if total is not None:
|
|
531
|
+
self.total_tokens = total
|
|
532
|
+
if prompt is not None:
|
|
533
|
+
self.prompt_tokens = prompt
|
|
534
|
+
|
|
535
|
+
def feed(self, chunk: bytes) -> int:
|
|
536
|
+
if not self.streaming:
|
|
537
|
+
if len(self._body_buf) + len(chunk) <= OBSERVER_LIMIT_BYTES:
|
|
538
|
+
self._body_buf.extend(chunk)
|
|
539
|
+
return 0
|
|
540
|
+
if len(self._line_buf) + len(chunk) > OBSERVER_LIMIT_BYTES:
|
|
541
|
+
self._line_buf.clear()
|
|
542
|
+
return 0
|
|
543
|
+
delta = 0
|
|
544
|
+
self._line_buf.extend(chunk)
|
|
545
|
+
while b"\n" in self._line_buf:
|
|
546
|
+
raw, _, rest = self._line_buf.partition(b"\n")
|
|
547
|
+
self._line_buf[:] = rest
|
|
548
|
+
line = raw.rstrip(b"\r")
|
|
549
|
+
if not line.startswith(b"data:"):
|
|
550
|
+
continue
|
|
551
|
+
data = line[5:].strip()
|
|
552
|
+
if not data or data == b"[DONE]":
|
|
553
|
+
continue
|
|
554
|
+
try:
|
|
555
|
+
self._record(json.loads(data))
|
|
556
|
+
except (ValueError, UnicodeDecodeError):
|
|
557
|
+
continue
|
|
558
|
+
self._pending_events += 1
|
|
559
|
+
if self._pending_events >= 16:
|
|
560
|
+
delta += self._pending_events
|
|
561
|
+
self._pending_events = 0
|
|
562
|
+
return delta
|
|
563
|
+
|
|
564
|
+
def finish(self) -> None:
|
|
565
|
+
if self.streaming or not self._body_buf:
|
|
566
|
+
return
|
|
567
|
+
try:
|
|
568
|
+
self._record(json.loads(self._body_buf))
|
|
569
|
+
except (ValueError, UnicodeDecodeError):
|
|
570
|
+
return
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
class ProgramAwareScheduler:
|
|
574
|
+
"""Thread-safe hybrid-memory-aware program scheduler with aged fairness reservation."""
|
|
575
|
+
|
|
576
|
+
def __init__(
|
|
577
|
+
self, accounting: HybridMemoryAccounting, config: SchedulerConfig | None = None
|
|
578
|
+
) -> None:
|
|
579
|
+
self.accounting = accounting
|
|
580
|
+
self.config = config or SchedulerConfig()
|
|
581
|
+
self.programs: dict[str, ProgramState] = {}
|
|
582
|
+
self.waiting: OrderedDict[str, float] = OrderedDict()
|
|
583
|
+
self.char_to_token_ratio: float = 4.0
|
|
584
|
+
self._ratio_initialized = False
|
|
585
|
+
self._lock = threading.Lock()
|
|
586
|
+
self._stop_event = threading.Event()
|
|
587
|
+
self._thread: threading.Thread | None = None
|
|
588
|
+
self._aged_owner_id: str | None = None
|
|
589
|
+
self._anon_seq = 0
|
|
590
|
+
self._peaks: dict[str, float] = {
|
|
591
|
+
"programs": 0,
|
|
592
|
+
"active": 0,
|
|
593
|
+
"paused": 0,
|
|
594
|
+
"pages_full": 0,
|
|
595
|
+
"wait_sec_max": 0.0,
|
|
596
|
+
}
|
|
597
|
+
self._counters: dict[str, int] = dict.fromkeys(_COUNTER_NAMES, 0)
|
|
598
|
+
self._wait_samples: list[float] = []
|
|
599
|
+
|
|
600
|
+
@property
|
|
601
|
+
def high_capacity_pages(self) -> float:
|
|
602
|
+
return self.accounting.capacity_pages * self.config.high_watermark
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def low_capacity_pages(self) -> float:
|
|
606
|
+
return self.accounting.capacity_pages * self.config.low_watermark
|
|
607
|
+
|
|
608
|
+
def start(self) -> None:
|
|
609
|
+
with self._lock:
|
|
610
|
+
if self._thread is not None and self._thread.is_alive():
|
|
611
|
+
return
|
|
612
|
+
self._stop_event.clear()
|
|
613
|
+
thread = threading.Thread(
|
|
614
|
+
target=self._loop, name="localmodels-program-scheduler", daemon=True
|
|
615
|
+
)
|
|
616
|
+
self._thread = thread
|
|
617
|
+
thread.start()
|
|
618
|
+
|
|
619
|
+
def stop(self) -> None:
|
|
620
|
+
self._stop_event.set()
|
|
621
|
+
thread = self._thread
|
|
622
|
+
if thread is not None and thread.is_alive():
|
|
623
|
+
thread.join(timeout=2.0)
|
|
624
|
+
with self._lock:
|
|
625
|
+
self._thread = None
|
|
626
|
+
for prog in self.programs.values():
|
|
627
|
+
if prog.waiting_event is not None:
|
|
628
|
+
prog.waiting_event.set()
|
|
629
|
+
|
|
630
|
+
def next_anonymous_id(self) -> str:
|
|
631
|
+
with self._lock:
|
|
632
|
+
self._anon_seq += 1
|
|
633
|
+
return f"__anon__-{self._anon_seq}"
|
|
634
|
+
|
|
635
|
+
def get_or_create(self, program_id: str) -> ProgramState:
|
|
636
|
+
with self._lock:
|
|
637
|
+
prog = self.programs.get(program_id)
|
|
638
|
+
if prog is None:
|
|
639
|
+
prog = ProgramState(program_id=program_id)
|
|
640
|
+
self.programs[program_id] = prog
|
|
641
|
+
self._peaks["programs"] = max(self._peaks["programs"], len(self.programs))
|
|
642
|
+
return prog
|
|
643
|
+
|
|
644
|
+
def _required_pages(self, prog: ProgramState, *, token_weight: float = 1.0) -> int:
|
|
645
|
+
reserve_transient = prog.status == ProgramStatus.REASONING or prog.request_pending
|
|
646
|
+
return self.accounting.program_pages(
|
|
647
|
+
prog.total_tokens,
|
|
648
|
+
decode_headroom_tokens=self.config.decode_headroom_tokens,
|
|
649
|
+
reserve_transient_state=reserve_transient,
|
|
650
|
+
token_weight=token_weight,
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
def _active_programs_locked(self) -> list[ProgramState]:
|
|
654
|
+
return [
|
|
655
|
+
p
|
|
656
|
+
for p in self.programs.values()
|
|
657
|
+
if p.lifecycle == ProgramLifecycle.ACTIVE and p.step_count > 0
|
|
658
|
+
]
|
|
659
|
+
|
|
660
|
+
def _breakdown_locked(self, now: float, *, decay: bool) -> PageBreakdown:
|
|
661
|
+
attn = res_state = trans_state = reasoning_count = 0
|
|
662
|
+
for prog in self._active_programs_locked():
|
|
663
|
+
reserve_transient = prog.status == ProgramStatus.REASONING or prog.request_pending
|
|
664
|
+
reasoning_count += int(reserve_transient)
|
|
665
|
+
weight = 1.0
|
|
666
|
+
if (
|
|
667
|
+
decay
|
|
668
|
+
and prog.status == ProgramStatus.ACTING
|
|
669
|
+
and not prog.request_pending
|
|
670
|
+
and prog.acting_since is not None
|
|
671
|
+
):
|
|
672
|
+
weight = self.config.acting_decay_base ** (-max(0.0, now - prog.acting_since))
|
|
673
|
+
attn += self.accounting.attention_pages(
|
|
674
|
+
prog.total_tokens,
|
|
675
|
+
decode_headroom_tokens=self.config.decode_headroom_tokens,
|
|
676
|
+
token_weight=weight,
|
|
677
|
+
)
|
|
678
|
+
res_state += self.accounting.resident_state_pages_per_seq
|
|
679
|
+
if reserve_transient:
|
|
680
|
+
trans_state += self.accounting.transient_state_pages_per_reasoning
|
|
681
|
+
return PageBreakdown(
|
|
682
|
+
attn + res_state + trans_state, attn, res_state, trans_state, reasoning_count
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
def _full_used_pages_locked(self) -> int:
|
|
686
|
+
return sum(self._required_pages(p) for p in self._active_programs_locked())
|
|
687
|
+
|
|
688
|
+
def _observe_peaks_locked(self) -> None:
|
|
689
|
+
active = self._active_programs_locked()
|
|
690
|
+
self._peaks["active"] = max(self._peaks["active"], len(active))
|
|
691
|
+
self._peaks["paused"] = max(self._peaks["paused"], len(self.waiting))
|
|
692
|
+
self._peaks["pages_full"] = max(
|
|
693
|
+
self._peaks["pages_full"], sum(self._required_pages(p) for p in active)
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
def _pause_locked(self, prog: ProgramState, now_mono: float) -> None:
|
|
697
|
+
if prog.lifecycle != ProgramLifecycle.PAUSED:
|
|
698
|
+
prog.lifecycle = ProgramLifecycle.PAUSED
|
|
699
|
+
prog.waiting_event = threading.Event()
|
|
700
|
+
if prog.request_pending and prog.wait_started_monotonic is None:
|
|
701
|
+
prog.wait_started_monotonic = now_mono
|
|
702
|
+
self.waiting[prog.program_id] = self.waiting.get(prog.program_id, now_mono)
|
|
703
|
+
self._observe_peaks_locked()
|
|
704
|
+
|
|
705
|
+
def _resume_locked(self, prog: ProgramState) -> None:
|
|
706
|
+
if prog.lifecycle != ProgramLifecycle.PAUSED:
|
|
707
|
+
return
|
|
708
|
+
if self._aged_owner_id == prog.program_id:
|
|
709
|
+
self._aged_owner_id = None
|
|
710
|
+
self.waiting.pop(prog.program_id, None)
|
|
711
|
+
prog.lifecycle = ProgramLifecycle.ACTIVE
|
|
712
|
+
prog.wait_started_monotonic = None
|
|
713
|
+
prog.service_lag_blocked = False
|
|
714
|
+
event, prog.waiting_event = prog.waiting_event, None
|
|
715
|
+
if event is not None:
|
|
716
|
+
event.set()
|
|
717
|
+
self._observe_peaks_locked()
|
|
718
|
+
|
|
719
|
+
def _can_fit_program_locked(self, req: int) -> bool:
|
|
720
|
+
cap = self.config.max_resident_programs
|
|
721
|
+
if cap > 0 and len(self._active_programs_locked()) >= cap:
|
|
722
|
+
return False
|
|
723
|
+
return self._full_used_pages_locked() + req <= self.high_capacity_pages
|
|
724
|
+
|
|
725
|
+
def _should_block_service_lag_locked(self, prog: ProgramState) -> bool:
|
|
726
|
+
if not self.config.enable_fairness or prog.step_count > self.config.fair_service_until_step:
|
|
727
|
+
return False
|
|
728
|
+
steps = [
|
|
729
|
+
w.step_count
|
|
730
|
+
for pid in self.waiting
|
|
731
|
+
for w in (self.programs.get(pid),)
|
|
732
|
+
if w is not None
|
|
733
|
+
and w.lifecycle == ProgramLifecycle.PAUSED
|
|
734
|
+
and w.request_pending
|
|
735
|
+
and self._required_pages(w) <= self.high_capacity_pages
|
|
736
|
+
]
|
|
737
|
+
return bool(steps) and prog.step_count > min(steps) + self.config.fair_service_lag_steps
|
|
738
|
+
|
|
739
|
+
def _aged_reservation_blocks_locked(self, prog: ProgramState) -> bool:
|
|
740
|
+
if not self.config.enable_aged_reservation or self._aged_owner_id is None:
|
|
741
|
+
return False
|
|
742
|
+
owner = self.programs.get(self._aged_owner_id)
|
|
743
|
+
if owner is None or owner is prog or owner.lifecycle != ProgramLifecycle.PAUSED:
|
|
744
|
+
return False
|
|
745
|
+
return not self._can_fit_program_locked(self._required_pages(owner))
|
|
746
|
+
|
|
747
|
+
def _admission_block_reason_locked(self, prog: ProgramState, *, is_new: bool) -> str | None:
|
|
748
|
+
active = self._active_programs_locked()
|
|
749
|
+
if (
|
|
750
|
+
self.config.max_resident_programs > 0
|
|
751
|
+
and len(active) > self.config.max_resident_programs
|
|
752
|
+
):
|
|
753
|
+
return "resident_cap"
|
|
754
|
+
stat_cap = self.config.static_concurrency_cap
|
|
755
|
+
if (
|
|
756
|
+
stat_cap > 0
|
|
757
|
+
and sum(1 for p in active if p.status == ProgramStatus.REASONING or p.request_pending)
|
|
758
|
+
> stat_cap
|
|
759
|
+
):
|
|
760
|
+
return "static_cap"
|
|
761
|
+
if is_new and bool(self.waiting):
|
|
762
|
+
return "queue_fifo"
|
|
763
|
+
if self._full_used_pages_locked() > self.high_capacity_pages:
|
|
764
|
+
return "capacity"
|
|
765
|
+
if not is_new and self._aged_reservation_blocks_locked(prog):
|
|
766
|
+
return "aged_reservation"
|
|
767
|
+
if not is_new and self._should_block_service_lag_locked(prog):
|
|
768
|
+
return "service_lag"
|
|
769
|
+
return None
|
|
770
|
+
|
|
771
|
+
def _record_pause_reason_locked(self, prog: ProgramState, reason: str, now_mono: float) -> None:
|
|
772
|
+
prog.service_lag_blocked = reason == "service_lag"
|
|
773
|
+
self._pause_locked(prog, now_mono)
|
|
774
|
+
self._counters["paused_on_admission"] += 1
|
|
775
|
+
key = {
|
|
776
|
+
"resident_cap": "paused_resident_cap",
|
|
777
|
+
"service_lag": "paused_service_lag",
|
|
778
|
+
"aged_reservation": "paused_aged_reservation",
|
|
779
|
+
}.get(reason)
|
|
780
|
+
if key is not None:
|
|
781
|
+
self._counters[key] += 1
|
|
782
|
+
|
|
783
|
+
def _wait_for_admission(
|
|
784
|
+
self,
|
|
785
|
+
prog: ProgramState,
|
|
786
|
+
wait_event: threading.Event,
|
|
787
|
+
is_cancelled: Callable[[], bool] | None,
|
|
788
|
+
) -> float:
|
|
789
|
+
wait_start = time.monotonic()
|
|
790
|
+
deadline = wait_start + self.config.force_resume_timeout_sec
|
|
791
|
+
while not wait_event.is_set():
|
|
792
|
+
if is_cancelled is not None and is_cancelled():
|
|
793
|
+
with self._lock:
|
|
794
|
+
self._record_wait_locked(max(0.0, time.monotonic() - wait_start))
|
|
795
|
+
raise ProgramCancelledError(prog.program_id)
|
|
796
|
+
remaining = deadline - time.monotonic()
|
|
797
|
+
if remaining <= 0:
|
|
798
|
+
with self._lock:
|
|
799
|
+
self._record_wait_locked(max(0.0, time.monotonic() - wait_start))
|
|
800
|
+
if prog.lifecycle == ProgramLifecycle.PAUSED:
|
|
801
|
+
if self._can_fit_program_locked(self._required_pages(prog)):
|
|
802
|
+
self._resume_locked(prog)
|
|
803
|
+
else:
|
|
804
|
+
self._counters["capacity_timeouts"] += 1
|
|
805
|
+
raise ProgramAdmissionTimeoutError(prog.program_id)
|
|
806
|
+
break
|
|
807
|
+
wait_event.wait(timeout=min(remaining, 0.05) if is_cancelled is not None else remaining)
|
|
808
|
+
return max(0.0, time.monotonic() - wait_start)
|
|
809
|
+
|
|
810
|
+
def begin_request(
|
|
811
|
+
self,
|
|
812
|
+
prog: ProgramState,
|
|
813
|
+
context_chars: int,
|
|
814
|
+
*,
|
|
815
|
+
is_cancelled: Callable[[], bool] | None = None,
|
|
816
|
+
) -> float:
|
|
817
|
+
"""Admit a program's next chat turn, waiting if paused. Returns gateway wait seconds."""
|
|
818
|
+
wait_event: threading.Event | None = None
|
|
819
|
+
with self._lock:
|
|
820
|
+
if self.programs.get(prog.program_id) is not prog:
|
|
821
|
+
raise ProgramReleasedError(prog.program_id)
|
|
822
|
+
now_mono = time.monotonic()
|
|
823
|
+
is_new = prog.step_count == 0
|
|
824
|
+
prog.step_count += 1
|
|
825
|
+
prog.context_chars = max(0, context_chars)
|
|
826
|
+
est_tokens = max(1, int(prog.context_chars / max(self.char_to_token_ratio, 1e-6)))
|
|
827
|
+
prog.total_tokens = max(prog.total_tokens, est_tokens)
|
|
828
|
+
prog.status = ProgramStatus.REASONING
|
|
829
|
+
prog.acting_since = None
|
|
830
|
+
prog.request_pending = True
|
|
831
|
+
|
|
832
|
+
if prog.lifecycle == ProgramLifecycle.PAUSED:
|
|
833
|
+
prog.waiting_event = prog.waiting_event or threading.Event()
|
|
834
|
+
if prog.wait_started_monotonic is None:
|
|
835
|
+
prog.wait_started_monotonic = now_mono
|
|
836
|
+
wait_event = prog.waiting_event
|
|
837
|
+
self._observe_peaks_locked()
|
|
838
|
+
else:
|
|
839
|
+
reason = self._admission_block_reason_locked(prog, is_new=is_new)
|
|
840
|
+
if reason is not None:
|
|
841
|
+
self._record_pause_reason_locked(prog, reason, now_mono)
|
|
842
|
+
wait_event = prog.waiting_event
|
|
843
|
+
else:
|
|
844
|
+
prog.inflight_requests += 1
|
|
845
|
+
self._counters["admitted_immediately"] += 1
|
|
846
|
+
self._observe_peaks_locked()
|
|
847
|
+
|
|
848
|
+
if wait_event is None:
|
|
849
|
+
return 0.0
|
|
850
|
+
waited = self._wait_for_admission(prog, wait_event, is_cancelled)
|
|
851
|
+
with self._lock:
|
|
852
|
+
self._record_wait_locked(waited)
|
|
853
|
+
if self.programs.get(prog.program_id) is not prog:
|
|
854
|
+
raise ProgramReleasedError(prog.program_id)
|
|
855
|
+
if prog.lifecycle != ProgramLifecycle.ACTIVE:
|
|
856
|
+
raise ProgramAdmissionTimeoutError(prog.program_id)
|
|
857
|
+
prog.inflight_requests += 1
|
|
858
|
+
return waited
|
|
859
|
+
|
|
860
|
+
def _record_wait_locked(self, waited: float) -> None:
|
|
861
|
+
self._wait_samples.append(waited)
|
|
862
|
+
self._peaks["wait_sec_max"] = max(self._peaks["wait_sec_max"], waited)
|
|
863
|
+
|
|
864
|
+
def cancel_waiting_request(self, prog: ProgramState) -> None:
|
|
865
|
+
with self._lock:
|
|
866
|
+
if self.programs.get(prog.program_id) is not prog:
|
|
867
|
+
return
|
|
868
|
+
self._counters["cancelled_waiters"] += 1
|
|
869
|
+
if self._aged_owner_id == prog.program_id:
|
|
870
|
+
self._aged_owner_id = None
|
|
871
|
+
prog.request_pending = False
|
|
872
|
+
prog.wait_started_monotonic = None
|
|
873
|
+
prog.service_lag_blocked = False
|
|
874
|
+
if prog.step_count <= 1 and prog.lifecycle == ProgramLifecycle.PAUSED:
|
|
875
|
+
self.waiting.pop(prog.program_id, None)
|
|
876
|
+
prog.lifecycle = ProgramLifecycle.TERMINATED
|
|
877
|
+
if prog.waiting_event is not None:
|
|
878
|
+
prog.waiting_event.set()
|
|
879
|
+
self.programs.pop(prog.program_id, None)
|
|
880
|
+
else:
|
|
881
|
+
prog.status = ProgramStatus.ACTING
|
|
882
|
+
prog.acting_since = time.time()
|
|
883
|
+
self._schedule_tick_locked(time.time(), time.monotonic())
|
|
884
|
+
|
|
885
|
+
def update_streaming_tokens(self, prog: ProgramState, delta_tokens: int) -> None:
|
|
886
|
+
if delta_tokens <= 0:
|
|
887
|
+
return
|
|
888
|
+
with self._lock:
|
|
889
|
+
if (
|
|
890
|
+
self.programs.get(prog.program_id) is prog
|
|
891
|
+
and prog.inflight_requests > 0
|
|
892
|
+
and prog.status == ProgramStatus.REASONING
|
|
893
|
+
):
|
|
894
|
+
prog.total_tokens += delta_tokens
|
|
895
|
+
self._observe_peaks_locked()
|
|
896
|
+
|
|
897
|
+
def finish_request(
|
|
898
|
+
self, prog: ProgramState, *, total_tokens: int | None, prompt_tokens: int | None
|
|
899
|
+
) -> None:
|
|
900
|
+
with self._lock:
|
|
901
|
+
if self.programs.get(prog.program_id) is not prog:
|
|
902
|
+
return
|
|
903
|
+
if isinstance(prompt_tokens, int) and prompt_tokens > 0 and prog.context_chars > 0:
|
|
904
|
+
sample = prog.context_chars / prompt_tokens
|
|
905
|
+
if math.isfinite(sample) and sample > 0:
|
|
906
|
+
self.char_to_token_ratio = (
|
|
907
|
+
sample
|
|
908
|
+
if not self._ratio_initialized
|
|
909
|
+
else 0.2 * sample + 0.8 * self.char_to_token_ratio
|
|
910
|
+
)
|
|
911
|
+
self._ratio_initialized = True
|
|
912
|
+
if isinstance(total_tokens, int) and total_tokens > 0:
|
|
913
|
+
prog.total_tokens = total_tokens
|
|
914
|
+
prog.inflight_requests = max(0, prog.inflight_requests - 1)
|
|
915
|
+
prog.request_pending = False
|
|
916
|
+
if prog.release_requested and prog.inflight_requests == 0:
|
|
917
|
+
self._terminate_locked(prog)
|
|
918
|
+
self._schedule_tick_locked(time.time(), time.monotonic())
|
|
919
|
+
return
|
|
920
|
+
prog.status = ProgramStatus.ACTING
|
|
921
|
+
prog.acting_since = time.time()
|
|
922
|
+
if prog.marked_for_pause:
|
|
923
|
+
prog.marked_for_pause = False
|
|
924
|
+
self._pause_locked(prog, time.monotonic())
|
|
925
|
+
self._schedule_tick_locked(time.time(), time.monotonic())
|
|
926
|
+
|
|
927
|
+
def release_program(self, program_id: str) -> tuple[bool, bool]:
|
|
928
|
+
with self._lock:
|
|
929
|
+
prog = self.programs.get(program_id)
|
|
930
|
+
if prog is None:
|
|
931
|
+
return False, False
|
|
932
|
+
if prog.inflight_requests > 0:
|
|
933
|
+
prog.release_requested = True
|
|
934
|
+
self._counters["release_deferred"] += 1
|
|
935
|
+
return True, False
|
|
936
|
+
self._terminate_locked(prog)
|
|
937
|
+
self._schedule_tick_locked(time.time(), time.monotonic())
|
|
938
|
+
return True, True
|
|
939
|
+
|
|
940
|
+
def _terminate_locked(self, prog: ProgramState) -> None:
|
|
941
|
+
if self._aged_owner_id == prog.program_id:
|
|
942
|
+
self._aged_owner_id = None
|
|
943
|
+
self.programs.pop(prog.program_id, None)
|
|
944
|
+
self.waiting.pop(prog.program_id, None)
|
|
945
|
+
prog.lifecycle = ProgramLifecycle.TERMINATED
|
|
946
|
+
prog.request_pending = False
|
|
947
|
+
prog.wait_started_monotonic = None
|
|
948
|
+
prog.service_lag_blocked = False
|
|
949
|
+
prog.release_requested = False
|
|
950
|
+
if prog.waiting_event is not None:
|
|
951
|
+
prog.waiting_event.set()
|
|
952
|
+
self._counters["released"] += 1
|
|
953
|
+
self._observe_peaks_locked()
|
|
954
|
+
|
|
955
|
+
def schedule_once(self) -> None:
|
|
956
|
+
with self._lock:
|
|
957
|
+
self._schedule_tick_locked(time.time(), time.monotonic())
|
|
958
|
+
|
|
959
|
+
def _schedule_tick_locked(self, now: float, now_mono: float) -> None:
|
|
960
|
+
self._counters["ticks"] += 1
|
|
961
|
+
self._restore_waiting_locked(now, now_mono)
|
|
962
|
+
self._pause_until_safe_locked(now_mono)
|
|
963
|
+
self._observe_peaks_locked()
|
|
964
|
+
|
|
965
|
+
def _service_aged_reservation_locked(
|
|
966
|
+
self, aged: list[ProgramState], now_mono: float
|
|
967
|
+
) -> tuple[set[str], bool]:
|
|
968
|
+
if not self.config.enable_aged_reservation:
|
|
969
|
+
return set(), False
|
|
970
|
+
owner = self.programs.get(self._aged_owner_id) if self._aged_owner_id else None
|
|
971
|
+
if owner is None or owner.lifecycle != ProgramLifecycle.PAUSED or not owner.request_pending:
|
|
972
|
+
self._aged_owner_id = None
|
|
973
|
+
owner = next(
|
|
974
|
+
(p for p in aged if self._required_pages(p) <= self.high_capacity_pages), None
|
|
975
|
+
)
|
|
976
|
+
if owner is not None:
|
|
977
|
+
self._aged_owner_id = owner.program_id
|
|
978
|
+
if owner is None:
|
|
979
|
+
return set(), False
|
|
980
|
+
|
|
981
|
+
req = self._required_pages(owner)
|
|
982
|
+
victims: set[str] = set()
|
|
983
|
+
idle_acting = sorted(
|
|
984
|
+
(
|
|
985
|
+
p
|
|
986
|
+
for p in self._active_programs_locked()
|
|
987
|
+
if p.status == ProgramStatus.ACTING
|
|
988
|
+
and not p.request_pending
|
|
989
|
+
and p.inflight_requests == 0
|
|
990
|
+
and not p.marked_for_pause
|
|
991
|
+
),
|
|
992
|
+
key=lambda p: (p.total_tokens, p.program_id),
|
|
993
|
+
)
|
|
994
|
+
for victim in idle_acting:
|
|
995
|
+
if self._can_fit_program_locked(req):
|
|
996
|
+
break
|
|
997
|
+
self._pause_locked(victim, now_mono)
|
|
998
|
+
self._counters["paused_acting_eviction"] += 1
|
|
999
|
+
victims.add(victim.program_id)
|
|
1000
|
+
|
|
1001
|
+
if self._can_fit_program_locked(req):
|
|
1002
|
+
self._resume_locked(owner)
|
|
1003
|
+
self._counters["resumed_aged_owner"] += 1
|
|
1004
|
+
return victims, False
|
|
1005
|
+
return victims, True
|
|
1006
|
+
|
|
1007
|
+
def _paused_programs_locked(self) -> list[ProgramState]:
|
|
1008
|
+
return [
|
|
1009
|
+
self.programs[pid]
|
|
1010
|
+
for pid in self.waiting
|
|
1011
|
+
if pid in self.programs and self.programs[pid].lifecycle == ProgramLifecycle.PAUSED
|
|
1012
|
+
]
|
|
1013
|
+
|
|
1014
|
+
def _ordered_restore_tiers_locked(
|
|
1015
|
+
self, paused: list[ProgramState], aged_ids: set[str], victims: set[str]
|
|
1016
|
+
) -> list[ProgramState]:
|
|
1017
|
+
fair, until = self.config.enable_fairness, self.config.fair_service_until_step
|
|
1018
|
+
|
|
1019
|
+
def pending_key(prog: ProgramState) -> tuple[int, int, int, float, str]:
|
|
1020
|
+
is_deep = int(fair and prog.step_count > until)
|
|
1021
|
+
step = prog.step_count if (fair and not is_deep) else 0
|
|
1022
|
+
return (
|
|
1023
|
+
is_deep,
|
|
1024
|
+
step,
|
|
1025
|
+
prog.total_tokens,
|
|
1026
|
+
prog.wait_started_monotonic or 0.0,
|
|
1027
|
+
prog.program_id,
|
|
1028
|
+
)
|
|
1029
|
+
|
|
1030
|
+
pending = sorted(
|
|
1031
|
+
(p for p in paused if p.request_pending and p.program_id not in aged_ids),
|
|
1032
|
+
key=pending_key,
|
|
1033
|
+
)
|
|
1034
|
+
idle = sorted(
|
|
1035
|
+
(p for p in paused if not p.request_pending and p.program_id not in victims),
|
|
1036
|
+
key=lambda p: p.total_tokens,
|
|
1037
|
+
)
|
|
1038
|
+
return [*pending, *idle]
|
|
1039
|
+
|
|
1040
|
+
def _select_for_restore_locked(
|
|
1041
|
+
self,
|
|
1042
|
+
aged: list[ProgramState],
|
|
1043
|
+
ordered_others: list[ProgramState],
|
|
1044
|
+
victims: set[str],
|
|
1045
|
+
available: float,
|
|
1046
|
+
) -> list[ProgramState]:
|
|
1047
|
+
selected: list[ProgramState] = []
|
|
1048
|
+
selected_ids: set[str] = set()
|
|
1049
|
+
committed = 0.0
|
|
1050
|
+
active = self._active_programs_locked()
|
|
1051
|
+
active_total = len(active)
|
|
1052
|
+
active_reasoning = sum(
|
|
1053
|
+
1 for p in active if p.status == ProgramStatus.REASONING or p.request_pending
|
|
1054
|
+
)
|
|
1055
|
+
res_cap, stat_cap = self.config.max_resident_programs, self.config.static_concurrency_cap
|
|
1056
|
+
|
|
1057
|
+
def try_pick(prog: ProgramState) -> None:
|
|
1058
|
+
nonlocal committed, active_total, active_reasoning
|
|
1059
|
+
if res_cap > 0 and active_total >= res_cap:
|
|
1060
|
+
return
|
|
1061
|
+
if prog.request_pending and stat_cap > 0 and active_reasoning >= stat_cap:
|
|
1062
|
+
return
|
|
1063
|
+
req = self._required_pages(prog)
|
|
1064
|
+
if committed + req > available:
|
|
1065
|
+
return
|
|
1066
|
+
selected.append(prog)
|
|
1067
|
+
selected_ids.add(prog.program_id)
|
|
1068
|
+
committed += req
|
|
1069
|
+
active_total += 1
|
|
1070
|
+
active_reasoning += int(prog.request_pending)
|
|
1071
|
+
|
|
1072
|
+
for p in aged[: self.config.aged_resume_quota_per_tick]:
|
|
1073
|
+
try_pick(p)
|
|
1074
|
+
for p in ordered_others:
|
|
1075
|
+
if p.program_id not in selected_ids and p.program_id not in victims:
|
|
1076
|
+
try_pick(p)
|
|
1077
|
+
return selected
|
|
1078
|
+
|
|
1079
|
+
def _restore_waiting_locked(self, now: float, now_mono: float) -> None:
|
|
1080
|
+
if not self.waiting:
|
|
1081
|
+
return
|
|
1082
|
+
paused = self._paused_programs_locked()
|
|
1083
|
+
aged = sorted(
|
|
1084
|
+
(
|
|
1085
|
+
p
|
|
1086
|
+
for p in paused
|
|
1087
|
+
if p.request_pending
|
|
1088
|
+
and p.wait_started_monotonic is not None
|
|
1089
|
+
and (now_mono - p.wait_started_monotonic) >= self.config.fair_wait_threshold_sec
|
|
1090
|
+
),
|
|
1091
|
+
key=lambda p: (p.wait_started_monotonic or 0.0, p.total_tokens, p.program_id),
|
|
1092
|
+
)
|
|
1093
|
+
victims: set[str] = set()
|
|
1094
|
+
if aged or self._aged_owner_id is not None:
|
|
1095
|
+
victims, blocked = self._service_aged_reservation_locked(aged, now_mono)
|
|
1096
|
+
if blocked:
|
|
1097
|
+
return
|
|
1098
|
+
paused = self._paused_programs_locked()
|
|
1099
|
+
aged = [p for p in aged if p.lifecycle == ProgramLifecycle.PAUSED]
|
|
1100
|
+
|
|
1101
|
+
used = float(self._breakdown_locked(now, decay=True).total_pages)
|
|
1102
|
+
available = self.high_capacity_pages - used
|
|
1103
|
+
min_pages = self.accounting.minimum_program_pages(
|
|
1104
|
+
decode_headroom_tokens=self.config.decode_headroom_tokens
|
|
1105
|
+
)
|
|
1106
|
+
if used >= self.low_capacity_pages or available < min_pages:
|
|
1107
|
+
return
|
|
1108
|
+
|
|
1109
|
+
aged_ids = {p.program_id for p in aged}
|
|
1110
|
+
ordered = self._ordered_restore_tiers_locked(paused, aged_ids, victims)
|
|
1111
|
+
selected = self._select_for_restore_locked(aged, ordered, victims, available)
|
|
1112
|
+
for p in sorted(selected, key=lambda item: item.total_tokens, reverse=True):
|
|
1113
|
+
was_pending, was_aged = p.request_pending, p.program_id in aged_ids
|
|
1114
|
+
self._resume_locked(p)
|
|
1115
|
+
key = (
|
|
1116
|
+
"resumed_aged"
|
|
1117
|
+
if was_aged
|
|
1118
|
+
else ("resumed_normal" if was_pending else "resumed_acting")
|
|
1119
|
+
)
|
|
1120
|
+
self._counters[key] += 1
|
|
1121
|
+
|
|
1122
|
+
def _unmarked_active_locked(self, status: ProgramStatus) -> list[ProgramState]:
|
|
1123
|
+
return sorted(
|
|
1124
|
+
(
|
|
1125
|
+
p
|
|
1126
|
+
for p in self._active_programs_locked()
|
|
1127
|
+
if p.status == status and not p.marked_for_pause
|
|
1128
|
+
),
|
|
1129
|
+
key=lambda p: (p.total_tokens, p.program_id),
|
|
1130
|
+
)
|
|
1131
|
+
|
|
1132
|
+
def _pause_until_safe_locked(self, now_mono: float) -> None:
|
|
1133
|
+
while (
|
|
1134
|
+
sum(
|
|
1135
|
+
self._required_pages(p)
|
|
1136
|
+
for p in self._active_programs_locked()
|
|
1137
|
+
if not p.marked_for_pause
|
|
1138
|
+
)
|
|
1139
|
+
> self.high_capacity_pages
|
|
1140
|
+
):
|
|
1141
|
+
acting = self._unmarked_active_locked(ProgramStatus.ACTING)
|
|
1142
|
+
if acting:
|
|
1143
|
+
self._pause_locked(acting[0], now_mono)
|
|
1144
|
+
self._counters["paused_acting_eviction"] += 1
|
|
1145
|
+
continue
|
|
1146
|
+
reasoning = self._unmarked_active_locked(ProgramStatus.REASONING)
|
|
1147
|
+
if not reasoning:
|
|
1148
|
+
break
|
|
1149
|
+
reasoning[0].marked_for_pause = True
|
|
1150
|
+
self._counters["marked_reasoning"] += 1
|
|
1151
|
+
|
|
1152
|
+
def _loop(self) -> None:
|
|
1153
|
+
while not self._stop_event.wait(self.config.scheduler_interval_sec):
|
|
1154
|
+
self.schedule_once()
|
|
1155
|
+
|
|
1156
|
+
def snapshot(self) -> dict[str, Any]:
|
|
1157
|
+
with self._lock:
|
|
1158
|
+
now = time.time()
|
|
1159
|
+
full = self._breakdown_locked(now, decay=False)
|
|
1160
|
+
decayed = self._breakdown_locked(now, decay=True)
|
|
1161
|
+
waits = sorted(self._wait_samples)
|
|
1162
|
+
p99_wait = waits[int(0.99 * (len(waits) - 1))] if waits else 0.0
|
|
1163
|
+
return {
|
|
1164
|
+
"accounting": self.accounting.contract(),
|
|
1165
|
+
"programs_live": len(self.programs),
|
|
1166
|
+
"active": len(self._active_programs_locked()),
|
|
1167
|
+
"paused": len(self.waiting),
|
|
1168
|
+
"pages_full": full.total_pages,
|
|
1169
|
+
"pages_decayed": decayed.total_pages,
|
|
1170
|
+
"attention_pages_full": full.attention_pages,
|
|
1171
|
+
"resident_state_pages": full.resident_state_pages,
|
|
1172
|
+
"transient_state_pages": full.transient_state_pages,
|
|
1173
|
+
"reasoning_reserved_programs": full.reasoning_reserved_programs,
|
|
1174
|
+
"char_to_token_ratio": round(self.char_to_token_ratio, 4),
|
|
1175
|
+
"wait_samples": len(waits),
|
|
1176
|
+
"p99_wait_sec": round(p99_wait, 6),
|
|
1177
|
+
"peaks": dict(self._peaks),
|
|
1178
|
+
"counters": dict(self._counters),
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
def scheduler_from_options(
|
|
1183
|
+
options: ProgramOptions,
|
|
1184
|
+
*,
|
|
1185
|
+
config: SchedulerConfig | None = None,
|
|
1186
|
+
catalog_path: Path | None = None,
|
|
1187
|
+
) -> ProgramAwareScheduler:
|
|
1188
|
+
"""Build a ready-to-start ``ProgramAwareScheduler`` from resolved ``ProgramOptions``."""
|
|
1189
|
+
accounting = resolve_accounting(
|
|
1190
|
+
options.model_id,
|
|
1191
|
+
window_tokens=options.window_tokens,
|
|
1192
|
+
slots=options.slots,
|
|
1193
|
+
kv_types=(options.kv_k, options.kv_v),
|
|
1194
|
+
prompt_cache_mib=options.prompt_cache_mib,
|
|
1195
|
+
catalog_path=catalog_path,
|
|
1196
|
+
)
|
|
1197
|
+
resolved_config = config or SchedulerConfig(max_resident_programs=options.max_resident_programs)
|
|
1198
|
+
return ProgramAwareScheduler(accounting, resolved_config)
|