tuieval 0.2.0.dev145__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/compare.py +43 -1
- tuieval/ctxbench.py +390 -0
- tuieval/engine.py +74 -16
- tuieval/insights.py +4 -4
- tuieval/machines.py +17 -0
- tuieval/profiles.py +37 -0
- tuieval/pta.py +10 -4
- tuieval/remove.py +3 -0
- tuieval/run_evals.py +107 -23
- tuieval/tui.py +51 -4
- tuieval/verdict.py +20 -6
- {tuieval-0.2.0.dev145.dist-info → tuieval-0.2.0.dev149.dist-info}/METADATA +3 -1
- {tuieval-0.2.0.dev145.dist-info → tuieval-0.2.0.dev149.dist-info}/RECORD +18 -17
- {tuieval-0.2.0.dev145.dist-info → tuieval-0.2.0.dev149.dist-info}/WHEEL +0 -0
- {tuieval-0.2.0.dev145.dist-info → tuieval-0.2.0.dev149.dist-info}/entry_points.txt +0 -0
- {tuieval-0.2.0.dev145.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/compare.py
CHANGED
|
@@ -4,6 +4,8 @@ Usage:
|
|
|
4
4
|
tuieval compare # everything in results/<model>/<pack>.json
|
|
5
5
|
tuieval compare --speed # speed & tokens table (TTFT, tok/s, tokens, memory)
|
|
6
6
|
tuieval compare --machine m3max-64gb # speed on another machine (measured there, or projected)
|
|
7
|
+
tuieval compare --ran-on m3max-64gb # only the answers that ran there (hosted models: any machine;
|
|
8
|
+
# --ran-on-strict: those too)
|
|
7
9
|
tuieval compare --pairwise --failures # is each difference real? which tests failed?
|
|
8
10
|
tuieval compare --reference MODEL # every model paired against one: better, tie or worse
|
|
9
11
|
tuieval compare --packs coding,rag # only these packs (works with every option)
|
|
@@ -63,6 +65,7 @@ def _load_native(data):
|
|
|
63
65
|
"severity": r.get("severity"), "group": r.get("group"), "repeat": r.get("repeat", 0),
|
|
64
66
|
"difficulty": r.get("difficulty", "unrated"),
|
|
65
67
|
"machine": r.get("machine") or run.get("machine"), "prompt_tokens": r.get("prompt_tokens"),
|
|
68
|
+
"hosted": info["hosted"], # an API's answer: it doesn't depend on the machine tuieval ran on (ran_on)
|
|
66
69
|
# other models served at the same time (parallel_models): its speed was shared with them
|
|
67
70
|
"alongside": r.get("ran_alongside") or [],
|
|
68
71
|
"agent": r.get("agent"), # an agent pack's task: the agent's stats (see agents.py)
|
|
@@ -95,12 +98,41 @@ def load(paths):
|
|
|
95
98
|
def local(along):
|
|
96
99
|
return [l for l in along if l not in labels and not l.startswith(tuple(prefixes))]
|
|
97
100
|
for row in rows:
|
|
101
|
+
row["hosted"] = row["hosted"] or row["model"] in labels or row["model"].startswith(tuple(prefixes) or ("\0",))
|
|
98
102
|
row["alongside"] = [] if row["model"] in labels else local(row["alongside"])
|
|
99
103
|
for i in infos:
|
|
100
104
|
i["loaded_alongside"] = [] if i["label"] in labels else local(i["loaded_alongside"])
|
|
101
105
|
return rows, infos
|
|
102
106
|
|
|
103
107
|
|
|
108
|
+
UNKNOWN_MACHINE = "unknown" # answers that recorded no machine
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def machine_of(r):
|
|
112
|
+
"""The machine an answer (a row, or a stored record) ran on, or UNKNOWN_MACHINE."""
|
|
113
|
+
return r.get("machine") or UNKNOWN_MACHINE
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def machines(rows):
|
|
117
|
+
"""{machine id: answers}, most answers first: the machines these answers ran on."""
|
|
118
|
+
return dict(collections.Counter(machine_of(r) for r in rows).most_common())
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def ran_on(rows, machine, hosted_any=True):
|
|
122
|
+
"""The answers that ran on machine (None: all of them). hosted_any: hosted models' answers are kept
|
|
123
|
+
whatever machine tuieval ran on, since an API's answer doesn't depend on it."""
|
|
124
|
+
if not machine:
|
|
125
|
+
return rows
|
|
126
|
+
return [r for r in rows if machine_of(r) == machine or (hosted_any and r.get("hosted"))]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def ran_on_note(machine, hosted_any=True):
|
|
130
|
+
"""" on m3max-64gb" (hosted models from any machine) for a scope sentence, or "" for every machine."""
|
|
131
|
+
if not machine:
|
|
132
|
+
return ""
|
|
133
|
+
return f" on {machine}" + (" (hosted models: any machine)" if hosted_any else "")
|
|
134
|
+
|
|
135
|
+
|
|
104
136
|
def _configs(paths):
|
|
105
137
|
"""The models.toml configs of the workspaces these results/<label>/<pack>.json are from (unreadable
|
|
106
138
|
ones left out)."""
|
|
@@ -663,13 +695,23 @@ def main(argv):
|
|
|
663
695
|
machine_arg = argv[argv.index("--machine") + 1] if "--machine" in argv else None
|
|
664
696
|
ref = argv[argv.index("--reference") + 1] if "--reference" in argv else None
|
|
665
697
|
only_packs = argv[argv.index("--packs") + 1].split(",") if "--packs" in argv else None
|
|
666
|
-
|
|
698
|
+
ran = argv[argv.index("--ran-on") + 1] if "--ran-on" in argv else None
|
|
699
|
+
values = (log_dir, machine_arg, ref, ",".join(only_packs) if only_packs else None, ran)
|
|
667
700
|
paths = [a for a in argv if not a.startswith("--") and a not in values] or default_paths()
|
|
668
701
|
if only_packs:
|
|
669
702
|
paths = [p for p in paths if os.path.basename(p)[:-len(".json")] in only_packs]
|
|
670
703
|
if not paths:
|
|
671
704
|
sys.exit(__doc__ + "\n(no results found in results/<model>/<pack>.json: run some evals first)")
|
|
672
705
|
rows, infos = load(paths)
|
|
706
|
+
if "--ran-on-strict" in flags and not ran:
|
|
707
|
+
sys.exit("--ran-on-strict needs --ran-on MACHINE")
|
|
708
|
+
if ran:
|
|
709
|
+
known = machines(rows)
|
|
710
|
+
if ran not in known:
|
|
711
|
+
sys.exit(f"no answers ran on {ran!r}; machines with answers: "
|
|
712
|
+
+ ", ".join(f"{m} ({n})" for m, n in known.items()))
|
|
713
|
+
rows = ran_on(rows, ran, "--ran-on-strict" not in flags)
|
|
714
|
+
print(f"Only the answers{ran_on_note(ran, '--ran-on-strict' not in flags)}.")
|
|
673
715
|
if ref:
|
|
674
716
|
if ref not in {r["model"] for r in rows}:
|
|
675
717
|
sys.exit(f"no results for reference model {ref!r}" + (f" in {', '.join(only_packs)}" if only_packs else ""))
|
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,
|