tuieval 0.2.0.dev147__py3-none-any.whl → 0.2.0.dev149__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.
- tuieval/_version.py +2 -2
- tuieval/cli.py +1 -0
- tuieval/ctxbench.py +390 -0
- tuieval/engine.py +74 -16
- tuieval/machines.py +17 -0
- tuieval/profiles.py +37 -0
- tuieval/remove.py +3 -0
- tuieval/run_evals.py +57 -9
- {tuieval-0.2.0.dev147.dist-info → tuieval-0.2.0.dev149.dist-info}/METADATA +2 -1
- {tuieval-0.2.0.dev147.dist-info → tuieval-0.2.0.dev149.dist-info}/RECORD +13 -12
- {tuieval-0.2.0.dev147.dist-info → tuieval-0.2.0.dev149.dist-info}/WHEEL +0 -0
- {tuieval-0.2.0.dev147.dist-info → tuieval-0.2.0.dev149.dist-info}/entry_points.txt +0 -0
- {tuieval-0.2.0.dev147.dist-info → tuieval-0.2.0.dev149.dist-info}/licenses/LICENSE +0 -0
tuieval/_version.py
CHANGED
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '0.2.0.
|
|
22
|
-
__version_tuple__ = version_tuple = (0, 2, 0, '
|
|
21
|
+
__version__ = version = '0.2.0.dev149'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 2, 0, 'dev149')
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
tuieval/cli.py
CHANGED
|
@@ -29,6 +29,7 @@ Advanced
|
|
|
29
29
|
tuieval scan list GGUFs in model_dirs that aren't in models.toml yet
|
|
30
30
|
tuieval machines this machine, other recorded machines, and fit and tuning per model
|
|
31
31
|
tuieval tune MODEL find the fastest speed-only server flags for a model on this machine
|
|
32
|
+
tuieval tune MODEL --ctx measure the largest context the model can be served with on this machine
|
|
32
33
|
tuieval export pi MODEL serve a model in the pi coding agent with its tuned flags
|
|
33
34
|
tuieval watch a proxy that shows the reasoning of any app using your server
|
|
34
35
|
tuieval help · --version
|
tuieval/ctxbench.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Find the largest context a model can be served with on this machine, by trying it, and save it
|
|
2
|
+
in tuning/<machine-id>/<label>.ctx.toml. Runs then use it in place of the fit check's estimate.
|
|
3
|
+
|
|
4
|
+
tuieval tune MODEL --ctx [--max N] [--start N] [--step N] [--max-starts N]
|
|
5
|
+
|
|
6
|
+
It works the same for every server tuieval starts, because it only uses what they all have:
|
|
7
|
+
|
|
8
|
+
the context set through {ctx} in the server's cmd, or its ctx_flag
|
|
9
|
+
the API one chat request per try, and the token counts the server reports
|
|
10
|
+
the machine the server's memory (its processes' resident memory; VRAM on discrete GPUs),
|
|
11
|
+
macOS memory pressure and swapping, memory available on Linux
|
|
12
|
+
|
|
13
|
+
One try ("probe") at a context: start the server with it, send a document that fills it (sized
|
|
14
|
+
from the server's own token counts, so any tokenizer works) with one fact near the start, and ask
|
|
15
|
+
for that fact. The probe passes when the answer is right, the server read the whole document (a
|
|
16
|
+
server that cuts long prompts short reports fewer tokens, or loses the fact), and the machine
|
|
17
|
+
stayed healthy. Filling matters: some servers only take memory as the context fills.
|
|
18
|
+
|
|
19
|
+
The search starts small and doubles. Memory grows about linearly with the context, so two probes
|
|
20
|
+
that passed predict the largest context that fits under the machine's limit; no probe goes above
|
|
21
|
+
that prediction, and a failed probe is bisected against the largest that passed. A probe is
|
|
22
|
+
stopped at once when memory pressure rises, the machine starts swapping, or (Linux) memory runs
|
|
23
|
+
out. Typically 3 to 5 server starts.
|
|
24
|
+
|
|
25
|
+
A server tuieval doesn't start, or can't set the context of, is only verified at the context its
|
|
26
|
+
model declares (max_context): one probe, nothing saved.
|
|
27
|
+
"""
|
|
28
|
+
import dataclasses
|
|
29
|
+
import os
|
|
30
|
+
import threading
|
|
31
|
+
|
|
32
|
+
from . import engine as engine_mod
|
|
33
|
+
from . import machines
|
|
34
|
+
from . import profiles
|
|
35
|
+
from . import tune
|
|
36
|
+
|
|
37
|
+
ANSWER_TOKENS = 1024 # room for the answer (and any thinking) in a probe
|
|
38
|
+
STEP = 8192 # how close to the true maximum the search gets
|
|
39
|
+
FLOOR = machines.MIN_CTX # the smallest context tried
|
|
40
|
+
MAX_STARTS = 8
|
|
41
|
+
REQUEST_LIMIT_S = 3600 # reading a few hundred thousand tokens takes a while ([tune] ctx_request_timeout_s)
|
|
42
|
+
PRESSURE_WARNING = 2 # macOS memory pressure level that stops a probe (1 is normal)
|
|
43
|
+
SWAP_STOP_MB = 512 # swapped out while a probe ran: stop it
|
|
44
|
+
AVAILABLE_STOP_GB = 1.0 # Linux: memory available under this stops a probe
|
|
45
|
+
SAMPLE_CHARS = 12000 # the request that measures the server's characters per token
|
|
46
|
+
UNKNOWN_CHARS_PER_TOKEN = 3.0 # for a server that reports no token counts: short of full rather than over
|
|
47
|
+
NOT_ABOUT_CONTEXT = ("already in use", "isn't installed", "not found", "is not set", "skipped by user")
|
|
48
|
+
CODE = 481739 # six digits: no section number or step count in the document can equal it
|
|
49
|
+
WORDS = ("river", "station", "ledger", "orchard", "signal", "harbour", "copper", "meadow", "lantern",
|
|
50
|
+
"quarry", "window", "valley", "engine", "garden", "bridge", "tower")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclasses.dataclass
|
|
54
|
+
class Probe:
|
|
55
|
+
ctx: int
|
|
56
|
+
ok: bool = False
|
|
57
|
+
error: str = ""
|
|
58
|
+
mem_gb: float | None = None # the server's peak memory with the context full
|
|
59
|
+
prompt_tokens: int | None = None # as the server counted them
|
|
60
|
+
pp_tps: float | None = None
|
|
61
|
+
tg_tps: float | None = None
|
|
62
|
+
total_s: float | None = None
|
|
63
|
+
load_s: float | None = None
|
|
64
|
+
filled: bool = False # the server's token count confirms the context was full
|
|
65
|
+
|
|
66
|
+
def summary(self):
|
|
67
|
+
if not self.ok:
|
|
68
|
+
return f"failed: {self.error}"
|
|
69
|
+
parts = ["ok"]
|
|
70
|
+
if self.mem_gb is not None:
|
|
71
|
+
parts.append(f"{self.mem_gb:.1f} GB")
|
|
72
|
+
if self.prompt_tokens:
|
|
73
|
+
parts.append(f"{self.prompt_tokens:,} prompt tokens" + ("" if self.filled else " (fill not confirmed)"))
|
|
74
|
+
if self.pp_tps:
|
|
75
|
+
parts.append(f"prompt {self.pp_tps:.0f} tok/s")
|
|
76
|
+
if self.tg_tps:
|
|
77
|
+
parts.append(f"gen {self.tg_tps:.1f} tok/s")
|
|
78
|
+
return ", ".join(parts)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ------------------------------------------------------------------ the document
|
|
82
|
+
def document(chars):
|
|
83
|
+
"""A ~chars-long synthetic document with one fact near its start and the question at its end
|
|
84
|
+
(the same text every time). A server that drops the start of a long prompt loses the fact."""
|
|
85
|
+
paras, size, i = [], 0, 0
|
|
86
|
+
while size < chars:
|
|
87
|
+
w = [WORDS[(i * 7 + k * 3) % len(WORDS)] for k in range(12)]
|
|
88
|
+
p = (f"Section {i + 1}. The {w[0]} near the {w[1]} kept a {w[2]} of every {w[3]}, and the {w[4]} by the "
|
|
89
|
+
f"{w[5]} was painted {w[6]} after the {w[7]} flooded. Visitors to the {w[8]} counted "
|
|
90
|
+
f"{(i * 37) % 900 + 100} steps to the {w[9]}, past a {w[10]} facing the {w[11]}.")
|
|
91
|
+
paras.append(p)
|
|
92
|
+
size += len(p) + 2
|
|
93
|
+
i += 1
|
|
94
|
+
paras.insert(max(1, len(paras) // 20), f"Note: the archive room code is {CODE}.")
|
|
95
|
+
return "\n\n".join(paras) + "\n\nWhat is the archive room code? Answer with the number only."
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _ask(eng, m, base_url, chars, max_tokens, name, emit, limit):
|
|
99
|
+
sampling = engine_mod.effective_sampling(eng.cfg, m)
|
|
100
|
+
request = eng.cfg["servers"][m["server"]].get("request", {})
|
|
101
|
+
body = tune._body(m, sampling, [{"role": "user", "content": document(chars)}], max_tokens, request)
|
|
102
|
+
body.pop("ignore_eos", None) # the answer should end where the model ends it
|
|
103
|
+
return tune._stream_request(eng, base_url, body, name, emit, limit)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def chars_per_token(eng, m, base_url, emit, limit):
|
|
107
|
+
"""Characters of the document per token, by this server's count (None if it reports none)."""
|
|
108
|
+
from . import client
|
|
109
|
+
res = _ask(eng, m, base_url, SAMPLE_CHARS, 8, "sizing", emit, limit)
|
|
110
|
+
if res.get("error"):
|
|
111
|
+
raise engine_mod.ModelFailed(f"sizing request: {res['error']}")
|
|
112
|
+
tokens = client.metrics(res)["prompt_tokens"]
|
|
113
|
+
return SAMPLE_CHARS / tokens if tokens else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def too_long(error):
|
|
117
|
+
e = (error or "").lower()
|
|
118
|
+
return "http 4" in e and any(w in e for w in ("context", "too long", "too large", "exceed", "maximum"))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Guard:
|
|
122
|
+
"""Watches the machine while a probe runs and stops the request when it gets unhealthy."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, eng, every_s=2.0):
|
|
125
|
+
self.eng, self.every_s, self.reason = eng, every_s, ""
|
|
126
|
+
self.pressure, self._stop = machines.memory_pressure_level(), threading.Event()
|
|
127
|
+
self._swap0 = machines.swapped_out_bytes()
|
|
128
|
+
self._linux = self.pressure is None and not eng.machine().discrete
|
|
129
|
+
|
|
130
|
+
def __enter__(self):
|
|
131
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
132
|
+
self._thread.start()
|
|
133
|
+
return self
|
|
134
|
+
|
|
135
|
+
def check(self):
|
|
136
|
+
lvl = machines.memory_pressure_level()
|
|
137
|
+
if lvl is not None:
|
|
138
|
+
self.pressure = max(self.pressure or 0, lvl)
|
|
139
|
+
if lvl >= PRESSURE_WARNING:
|
|
140
|
+
return f"macOS memory pressure rose to level {lvl}"
|
|
141
|
+
swap = machines.swapped_out_bytes()
|
|
142
|
+
if None not in (swap, self._swap0) and (swap - self._swap0) / 2**20 > SWAP_STOP_MB:
|
|
143
|
+
return f"the machine swapped out {(swap - self._swap0) / 2**20:.0f} MB"
|
|
144
|
+
if self._linux:
|
|
145
|
+
free = machines.available_memory_gb()
|
|
146
|
+
if free is not None and free < AVAILABLE_STOP_GB:
|
|
147
|
+
return f"only {free:.1f} GB of memory was left"
|
|
148
|
+
return ""
|
|
149
|
+
|
|
150
|
+
def _run(self):
|
|
151
|
+
while not self._stop.wait(self.every_s):
|
|
152
|
+
self.reason = self.reason or self.check()
|
|
153
|
+
if self.reason:
|
|
154
|
+
stream = getattr(self.eng, "_stream", None)
|
|
155
|
+
if stream is not None:
|
|
156
|
+
stream.close()
|
|
157
|
+
return
|
|
158
|
+
|
|
159
|
+
def __exit__(self, *exc):
|
|
160
|
+
self._stop.set()
|
|
161
|
+
self._thread.join(self.every_s + 1)
|
|
162
|
+
self.reason = self.reason or self.check()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def probe(eng, m, ctx, emit=lambda *a, **k: None, limit=REQUEST_LIMIT_S):
|
|
166
|
+
"""Serve the model with this context, fill it and ask for the fact. Returns a Probe."""
|
|
167
|
+
from . import client
|
|
168
|
+
out = Probe(ctx)
|
|
169
|
+
reserve = ANSWER_TOKENS + max(256, ctx // 50)
|
|
170
|
+
target = ctx - reserve
|
|
171
|
+
if target < 1024:
|
|
172
|
+
out.error = f"a context of {ctx:,} is too small to test"
|
|
173
|
+
return out
|
|
174
|
+
try:
|
|
175
|
+
with eng.serve(m, log_name=f"{m['label']}.ctx", ctx=ctx) as (url, info):
|
|
176
|
+
out.load_s = round(info["load_s"], 1) if info.get("load_s") else None
|
|
177
|
+
with Guard(eng) as guard:
|
|
178
|
+
ratio = chars_per_token(eng, m, url, emit, limit)
|
|
179
|
+
chars = int(target * (ratio or UNKNOWN_CHARS_PER_TOKEN) * 0.98)
|
|
180
|
+
emit("tune_progress", message=f" filling the context: ~{target:,} tokens, {chars:,} characters"
|
|
181
|
+
+ ("" if ratio else " (the server reports no token counts)"))
|
|
182
|
+
res = _ask(eng, m, url, chars, ANSWER_TOKENS, "fill", emit, limit)
|
|
183
|
+
if too_long(res.get("error")) and not guard.reason:
|
|
184
|
+
emit("tune_progress", message=" the server found that too long; trying 7% shorter")
|
|
185
|
+
res = _ask(eng, m, url, int(chars * 0.93), ANSWER_TOKENS, "fill", emit, limit)
|
|
186
|
+
met = client.metrics(res) if not res.get("error") else {}
|
|
187
|
+
out.prompt_tokens, out.pp_tps, out.tg_tps = met.get("prompt_tokens"), met.get("prompt_tps"), met.get("gen_tps")
|
|
188
|
+
out.total_s = round(res["total_s"], 1) if res.get("total_s") else None
|
|
189
|
+
peak = info.get("vram_peak_gb") if eng.machine().discrete else \
|
|
190
|
+
(info["peak_mb"]() or 0) / 1024 if info.get("peak_mb") else None
|
|
191
|
+
out.mem_gb = round(peak, 2) if peak else None
|
|
192
|
+
text = (res.get("answer") or "") + (res.get("reasoning") or "")
|
|
193
|
+
if guard.reason:
|
|
194
|
+
out.error = guard.reason
|
|
195
|
+
elif res.get("error"):
|
|
196
|
+
out.error = res["error"]
|
|
197
|
+
elif not info["alive"]():
|
|
198
|
+
out.error = "the server stopped"
|
|
199
|
+
elif str(CODE) not in text:
|
|
200
|
+
out.error = "it didn't find a fact near the start of the document (the context isn't all used)"
|
|
201
|
+
elif out.prompt_tokens and out.prompt_tokens < 0.85 * target:
|
|
202
|
+
out.error = (f"the server read {out.prompt_tokens:,} of ~{target:,} tokens "
|
|
203
|
+
"(it cuts long prompts short)")
|
|
204
|
+
else:
|
|
205
|
+
out.ok = True
|
|
206
|
+
out.filled = bool(ratio and out.prompt_tokens and out.prompt_tokens >= 0.85 * target)
|
|
207
|
+
except engine_mod.ModelFailed as e:
|
|
208
|
+
out.error = str(e).splitlines()[0]
|
|
209
|
+
if any(w in out.error for w in NOT_ABOUT_CONTEXT):
|
|
210
|
+
raise # a smaller context wouldn't help
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ------------------------------------------------------------------ the search
|
|
215
|
+
def predict(passed, limit_gb):
|
|
216
|
+
"""(base_gb, gb_per_token, largest context predicted to fit) from the two largest contexts that
|
|
217
|
+
passed with a memory reading. The third is None when memory doesn't grow with the context
|
|
218
|
+
(nothing to predict) or there aren't two readings."""
|
|
219
|
+
pts = sorted((p.ctx, p.mem_gb) for p in passed if p.mem_gb)
|
|
220
|
+
if len(pts) < 2:
|
|
221
|
+
return None, None, None
|
|
222
|
+
(c1, g1), (c2, g2) = pts[-2:]
|
|
223
|
+
per = (g2 - g1) / (c2 - c1)
|
|
224
|
+
base = g2 - per * c2
|
|
225
|
+
if per <= 0 or limit_gb is None:
|
|
226
|
+
return base, max(per, 0.0), None
|
|
227
|
+
return base, per, int((limit_gb - base) / per)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _grid(n):
|
|
231
|
+
return int(n) // 1024 * 1024
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_starts=MAX_STARTS,
|
|
235
|
+
emit=lambda *a, **k: None):
|
|
236
|
+
"""Probe contexts until the largest that works is known to within `step`. try_ctx(ctx) -> Probe.
|
|
237
|
+
Returns (probes in the order tried, why it stopped)."""
|
|
238
|
+
tried, lo, hi, c = [], None, None, min(start, upper)
|
|
239
|
+
why = f"{max_starts} server starts used"
|
|
240
|
+
while len(tried) < max_starts:
|
|
241
|
+
emit("tune_step", message=f"[{len(tried) + 1}] context {c:,}", start=len(tried) + 1, max_starts=max_starts)
|
|
242
|
+
r = try_ctx(c)
|
|
243
|
+
tried.append(r)
|
|
244
|
+
emit("tune_result", message=" " + r.summary(), result=r)
|
|
245
|
+
if r.ok:
|
|
246
|
+
lo = max(lo or 0, c)
|
|
247
|
+
else:
|
|
248
|
+
hi = min(hi or c, c)
|
|
249
|
+
if lo is None: # nothing has worked yet: halve
|
|
250
|
+
c = _grid(hi // 2)
|
|
251
|
+
if c < floor:
|
|
252
|
+
why = f"nothing from {floor:,} up worked"
|
|
253
|
+
break
|
|
254
|
+
continue
|
|
255
|
+
if lo >= upper:
|
|
256
|
+
why = f"reached the upper bound ({upper:,})"
|
|
257
|
+
break
|
|
258
|
+
if hi is not None and hi - lo <= step:
|
|
259
|
+
why = f"{hi:,} failed: {next(p.error for p in tried if p.ctx == hi)}"
|
|
260
|
+
break
|
|
261
|
+
_, per, fit = predict([p for p in tried if p.ok], limit_gb)
|
|
262
|
+
nxt = min(upper, lo * 2) if hi is None else lo + _grid((hi - lo) / 2)
|
|
263
|
+
if fit is not None and fit < nxt:
|
|
264
|
+
if _grid(fit) - lo < min(step, upper - lo):
|
|
265
|
+
at = min(upper, lo + step)
|
|
266
|
+
why = (f"memory: {at:,} is predicted to need more than the {limit_gb:.1f} GB this machine has "
|
|
267
|
+
f"for it ({per * 1000:.3f} GB per 1,000 tokens)")
|
|
268
|
+
break
|
|
269
|
+
nxt = _grid(fit)
|
|
270
|
+
if nxt <= lo:
|
|
271
|
+
why = f"{hi:,} failed: {next(p.error for p in tried if p.ctx == hi)}" if hi else why
|
|
272
|
+
break
|
|
273
|
+
c = nxt
|
|
274
|
+
return tried, why
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ------------------------------------------------------------------ driver
|
|
278
|
+
def model_gb(m):
|
|
279
|
+
"""The model's size on disk (a file with its other shards beside it, or a folder), or None."""
|
|
280
|
+
path = engine_mod.expand(str(m.get("model", "")))
|
|
281
|
+
try:
|
|
282
|
+
if os.path.isfile(path):
|
|
283
|
+
return os.path.getsize(path) / machines.GB
|
|
284
|
+
if os.path.isdir(path):
|
|
285
|
+
return sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(path) for f in fs) / machines.GB
|
|
286
|
+
except OSError:
|
|
287
|
+
pass
|
|
288
|
+
return None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def room_gb(eng):
|
|
292
|
+
"""(memory this machine has for a model now, a reason not to load one at all or "")."""
|
|
293
|
+
mc = eng.machine()
|
|
294
|
+
headroom = eng.headroom_gb(mc)
|
|
295
|
+
if mc.discrete:
|
|
296
|
+
used = machines.vram_used_gb()
|
|
297
|
+
return mc.gpu_limit_gb - (used or 0) - headroom, ""
|
|
298
|
+
level = machines.memory_pressure_level()
|
|
299
|
+
if level is not None and level > 1:
|
|
300
|
+
return None, f"macOS memory pressure is already elevated (level {level}); close other apps or models first"
|
|
301
|
+
free = machines.available_memory_gb()
|
|
302
|
+
limit = mc.gpu_limit_gb - headroom
|
|
303
|
+
return (limit if free is None else min(limit, free - headroom)), ""
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def upper_bound(eng, m, server, how, asked=None):
|
|
307
|
+
"""(the largest context worth trying, where that number comes from)."""
|
|
308
|
+
if asked:
|
|
309
|
+
return asked, "--max"
|
|
310
|
+
caps = [(server.get("max_ctx"), f"max_ctx in [servers.{m['server']}]"), (m.get("ctx"), "the model's ctx"),
|
|
311
|
+
(m.get("max_context"), "the model's max_context")]
|
|
312
|
+
caps = [(v, src) for v, src in caps if v]
|
|
313
|
+
if how == "flag":
|
|
314
|
+
sv = eng.serving(m)
|
|
315
|
+
written = engine_mod.read_context(list(m.get("server_args", [])) + list(sv.perf_args), server["ctx_flag"])
|
|
316
|
+
if written:
|
|
317
|
+
caps.append((written, f"{server['ctx_flag']} in models.toml"))
|
|
318
|
+
if caps:
|
|
319
|
+
return min(caps)
|
|
320
|
+
path = engine_mod.expand(str(m.get("model", "")))
|
|
321
|
+
if os.path.isfile(path):
|
|
322
|
+
try:
|
|
323
|
+
n = machines.read_gguf(path).get("context_length")
|
|
324
|
+
if n:
|
|
325
|
+
return n, "the model file"
|
|
326
|
+
except (OSError, ValueError):
|
|
327
|
+
pass
|
|
328
|
+
raise engine_mod.ModelFailed("no upper bound for its context is known: pass --max N (the model's own limit)")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=STEP, max_starts=MAX_STARTS):
|
|
332
|
+
"""Measure the largest context one model can be served with here and save it. Returns the saved
|
|
333
|
+
measurement, or {"verified": bool, ...} for a server whose context tuieval can't set."""
|
|
334
|
+
m = eng.model(label)
|
|
335
|
+
server = eng.cfg["servers"][m["server"]]
|
|
336
|
+
if eng.hosted(m):
|
|
337
|
+
raise engine_mod.ModelFailed("it's a hosted model: its context doesn't depend on this machine")
|
|
338
|
+
how = engine_mod.takes_context(server)
|
|
339
|
+
limit_s = eng.cfg.get("tune", {}).get("ctx_request_timeout_s", REQUEST_LIMIT_S)
|
|
340
|
+
sv = eng.serving(m)
|
|
341
|
+
if not how:
|
|
342
|
+
ctx = m.get("max_context") or sv.ctx
|
|
343
|
+
if not ctx:
|
|
344
|
+
raise engine_mod.ModelFailed("tuieval can't set this server's context ({ctx} in its cmd, or ctx_flag), and "
|
|
345
|
+
"the model has no max_context to verify")
|
|
346
|
+
emit("tune_step", message=f"tuieval can't set this server's context: checking the {ctx:,} it declares")
|
|
347
|
+
r = probe(eng, m, ctx, emit, limit_s)
|
|
348
|
+
emit("tune_result", message=" " + r.summary(), result=r)
|
|
349
|
+
return {"verified": r.ok, "ctx": ctx, "probe": r}
|
|
350
|
+
upper, source = upper_bound(eng, m, server, how, max_ctx)
|
|
351
|
+
upper = max(upper, FLOOR)
|
|
352
|
+
room, refuse = room_gb(eng)
|
|
353
|
+
if refuse:
|
|
354
|
+
raise engine_mod.ModelFailed(refuse)
|
|
355
|
+
size = model_gb(m)
|
|
356
|
+
if room is not None and size is not None and size > room:
|
|
357
|
+
raise engine_mod.ModelFailed(f"the model is {size:.1f} GB and {room:.1f} GB is free for it now: another "
|
|
358
|
+
"model or app is holding memory")
|
|
359
|
+
first = min(upper, max(FLOOR, _grid(start or upper // 4)))
|
|
360
|
+
emit("tune_step", message=f"largest context up to {upper:,} ({source})"
|
|
361
|
+
+ (f"; {room:.1f} GB of memory to work with" if room is not None else ""))
|
|
362
|
+
|
|
363
|
+
def try_ctx(ctx):
|
|
364
|
+
eng._check()
|
|
365
|
+
return probe(eng, m, ctx, emit, limit_s)
|
|
366
|
+
|
|
367
|
+
tried, why = search(try_ctx, first, upper, room, step, min(FLOOR, first), max_starts, emit)
|
|
368
|
+
passed = [p for p in tried if p.ok]
|
|
369
|
+
if not passed:
|
|
370
|
+
raise engine_mod.ModelFailed(f"no context worked ({why}); the last try: {tried[-1].error}")
|
|
371
|
+
best = max(passed, key=lambda p: p.ctx)
|
|
372
|
+
base, per, _ = predict(passed, room)
|
|
373
|
+
measured = {
|
|
374
|
+
"max_ctx": best.ctx,
|
|
375
|
+
"measured": {"memory_gb": best.mem_gb, "base_gb": round(base, 2) if base is not None else None,
|
|
376
|
+
"gb_per_1k_tokens": round(per * 1000, 4) if per is not None else None,
|
|
377
|
+
"prompt_tokens": best.prompt_tokens, "prompt_tps": best.pp_tps, "gen_tps": best.tg_tps,
|
|
378
|
+
"fill_s": best.total_s, "load_s": best.load_s, "limit_gb": round(room, 1) if room is not None else None,
|
|
379
|
+
"stopped": why},
|
|
380
|
+
"probes": {str(p.ctx): p.summary() for p in tried},
|
|
381
|
+
"meta": {"date": profiles.now(), "machine": sv.machine.summary, "server_version": eng.server_version(m),
|
|
382
|
+
"model_file": os.path.basename(str(m.get("model", ""))), "model_bytes": sv.identity.get("model_bytes"),
|
|
383
|
+
"kv_type": sv.kv_type, "upper_bound": upper, "upper_bound_from": source,
|
|
384
|
+
"fill_confirmed": best.filled, "server_starts": len(tried)},
|
|
385
|
+
}
|
|
386
|
+
path = profiles.save_context(sv.machine.id, label, measured, eng.tuning_dir)
|
|
387
|
+
eng._serving.clear()
|
|
388
|
+
shown = os.path.relpath(path, eng.root) if path.startswith(eng.root) else path
|
|
389
|
+
emit("tune_done", message=f"saved {shown}", profile=measured, path=path)
|
|
390
|
+
return measured
|
tuieval/engine.py
CHANGED
|
@@ -162,6 +162,43 @@ def effective_sampling(cfg, m):
|
|
|
162
162
|
CONTEXT_FLAGS = {"--max-context", "--max-context-tokens", "--ctx-size", "-c", "--context-length", "--max-model-len"}
|
|
163
163
|
|
|
164
164
|
|
|
165
|
+
def read_context(args, flag):
|
|
166
|
+
"""The context a command line sets with the server's context flag ("--flag N" or "--flag=N"), or None."""
|
|
167
|
+
args = [str(a) for a in args]
|
|
168
|
+
for i, a in enumerate(args):
|
|
169
|
+
value = args[i + 1] if a == flag and i + 1 < len(args) else a[len(flag) + 1:] if a.startswith(flag + "=") else ""
|
|
170
|
+
if value.isdigit():
|
|
171
|
+
return int(value)
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def set_context(args, flag, ctx):
|
|
176
|
+
"""The command line with the server's context flag set to ctx: its value replaced where the flag
|
|
177
|
+
is there ("--flag N" or "--flag=N"), the flag added where it isn't."""
|
|
178
|
+
out, i, done = [], 0, False
|
|
179
|
+
while i < len(args):
|
|
180
|
+
a = str(args[i])
|
|
181
|
+
if a == flag and i + 1 < len(args):
|
|
182
|
+
out += [a, str(ctx)]
|
|
183
|
+
i, done = i + 2, True
|
|
184
|
+
continue
|
|
185
|
+
if a.startswith(flag + "="):
|
|
186
|
+
a, done = f"{flag}={ctx}", True
|
|
187
|
+
out.append(a)
|
|
188
|
+
i += 1
|
|
189
|
+
return out if done else out + [flag, str(ctx)]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def takes_context(server):
|
|
193
|
+
"""How tuieval can set this server's context: "placeholder" ({ctx} in its cmd), "flag" (its
|
|
194
|
+
ctx_flag), or "" when it can't (a server it doesn't start, or one with neither)."""
|
|
195
|
+
if not server.get("cmd"):
|
|
196
|
+
return ""
|
|
197
|
+
if any("{ctx}" in str(a) for a in server["cmd"]):
|
|
198
|
+
return "placeholder"
|
|
199
|
+
return "flag" if server.get("ctx_flag") else ""
|
|
200
|
+
|
|
201
|
+
|
|
165
202
|
def strip_context(args):
|
|
166
203
|
"""A command line without its context-size flags (and their values)."""
|
|
167
204
|
out, skip = [], False
|
|
@@ -254,6 +291,9 @@ class Serving:
|
|
|
254
291
|
profile: dict | None = None
|
|
255
292
|
mtp_layers: int = 0
|
|
256
293
|
need_gb: float | None = None # estimated GPU memory at ctx (from the fit check); None when unknown
|
|
294
|
+
ctx_source: str = "" # "measured" when ctx comes from tuieval tune --ctx on this machine
|
|
295
|
+
ctx_measured: dict | None = None # that measurement (profiles.load_context), also when it's out of date
|
|
296
|
+
ctx_note: str = "" # why a measurement isn't used
|
|
257
297
|
|
|
258
298
|
|
|
259
299
|
def infer_server(cfg, model):
|
|
@@ -1420,33 +1460,46 @@ class Engine:
|
|
|
1420
1460
|
ctx, fits, note, need = f.max_ctx, f.fits, f.note, f.need_gb
|
|
1421
1461
|
except (OSError, ValueError) as e:
|
|
1422
1462
|
note = f"couldn't read the GGUF header ({e}); context not checked"
|
|
1423
|
-
profile, perf,
|
|
1463
|
+
profile, perf, perf_source = None, [], "n/a"
|
|
1424
1464
|
if server.get("cmd") and (server.get("perf") or server.get("tune")):
|
|
1425
1465
|
perf = list(server.get("perf", []))
|
|
1426
1466
|
profile = profiles.load(mc.id, m["label"], self.tuning_dir)
|
|
1427
1467
|
if profile:
|
|
1428
1468
|
perf += list(profile["args"])
|
|
1429
1469
|
why = profiles.stale(profile, self.server_version(m), size)
|
|
1430
|
-
|
|
1470
|
+
perf_source = f"outdated: {why}" if why else \
|
|
1431
1471
|
("seeded" if profile.get("meta", {}).get("method") == "seeded" else "tuned")
|
|
1432
1472
|
else:
|
|
1433
1473
|
perf += self.default_knob_args(server, mc)
|
|
1434
|
-
|
|
1474
|
+
perf_source = "untuned"
|
|
1435
1475
|
flag = server.get("ctx_flag") # e.g. --max-context-tokens, when the server takes one
|
|
1436
1476
|
if flag and ctx is None:
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1477
|
+
ctx = read_context(list(m.get("server_args", [])) + perf, flag)
|
|
1478
|
+
# The largest context measured here (tuieval tune --ctx) replaces the estimate. Your own caps
|
|
1479
|
+
# (max_ctx, ctx, max_context, a context flag you wrote) still apply.
|
|
1480
|
+
how, source, ctx_note = takes_context(server), "", ""
|
|
1481
|
+
measured = profiles.load_context(mc.id, m["label"], self.tuning_dir) if how else None
|
|
1482
|
+
if measured:
|
|
1483
|
+
meta = measured.get("meta", {})
|
|
1484
|
+
if meta.get("model_bytes") and size and meta["model_bytes"] != size:
|
|
1485
|
+
ctx_note = "the model file changed since its context was measured; run tuieval tune --ctx again"
|
|
1486
|
+
elif meta.get("kv_type") and kv and meta["kv_type"] != kv:
|
|
1487
|
+
ctx_note = f"its context was measured with {meta['kv_type']} KV, not {kv}; run tuieval tune --ctx again"
|
|
1488
|
+
else:
|
|
1489
|
+
cap = want if how == "placeholder" else ctx
|
|
1490
|
+
ctx, fits, source = min(cap, measured["max_ctx"]) if cap else measured["max_ctx"], True, "measured"
|
|
1491
|
+
note = f"measured on {mc.id}: up to {measured['max_ctx'] // 1024}k context"
|
|
1492
|
+
at = measured.get("measured", {})
|
|
1493
|
+
if at.get("base_gb") is not None and at.get("gb_per_1k_tokens") is not None:
|
|
1494
|
+
need = round(at["base_gb"] + at["gb_per_1k_tokens"] * ctx / 1000, 1)
|
|
1443
1495
|
identity = self._identity(m, server, kv, size)
|
|
1444
1496
|
if server.get("outputs_depend_on_machine"):
|
|
1445
1497
|
# Answers depend on the machine and on its memory settings (e.g. which experts stay
|
|
1446
1498
|
# resident), so both are part of what a result is valid for.
|
|
1447
1499
|
identity["machine"] = mc.id
|
|
1448
1500
|
identity["perf"] = perf
|
|
1449
|
-
sv = Serving(mc, ctx, kv, fits, note, perf,
|
|
1501
|
+
sv = Serving(mc, ctx, kv, fits, note, perf, perf_source, identity, profile, mtp, need,
|
|
1502
|
+
ctx_source=source, ctx_measured=measured, ctx_note=ctx_note)
|
|
1450
1503
|
self._serving[key] = sv
|
|
1451
1504
|
return sv
|
|
1452
1505
|
|
|
@@ -1477,22 +1530,26 @@ class Engine:
|
|
|
1477
1530
|
out["agent"] = agents.identity(self.cfg, pack)
|
|
1478
1531
|
return out
|
|
1479
1532
|
|
|
1480
|
-
def server_command(self, m, perf_args=None, port=None):
|
|
1533
|
+
def server_command(self, m, perf_args=None, port=None, ctx=None):
|
|
1481
1534
|
"""(cmd or None, cwd, base_url) for a model. cmd is None for an already-running server.
|
|
1482
|
-
perf_args replaces the speed flags (the tuner uses this); port overrides the server's
|
|
1535
|
+
perf_args replaces the speed flags (the tuner uses this); port overrides the server's; ctx
|
|
1536
|
+
the context (tuieval tune --ctx tries several)."""
|
|
1483
1537
|
server = self.cfg["servers"][m["server"]]
|
|
1484
1538
|
if not server.get("cmd"):
|
|
1485
1539
|
return None, None, server["url"].rstrip("/").removesuffix("/v1")
|
|
1486
1540
|
sv = self.serving(m)
|
|
1487
1541
|
port = port or server["port"]
|
|
1488
1542
|
values = {"model": expand(m["model"]), "served_name": m["served_name"], "port": port,
|
|
1489
|
-
"mmproj": expand(m.get("mmproj", "")), "ctx": sv.ctx or "", "kv_type": sv.kv_type or "",
|
|
1543
|
+
"mmproj": expand(m.get("mmproj", "")), "ctx": ctx or sv.ctx or "", "kv_type": sv.kv_type or "",
|
|
1490
1544
|
"root": self.root, **self.knob_values(sv.machine)}
|
|
1491
1545
|
cmd = [expand(a, **values) for a in server["cmd"]]
|
|
1492
1546
|
cmd += [expand(a, **values) for a in (sv.perf_args if perf_args is None else perf_args)]
|
|
1493
1547
|
if m.get("mmproj"):
|
|
1494
1548
|
cmd += [expand(a, **values) for a in server.get("vision_args", [])]
|
|
1495
1549
|
cmd += [expand(a, **values) for a in m.get("server_args", [])]
|
|
1550
|
+
use = ctx or (sv.ctx if sv.ctx_source == "measured" else None)
|
|
1551
|
+
if use and takes_context(server) == "flag":
|
|
1552
|
+
cmd = set_context(cmd, server["ctx_flag"], use)
|
|
1496
1553
|
cmd, env = split_env(cmd)
|
|
1497
1554
|
env = [f"{k}={expand(str(v), **values)}" for k, v in server.get("env", {}).items()] + env
|
|
1498
1555
|
if env: # env(1) keeps the command one copy-pasteable line and one process group
|
|
@@ -1970,12 +2027,13 @@ class Engine:
|
|
|
1970
2027
|
return free
|
|
1971
2028
|
|
|
1972
2029
|
@contextlib.contextmanager
|
|
1973
|
-
def serve(self, m, perf_args=None, port=None, log_name=None):
|
|
2030
|
+
def serve(self, m, perf_args=None, port=None, log_name=None, ctx=None):
|
|
1974
2031
|
"""Start a model's server (or use the running one), wait until it serves the expected name,
|
|
1975
|
-
yield (base_url, info), and stop it afterwards. info: load_s, command, alive(), peak_mb().
|
|
2032
|
+
yield (base_url, info), and stop it afterwards. info: load_s, command, alive(), peak_mb().
|
|
2033
|
+
ctx: serve with this context instead of the model's usual one."""
|
|
1976
2034
|
defaults = self.cfg["defaults"]
|
|
1977
2035
|
server = self.cfg["servers"][m["server"]]
|
|
1978
|
-
cmd, cwd, base_url = self.server_command(m, perf_args=perf_args, port=port)
|
|
2036
|
+
cmd, cwd, base_url = self.server_command(m, perf_args=perf_args, port=port, ctx=ctx)
|
|
1979
2037
|
port = port or server.get("port")
|
|
1980
2038
|
srv, stop, peak = None, threading.Event(), [0.0]
|
|
1981
2039
|
info = {"load_s": None, "command": cmd, "alive": lambda: srv is None or srv.poll() is None,
|
tuieval/machines.py
CHANGED
|
@@ -356,6 +356,23 @@ def swapped_out_bytes():
|
|
|
356
356
|
return int(page.group(1)) * int(swaps.group(1)) if page and swaps else None
|
|
357
357
|
|
|
358
358
|
|
|
359
|
+
def available_memory_gb():
|
|
360
|
+
"""Memory a new process could take now without pushing anything to swap: free plus what the
|
|
361
|
+
system gives back on demand (file cache). macOS: `memory_pressure`'s free percentage of RAM;
|
|
362
|
+
Linux: MemAvailable. None where unknown."""
|
|
363
|
+
try:
|
|
364
|
+
if platform.system() == "Darwin":
|
|
365
|
+
out = subprocess.run(["memory_pressure"], capture_output=True, text=True, timeout=10).stdout
|
|
366
|
+
pct = re.search(r"free percentage:\s*(\d+)%", out)
|
|
367
|
+
ram = int(_sysctl("hw.memsize") or 0)
|
|
368
|
+
return int(pct.group(1)) / 100 * ram / GB if pct and ram else None
|
|
369
|
+
with open("/proc/meminfo") as f:
|
|
370
|
+
kb = re.search(r"MemAvailable:\s+(\d+) kB", f.read())
|
|
371
|
+
return int(kb.group(1)) * 1024 / GB if kb else None
|
|
372
|
+
except (OSError, subprocess.TimeoutExpired, ValueError):
|
|
373
|
+
return None
|
|
374
|
+
|
|
375
|
+
|
|
359
376
|
# ---------------------------------------------------------------- GPU residency
|
|
360
377
|
# On Apple Silicon Macs, once the system's GPU allocations exceed about half of RAM, the GPU driver evicts and re-maps memory on every command submission (70-95% of the
|
|
361
378
|
# server's CPU in the kernel, GPU idle), whatever iogpu.wired_limit_mb says. Servers that submit
|
tuieval/profiles.py
CHANGED
|
@@ -65,6 +65,43 @@ def now():
|
|
|
65
65
|
return datetime.datetime.now().isoformat(timespec="seconds")
|
|
66
66
|
|
|
67
67
|
|
|
68
|
+
# ---------------------------------------------------------------- measured context
|
|
69
|
+
def context_path(machine_id, label, root=None):
|
|
70
|
+
return os.path.join(root or workspace.path("tuning"), machine_id, f"{label}.ctx.toml")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_context(machine_id, label, root=None):
|
|
74
|
+
"""The largest context measured for a model on a machine (tuieval tune --ctx), or None."""
|
|
75
|
+
p = context_path(machine_id, label, root)
|
|
76
|
+
if not os.path.isfile(p):
|
|
77
|
+
return None
|
|
78
|
+
try:
|
|
79
|
+
with open(p, "rb") as f:
|
|
80
|
+
d = tomllib.load(f)
|
|
81
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
82
|
+
return None
|
|
83
|
+
ok = isinstance(d.get("max_ctx"), int) and not isinstance(d.get("max_ctx"), bool) and d["max_ctx"] > 0
|
|
84
|
+
return d if ok else None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def save_context(machine_id, label, measured, root=None):
|
|
88
|
+
"""Write a measurement: {"max_ctx": n, "measured": {...}, "probes": {...}, "meta": {...}}."""
|
|
89
|
+
p = context_path(machine_id, label, root)
|
|
90
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
91
|
+
lines = [f"# Largest context measured for {label} on {machine_id}. Written by tuieval tune --ctx; runs use it",
|
|
92
|
+
"# in place of the estimate. Delete this file to go back to the estimate.",
|
|
93
|
+
f"max_ctx = {int(measured['max_ctx'])}", ""]
|
|
94
|
+
for section in ("measured", "probes", "meta"):
|
|
95
|
+
lines.append(f"[{section}]")
|
|
96
|
+
for k, v in measured.get(section, {}).items():
|
|
97
|
+
if v is not None:
|
|
98
|
+
lines.append(f"{json.dumps(str(k)) if section == 'probes' else k} = {_toml_value(v)}")
|
|
99
|
+
lines.append("")
|
|
100
|
+
with open(p, "w") as f:
|
|
101
|
+
f.write("\n".join(lines))
|
|
102
|
+
return p
|
|
103
|
+
|
|
104
|
+
|
|
68
105
|
# ---------------------------------------------------------------- known machines
|
|
69
106
|
def save_machine(machine, root=None):
|
|
70
107
|
"""Record a machine's facts (tuning/<id>/machine.toml) so the others can check fit for it."""
|
tuieval/remove.py
CHANGED
|
@@ -78,6 +78,9 @@ def plan(eng, label):
|
|
|
78
78
|
f = profiles.path(machine, label, eng.tuning_dir)
|
|
79
79
|
if os.path.isfile(f):
|
|
80
80
|
p.moves.append((f, os.path.join("tuning", machine, label + ".toml")))
|
|
81
|
+
f = profiles.context_path(machine, label, eng.tuning_dir)
|
|
82
|
+
if os.path.isfile(f):
|
|
83
|
+
p.moves.append((f, os.path.join("tuning", machine, label + ".ctx.toml")))
|
|
81
84
|
with open(eng.models_path) as f:
|
|
82
85
|
old = f.read()
|
|
83
86
|
new = without_block(old, label)
|
tuieval/run_evals.py
CHANGED
|
@@ -616,21 +616,49 @@ def cmd_machines(argv):
|
|
|
616
616
|
f"~{e.gpu_residency_gb(mc):.0f} GB resident{RESET}")
|
|
617
617
|
for m in e.cfg["models"]:
|
|
618
618
|
sv = e.serving(m, mc)
|
|
619
|
-
if sv.perf_source == "n/a":
|
|
619
|
+
if sv.perf_source == "n/a" and sv.ctx_source != "measured":
|
|
620
620
|
print(f" {m['label']:24s} {DIM}{m['server']} picks its own context and speed settings{RESET}")
|
|
621
|
+
if sv.ctx_note:
|
|
622
|
+
print(f" {'':24s} {DIM}{sv.ctx_note}{RESET}")
|
|
621
623
|
continue
|
|
622
624
|
fit = f"{RED}doesn't fit{RESET}" if not sv.fits else (f"ctx {sv.ctx // 1024}k" if sv.ctx else "ctx default")
|
|
623
|
-
|
|
624
|
-
|
|
625
|
+
if sv.fits and sv.ctx_source == "measured":
|
|
626
|
+
fit += " measured"
|
|
627
|
+
src = {"tuned": GREEN + "tuned" + RESET, "seeded": "seeded (hand-tuned flags)",
|
|
628
|
+
"n/a": f"{DIM}no speed flags to tune{RESET}"}.get(sv.perf_source, f"{DIM}{sv.perf_source}{RESET}")
|
|
625
629
|
speed = (sv.profile or {}).get("measured", {})
|
|
626
630
|
sp = f" gen {speed['tg_tps']} tok/s, prompt {speed['pp_tps']} tok/s" if speed.get("tg_tps") else ""
|
|
627
631
|
print(f" {m['label']:24s} {fit:12s} {src}{sp}")
|
|
628
632
|
if not sv.fits:
|
|
629
633
|
print(f" {'':24s} {DIM}{sv.fit_note}{RESET}")
|
|
634
|
+
if sv.ctx_note:
|
|
635
|
+
print(f" {'':24s} {DIM}{sv.ctx_note}{RESET}")
|
|
630
636
|
print(f"\n{DIM}Machines appear here after tuieval has run on them once (tuning/<id>/machine.toml; sync the"
|
|
631
637
|
f" workspace to share it). Set EVALS_MACHINE to rename this one.{RESET}")
|
|
632
638
|
|
|
633
639
|
|
|
640
|
+
def context_report(e, label, got):
|
|
641
|
+
"""Print what tuieval tune --ctx found for a model. False if a declared context didn't hold."""
|
|
642
|
+
if "verified" in got:
|
|
643
|
+
if got["verified"]:
|
|
644
|
+
say(f"{label}: the {got['ctx']:,} context it declares works ({got['probe'].summary()})", GREEN)
|
|
645
|
+
else:
|
|
646
|
+
say(f"{label}: the {got['ctx']:,} context it declares doesn't work: {got['probe'].error}", RED)
|
|
647
|
+
return got["verified"]
|
|
648
|
+
at, sv = got["measured"], e.serving(e.model(label))
|
|
649
|
+
mem = f", {at['memory_gb']:.1f} GB with it full" if at.get("memory_gb") else ""
|
|
650
|
+
per = f", {at['gb_per_1k_tokens']} GB per 1,000 tokens" if at.get("gb_per_1k_tokens") else ""
|
|
651
|
+
say(f"{label}: largest context {got['max_ctx']:,}{mem}{per}", GREEN)
|
|
652
|
+
say(f"{label}: stopped there because: {at['stopped']}")
|
|
653
|
+
if not got["meta"].get("fill_confirmed"):
|
|
654
|
+
say(f"{label}: the server reports no token counts, so how full the context was isn't confirmed", YELLOW)
|
|
655
|
+
if sv.ctx and sv.ctx < got["max_ctx"]:
|
|
656
|
+
say(f"{label}: runs use {sv.ctx:,}, the cap set in models.toml")
|
|
657
|
+
elif sv.ctx_source == "measured":
|
|
658
|
+
say(f"{label}: runs use {sv.ctx:,} from now on")
|
|
659
|
+
return True
|
|
660
|
+
|
|
661
|
+
|
|
634
662
|
class TunePrinter:
|
|
635
663
|
"""Everything the tuner does, as it happens: server start and its log, each request's
|
|
636
664
|
progress, each candidate's result."""
|
|
@@ -665,17 +693,29 @@ def cmd_tune(argv):
|
|
|
665
693
|
"same architecture is already tuned here (its flags are the starting point).")
|
|
666
694
|
p.add_argument("labels", nargs="*", help="models to tune")
|
|
667
695
|
p.add_argument("--untuned", action="store_true", help="every local model without a current profile here")
|
|
668
|
-
p.add_argument("--max-starts", type=int, default=
|
|
696
|
+
p.add_argument("--max-starts", type=int, default=None, help="server starts per model (default 16; 8 with --ctx)")
|
|
669
697
|
p.add_argument("--no-bench", action="store_true", help="skip llama-bench even if it is installed")
|
|
670
698
|
p.add_argument("--export-pi", action="store_true",
|
|
671
699
|
help="after tuning, export each model's serving settings to the pi coding agent (asks first)")
|
|
672
700
|
p.add_argument("--cold", action="store_true",
|
|
673
701
|
help="tune every knob from the defaults, even if a model of the same architecture is tuned here")
|
|
702
|
+
p.add_argument("--ctx", action="store_true",
|
|
703
|
+
help="instead of speed flags, measure the largest context each model can be served with on this "
|
|
704
|
+
"machine (ctxbench.py): a few server starts, each filling the context it tries. Runs then "
|
|
705
|
+
"use it in place of the estimate")
|
|
706
|
+
p.add_argument("--max", type=int, default=None, metavar="N",
|
|
707
|
+
help="with --ctx: the largest context to try (default: the model's or server's own cap)")
|
|
708
|
+
p.add_argument("--start", type=int, default=None, metavar="N",
|
|
709
|
+
help="with --ctx: the first context to try (default: a quarter of the largest)")
|
|
710
|
+
p.add_argument("--step", type=int, default=None, metavar="N",
|
|
711
|
+
help="with --ctx: how close to the true maximum to get (default 8192)")
|
|
674
712
|
p.add_argument("--models", default=None, help="default: the workspace's models.toml")
|
|
675
713
|
a = p.parse_args(argv)
|
|
676
|
-
from . import tune
|
|
714
|
+
from . import ctxbench, tune
|
|
677
715
|
e = engine.Engine(TunePrinter(), models_path=a.models)
|
|
678
716
|
labels = a.labels
|
|
717
|
+
if a.ctx and a.untuned:
|
|
718
|
+
sys.exit("--ctx needs the models named")
|
|
679
719
|
if a.untuned:
|
|
680
720
|
labels += [m["label"] for m in e.cfg["models"] if m["label"] not in labels
|
|
681
721
|
and e.cfg["servers"][m["server"]].get("cmd") and e.serving(m).perf_source not in ("tuned",)]
|
|
@@ -683,10 +723,10 @@ def cmd_tune(argv):
|
|
|
683
723
|
if bad or not labels:
|
|
684
724
|
sys.exit(f"unknown model(s) {bad}; see tuieval list" if bad else "name models to tune, or --untuned")
|
|
685
725
|
signal.signal(signal.SIGINT, lambda *_: (say("stopping…", RED), e.cancel()))
|
|
686
|
-
say(f"tuning on {e.machine().id}: {e.machine().summary}")
|
|
726
|
+
say(f"{'measuring context' if a.ctx else 'tuning'} on {e.machine().id}: {e.machine().summary}")
|
|
687
727
|
failed = 0
|
|
688
728
|
try:
|
|
689
|
-
lock = e.machine_lock(f"tune: {', '.join(labels)}")
|
|
729
|
+
lock = e.machine_lock(f"{'context' if a.ctx else 'tune'}: {', '.join(labels)}")
|
|
690
730
|
lock.__enter__() # held until this process exits
|
|
691
731
|
except engine.Cancelled:
|
|
692
732
|
sys.exit(1)
|
|
@@ -696,7 +736,12 @@ def cmd_tune(argv):
|
|
|
696
736
|
|
|
697
737
|
def work(label=label, result=result):
|
|
698
738
|
try:
|
|
699
|
-
|
|
739
|
+
if a.ctx:
|
|
740
|
+
result["context"] = ctxbench.bench(
|
|
741
|
+
e, label, e.on_event, max_ctx=a.max, start=a.start, step=a.step or ctxbench.STEP,
|
|
742
|
+
max_starts=a.max_starts or ctxbench.MAX_STARTS)
|
|
743
|
+
return
|
|
744
|
+
result["profile"] = tune.tune(e, label, e.on_event, max_starts=a.max_starts or 16, use_bench=not a.no_bench,
|
|
700
745
|
warm=not a.cold)
|
|
701
746
|
except (engine.ModelFailed, engine.Cancelled) as ex:
|
|
702
747
|
result["error"] = str(ex) or "cancelled"
|
|
@@ -706,10 +751,13 @@ def cmd_tune(argv):
|
|
|
706
751
|
t.join(0.5)
|
|
707
752
|
if "error" in result:
|
|
708
753
|
failed += 1
|
|
709
|
-
say(f"{label}: not tuned: {result['error']}", RED)
|
|
754
|
+
say(f"{label}: not {'measured' if a.ctx else 'tuned'}: {result['error']}", RED)
|
|
710
755
|
if e._cancel.is_set():
|
|
711
756
|
break
|
|
712
757
|
continue
|
|
758
|
+
if a.ctx:
|
|
759
|
+
failed += not context_report(e, label, result["context"])
|
|
760
|
+
continue
|
|
713
761
|
pr = result["profile"]
|
|
714
762
|
ms = pr["measured"]
|
|
715
763
|
gain = ", " + tune.gain_text(ms) if tune.gain_text(ms) else ""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: tuieval
|
|
3
|
-
Version: 0.2.0.
|
|
3
|
+
Version: 0.2.0.dev149
|
|
4
4
|
Summary: Evaluate local and frontier LLMs on your own questions: accuracy, speed, tokens and PASS/FAIL verdicts, in the terminal.
|
|
5
5
|
Project-URL: Homepage, https://github.com/ashe-wb/tuieval
|
|
6
6
|
Project-URL: Issues, https://github.com/ashe-wb/tuieval/issues
|
|
@@ -173,6 +173,7 @@ tuieval regrade # re-score stored answers after ch
|
|
|
173
173
|
tuieval regrade --only <model> --packs X # just one model's results (and packs)
|
|
174
174
|
tuieval machines # this machine and others, fit and tuning per model
|
|
175
175
|
tuieval tune <model> # fastest speed flags for a model on this machine
|
|
176
|
+
tuieval tune <model> --ctx # largest context it can be served with on this machine, measured
|
|
176
177
|
tuieval export pi <model> # serve it in the pi coding agent with those flags
|
|
177
178
|
tuieval watch --upstream http://localhost:8080 # show the reasoning of any app using your server
|
|
178
179
|
tuieval help
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
tuieval/__init__.py,sha256=myVXVX7htbwezW6k3x_FuKgn1RSZ2WcTaDEMByGn6Wg,312
|
|
2
2
|
tuieval/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
-
tuieval/_version.py,sha256=
|
|
3
|
+
tuieval/_version.py,sha256=JzSeZ8IHIsxajjd9t8bAmIw4bXqFUdECzK4hpV4df3o,537
|
|
4
4
|
tuieval/agents.py,sha256=XmY4d4PAnC7BQcs_6KO9WTuIdpnwYVAdyhqItybWdAM,15408
|
|
5
5
|
tuieval/builtin.toml,sha256=QLQP1nh577RW6x0Z38JKNES-MPTSmlZAcxD5Javbk4Q,4768
|
|
6
|
-
tuieval/cli.py,sha256=
|
|
6
|
+
tuieval/cli.py,sha256=Q9-b9sg6LSAfNq6o-c3J3hiOIoINgvH_Fe_U1x-0W4U,4915
|
|
7
7
|
tuieval/client.py,sha256=O77uftaxqgQ8b8rMnpR5822kmYFfr574w1pZlaSOFEE,14304
|
|
8
8
|
tuieval/compare.py,sha256=T5MDIkNzPGTFUvYr1EzxVGGlCdvTlO1v5De3gN0Eocw,39654
|
|
9
|
+
tuieval/ctxbench.py,sha256=-65BHVBCjbdflMaH5Z5trjHtWwrniIGV-TpOT0Yxa1s,19271
|
|
9
10
|
tuieval/dates.py,sha256=CVazlwNjCRhD__D12zXLdeqF2ySt15X3xLUQeE-o6PY,6293
|
|
10
11
|
tuieval/doctor.py,sha256=j2MdDORstsAGPnRmpsnxau1_fR6sTc_oEFGM5zugTJU,7246
|
|
11
|
-
tuieval/engine.py,sha256=
|
|
12
|
+
tuieval/engine.py,sha256=5F9GGoncVc424sELAR0016Tw5ImxJJryTtmH9ihP0eg,141504
|
|
12
13
|
tuieval/export.py,sha256=dbHQgL_ubWtIPM1sLzAew_gETnrDJyd0zgqVA5vkpXM,9657
|
|
13
14
|
tuieval/insights.py,sha256=hIJp1n0eZeoo9QCyS5-OChv70ItSqV8jSsInoh4Stm0,29591
|
|
14
15
|
tuieval/logs.py,sha256=01gZK6tf53dIThaIrs1bEsz9eqKYVlcxpyaLnSPTVxo,8127
|
|
15
|
-
tuieval/machines.py,sha256=
|
|
16
|
+
tuieval/machines.py,sha256=Sz8ba4LXqTH-ENipB6vtzi9p-dDr6mOg9oge_k_Bu2g,20990
|
|
16
17
|
tuieval/onboard.py,sha256=IYETVDWCCo9vF0Dtj4_rr9VanYeCky8PwP3-2g5A_l0,6215
|
|
17
18
|
tuieval/packs.py,sha256=KOj0BkwsB2124aslGyauZonyyGqtSrCJ-WAozEntmqE,17466
|
|
18
|
-
tuieval/profiles.py,sha256=
|
|
19
|
+
tuieval/profiles.py,sha256=3GribubCOCRTi_rClLxVynBeX2SBYTig0XObAlS8lzg,5300
|
|
19
20
|
tuieval/pta.py,sha256=MBn2EkDysayv8XOqiTKp5zomuUmZnZTuQ5jGBR2-Z4s,19281
|
|
20
|
-
tuieval/remove.py,sha256=
|
|
21
|
-
tuieval/run_evals.py,sha256=
|
|
21
|
+
tuieval/remove.py,sha256=ckep4iZUkuWE2JTcZFovCy7snNd_WLkJ6b602eGKZws,5339
|
|
22
|
+
tuieval/run_evals.py,sha256=7HkKvcUqcOliwVoZlFoXHpDCIIk6ixbZyg2dMXkis5I,56178
|
|
22
23
|
tuieval/scaffold.py,sha256=YBOqniJpf_GtKKAFF3_OHxxMGbmTWdFjcClGcOnrrKE,12130
|
|
23
24
|
tuieval/selftest.py,sha256=cIGSDCrCK-QISAXjKSJDB4sD-WwS32bn3Gn4Y0oGoF8,11502
|
|
24
25
|
tuieval/tui.py,sha256=5BtqHoEtqBHRCrh0qPn2Vmg-4hSjjtlfPQ5qoysHlb0,211349
|
|
@@ -50,8 +51,8 @@ tuieval/templates/packs/tool_call/pack.toml,sha256=n4bx0lGJHSmW41uVqhfIXJ2BWZpmT
|
|
|
50
51
|
tuieval/templates/packs/tool_call/system.txt,sha256=mKxu-lB-0YjLHXdgeFJa8x2C180OvcNz5cHv2N5Bg3U,254
|
|
51
52
|
tuieval/templates/packs/tool_call/tests.yaml,sha256=Nv7c4syrzJ9cU8EBKSK_1ZSFx9V02aCjW4-2TBCPT7s,1859
|
|
52
53
|
tuieval/templates/packs/tool_call/tools.yaml,sha256=HgxCkh0On2VwbHSsjAGM8tNCK7ZtKLGrs7lMCn3Fprs,1048
|
|
53
|
-
tuieval-0.2.0.
|
|
54
|
-
tuieval-0.2.0.
|
|
55
|
-
tuieval-0.2.0.
|
|
56
|
-
tuieval-0.2.0.
|
|
57
|
-
tuieval-0.2.0.
|
|
54
|
+
tuieval-0.2.0.dev149.dist-info/METADATA,sha256=fSNrIqiDmsdPw69AVFAi86cfoL_aGMorQ44TpexnE9E,15306
|
|
55
|
+
tuieval-0.2.0.dev149.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
56
|
+
tuieval-0.2.0.dev149.dist-info/entry_points.txt,sha256=7eIhi1GpFxBP2OLJV02Nn8LwsNuO512eKOGt1IBbj04,45
|
|
57
|
+
tuieval-0.2.0.dev149.dist-info/licenses/LICENSE,sha256=7wfRgGtBGH1aXhZkIn47oUznqKC18kEPMvUVgol7Ffc,1077
|
|
58
|
+
tuieval-0.2.0.dev149.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|