tuieval 0.2.0.dev147__tar.gz → 0.2.0.dev149__tar.gz
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-0.2.0.dev147 → tuieval-0.2.0.dev149}/CHANGELOG.md +1 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/PKG-INFO +2 -1
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/README.md +1 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/models.md +19 -1
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/_version.py +2 -2
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/cli.py +1 -0
- tuieval-0.2.0.dev149/src/tuieval/ctxbench.py +390 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/engine.py +74 -16
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/machines.py +17 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/profiles.py +37 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/remove.py +3 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/run_evals.py +57 -9
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/tests/mock_server.py +24 -1
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/tests/test_tuieval.py +207 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/.gitignore +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/LICENSE +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/RELEASING.md +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/agent-packs.md +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/README.md +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/favicon.ico +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/readme-header.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/social-preview.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-1024.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-128.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-16.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-16.svg +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-256.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-32.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-48.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-512.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-64.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon-animated.svg +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/brand/tuieval-icon.svg +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/tui-answer-reasoning.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/tui-run-reasoning.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/images/tui-setup.png +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/docs/writing-packs.md +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/pyproject.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/__init__.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/__main__.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/agents.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/builtin.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/client.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/compare.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/dates.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/doctor.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/export.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/__init__.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/answer.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/code.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/rag.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/reply.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/graders/tool_call.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/insights.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/logs.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/onboard.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/packs.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/pta.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/scaffold.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/selftest.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/models.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/answer/pack.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/answer/system.txt +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/answer/tests.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/code/pack.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/code/system.txt +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/code/tests.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/rag/pack.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/rag/system.txt +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/rag/tests.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/reply/pack.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/reply/system.txt +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/reply/tests.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/tool_call/pack.toml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/tool_call/system.txt +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/tool_call/tests.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/templates/packs/tool_call/tools.yaml +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/tui.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/tune.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/verdict.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/watch_proxy.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/workspace.py +0 -0
- {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev149}/src/tuieval/yamlout.py +0 -0
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `tuieval tune <model> --ctx` measures the largest context a model can be served with on this machine, for any server tuieval starts: it fills each context it tries and checks the answer, the tokens the server read, memory pressure and swapping. Runs then use the measured context in place of the fit check's estimate (`tuning/<machine>/<model>.ctx.toml`; `tuieval machines` shows *measured*). See docs/models.md.
|
|
5
6
|
- Results from more than one machine: a **Machine** dropdown in Results keeps only the answers that ran on one machine, in every tab (hosted models' answers count from any machine unless **Hosted from any machine** is unticked). `--ran-on <id>` (and `--ran-on-strict`) on `tuieval pta`, `compare`, `verdict`, `report` and `insights`.
|
|
6
7
|
- Fix: the PTA index's Score ≥ filter did nothing once a pack was picked; it now filters the models that answered the pack (models picked by hand are still always shown).
|
|
7
8
|
- PTA index: models scoring below 85% are left out by default (listed with their score), unless every model is. The **Score ≥** dropdown (`tuieval pta --min-score N`) sets the minimum, Any score shows all; picked models are always shown.
|
|
@@ -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
|
|
@@ -147,6 +147,7 @@ tuieval regrade # re-score stored answers after ch
|
|
|
147
147
|
tuieval regrade --only <model> --packs X # just one model's results (and packs)
|
|
148
148
|
tuieval machines # this machine and others, fit and tuning per model
|
|
149
149
|
tuieval tune <model> # fastest speed flags for a model on this machine
|
|
150
|
+
tuieval tune <model> --ctx # largest context it can be served with on this machine, measured
|
|
150
151
|
tuieval export pi <model> # serve it in the pi coding agent with those flags
|
|
151
152
|
tuieval watch --upstream http://localhost:8080 # show the reasoning of any app using your server
|
|
152
153
|
tuieval help
|
|
@@ -147,6 +147,23 @@ Expect 8–15 server starts, about 20–30 minutes for a 27B model, once per mod
|
|
|
147
147
|
|
|
148
148
|
The knobs are `[servers.<name>.tune]` in `models.toml`: each knob is a list of options, each option a list of flags. Placeholders: `{p}` P-cores, `{p_minus_2}`, `{all}` all cores, `{gpu_safe_gb}` (the GPU residency limit minus 2 GB; also `_minus_1`, `_minus_2`, `_plus_1`).
|
|
149
149
|
|
|
150
|
+
|
|
151
|
+
## Measuring the largest context
|
|
152
|
+
|
|
153
|
+
The fit check estimates the context from the model file, and only for servers that use memory the way llama.cpp does. `tuieval tune <model> --ctx` measures it instead, the same way for any server tuieval starts:
|
|
154
|
+
|
|
155
|
+
1. It starts the server with a context, sends a built-in document that fills it (sized from the token counts the server reports, so any tokenizer works) with one fact near the start, and asks for that fact.
|
|
156
|
+
2. The try passes when the answer is right, the server read the whole document (a server that cuts long prompts short fails here), and the machine stayed healthy: no macOS memory pressure, no swapping, memory left on Linux. A try is stopped the moment one of those turns bad.
|
|
157
|
+
3. It starts at a quarter of the upper bound and doubles. Memory grows about linearly with the context, so two tries that passed predict the largest context that fits in the machine's memory (less `memory_headroom_gb`, and less whatever other apps hold now); no try goes above the prediction, and a failed try is bisected against the largest that passed.
|
|
158
|
+
|
|
159
|
+
Expect 3 to 5 server starts; the largest ones take as long as the server needs to read that many tokens. It won't start when memory pressure is already elevated or the model is larger than the memory free now.
|
|
160
|
+
|
|
161
|
+
The upper bound is `--max N`, else the smallest of the server's `max_ctx`, the model's `ctx` or `max_context` and a context flag written in `models.toml`, else the model file's own limit. `--start N` sets the first context tried, `--step N` how close to the true maximum to get (default 8192).
|
|
162
|
+
|
|
163
|
+
The result is saved in `tuning/<machine>/<model>.ctx.toml`: the context, the memory with it full, the memory per 1,000 tokens and every try. Runs on that machine then use it in place of the estimate; your own caps still apply, so raise `max_ctx` if the measured context is above it. `tuieval machines` marks it *measured*. Delete the file to go back to the estimate; a measurement made with another model file or KV type is ignored.
|
|
164
|
+
|
|
165
|
+
tuieval sets the context through `{ctx}` in the server's `cmd`, or through its `ctx_flag`. For a server with neither (one already running, or one that sizes itself), `--ctx` only checks the `max_context` its model declares, with one try, and saves nothing.
|
|
166
|
+
|
|
150
167
|
## Exporting to the pi coding agent
|
|
151
168
|
|
|
152
169
|
`tuieval export pi <model>` makes pi serve a model the way the evals did: the same file, the output-affecting flags, the context from the fit check, the model's sampling, and the speed flags tuned on this machine. `tuieval tune <model> --export-pi` does it right after tuning.
|
|
@@ -185,7 +202,7 @@ On Apple Silicon Macs, once the system's GPU allocations pass about half of RAM,
|
|
|
185
202
|
| `fit_check` | size the context from the GGUF header and skip models that don't fit (the fit check; it assumes llama.cpp's memory use). Default: on for servers whose `cmd` takes `{ctx}`, off for others, whose context is the model's `max_context` |
|
|
186
203
|
| `vision_args` | flags appended for models with `mmproj` |
|
|
187
204
|
| `kv_type`, `max_ctx` | llama defaults: KV-cache type, upper bound on context |
|
|
188
|
-
| `ctx_flag` | the server's context flag,
|
|
205
|
+
| `ctx_flag` | the server's context flag (e.g. `--max-context`), for servers whose `cmd` doesn't take `{ctx}`: long packs are skipped if a configured context is too small, and `tuieval tune --ctx` sets it to measure the largest context |
|
|
189
206
|
| `request` | fields added to every request (e.g. `{ cache_prompt = false }`) |
|
|
190
207
|
| `perf` | speed-only flags always applied |
|
|
191
208
|
| `tune` | speed-only knobs for `tuieval tune` |
|
|
@@ -316,6 +333,7 @@ Optional sections:
|
|
|
316
333
|
# warm_retest = ["spec", "ubatch"] # the knobs a warm start re-tries; the rest are inherited
|
|
317
334
|
# answer_tokens = 1024 # answer length options are scored for (projected objective)
|
|
318
335
|
# swap_limit_mb = 500 # reject options that swap more than this beyond the defaults (default: report only)
|
|
336
|
+
# ctx_request_timeout_s = 3600 # tune --ctx: how long a server may take to read one full context
|
|
319
337
|
|
|
320
338
|
# Optional: llama-bench for the tuner's fast first stage (found on PATH as llama-bench otherwise).
|
|
321
339
|
# [bench]
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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,
|