tuieval 0.2.0.dev147__tar.gz → 0.2.0.dev152__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.
Files changed (83) hide show
  1. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/CHANGELOG.md +2 -0
  2. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/PKG-INFO +2 -1
  3. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/README.md +1 -0
  4. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/models.md +22 -2
  5. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/_version.py +2 -2
  6. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/cli.py +1 -0
  7. tuieval-0.2.0.dev152/src/tuieval/ctxbench.py +424 -0
  8. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/engine.py +74 -16
  9. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/machines.py +33 -0
  10. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/profiles.py +37 -0
  11. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/remove.py +3 -0
  12. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/run_evals.py +55 -9
  13. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/tests/mock_server.py +24 -1
  14. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/tests/test_tuieval.py +274 -0
  15. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/.gitignore +0 -0
  16. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/LICENSE +0 -0
  17. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/RELEASING.md +0 -0
  18. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/agent-packs.md +0 -0
  19. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/README.md +0 -0
  20. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/favicon.ico +0 -0
  21. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/readme-header.png +0 -0
  22. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/social-preview.png +0 -0
  23. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-1024.png +0 -0
  24. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-128.png +0 -0
  25. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-16.png +0 -0
  26. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-16.svg +0 -0
  27. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-256.png +0 -0
  28. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-32.png +0 -0
  29. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-48.png +0 -0
  30. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-512.png +0 -0
  31. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-64.png +0 -0
  32. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-animated.svg +0 -0
  33. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon.svg +0 -0
  34. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/tui-answer-reasoning.png +0 -0
  35. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/tui-run-reasoning.png +0 -0
  36. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/images/tui-setup.png +0 -0
  37. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/docs/writing-packs.md +0 -0
  38. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/pyproject.toml +0 -0
  39. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/__init__.py +0 -0
  40. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/__main__.py +0 -0
  41. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/agents.py +0 -0
  42. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/builtin.toml +0 -0
  43. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/client.py +0 -0
  44. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/compare.py +0 -0
  45. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/dates.py +0 -0
  46. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/doctor.py +0 -0
  47. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/export.py +0 -0
  48. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/__init__.py +0 -0
  49. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/answer.py +0 -0
  50. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/code.py +0 -0
  51. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/rag.py +0 -0
  52. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/reply.py +0 -0
  53. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/graders/tool_call.py +0 -0
  54. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/insights.py +0 -0
  55. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/logs.py +0 -0
  56. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/onboard.py +0 -0
  57. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/packs.py +0 -0
  58. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/pta.py +0 -0
  59. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/scaffold.py +0 -0
  60. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/selftest.py +0 -0
  61. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/models.toml +0 -0
  62. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/pack.toml +0 -0
  63. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/system.txt +0 -0
  64. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/tests.yaml +0 -0
  65. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/pack.toml +0 -0
  66. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/system.txt +0 -0
  67. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/tests.yaml +0 -0
  68. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/pack.toml +0 -0
  69. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/system.txt +0 -0
  70. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/tests.yaml +0 -0
  71. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/pack.toml +0 -0
  72. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/system.txt +0 -0
  73. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/tests.yaml +0 -0
  74. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/pack.toml +0 -0
  75. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/system.txt +0 -0
  76. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/tests.yaml +0 -0
  77. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/tools.yaml +0 -0
  78. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/tui.py +0 -0
  79. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/tune.py +0 -0
  80. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/verdict.py +0 -0
  81. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/watch_proxy.py +0 -0
  82. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/workspace.py +0 -0
  83. {tuieval-0.2.0.dev147 → tuieval-0.2.0.dev152}/src/tuieval/yamlout.py +0 -0
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `tuieval tune --ctx`: the measured context governs the caps in `models.toml` (`max_ctx`, a model's `ctx`, a context flag), not the other way around: the search runs up to the model's own limit, and runs use what was measured even above a cap. It starts at half the model's current context, and a try is also stopped while the server loads. Memory is measured as what the machine loses while the server runs (on a Mac from `vm_stat` page counts, not the rounded free percentage), so memory-mapped files a server reads on demand no longer count against it.
6
+ - `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
7
  - 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
8
  - 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
9
  - 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.dev147
3
+ Version: 0.2.0.dev152
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,25 @@ 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, also while the server is still loading.
157
+ 3. It starts at half the context the model runs with now (32768 when that isn't known) 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
+ Memory is read off the machine, not the server's processes: the memory available before the server starts, less the lowest it falls to while the context is full (VRAM on discrete GPUs). On a Mac, available memory is RAM less what is held and can't be given back (anonymous and wired pages and the compressor, from `vm_stat`), so files a server maps and reads on demand don't count against it, and the reading is in the same terms as the memory it is compared with.
162
+
163
+ The upper bound is the model's own limit: `--max N`, else the context length in the model file, else the model's `max_context`. What `models.toml` caps the context at (`max_ctx`, a model's `ctx`, a context flag in `server_args`) doesn't bound the search. `--start N` sets the first context tried, `--step N` how close to the true maximum to get (default 8192).
164
+
165
+ 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 as the model's context, in place of the estimate and of the caps in `models.toml`: those were written without the measurement, so it governs them, also when it is larger. `tuieval machines` marks it *measured*. To hold a model below its maximum, lower the `max_ctx` line in that `.ctx.toml` file; delete the file to go back to the estimate and the caps. Also, a measurement made with another model file or KV type is ignored.
166
+
167
+ 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.
168
+
150
169
  ## Exporting to the pi coding agent
151
170
 
152
171
  `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.
@@ -184,8 +203,8 @@ On Apple Silicon Macs, once the system's GPU allocations pass about half of RAM,
184
203
  | `model_is_path` | `model` is a file or folder: check it exists before starting |
185
204
  | `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
205
  | `vision_args` | flags appended for models with `mmproj` |
187
- | `kv_type`, `max_ctx` | llama defaults: KV-cache type, upper bound on context |
188
- | `ctx_flag` | the server's context flag, so long packs are skipped if a configured context is too small |
206
+ | `kv_type`, `max_ctx` | llama defaults: KV-cache type, upper bound on context (until a model's context is measured with `tuieval tune --ctx`) |
207
+ | `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
208
  | `request` | fields added to every request (e.g. `{ cache_prompt = false }`) |
190
209
  | `perf` | speed-only flags always applied |
191
210
  | `tune` | speed-only knobs for `tuieval tune` |
@@ -316,6 +335,7 @@ Optional sections:
316
335
  # warm_retest = ["spec", "ubatch"] # the knobs a warm start re-tries; the rest are inherited
317
336
  # answer_tokens = 1024 # answer length options are scored for (projected objective)
318
337
  # swap_limit_mb = 500 # reject options that swap more than this beyond the defaults (default: report only)
338
+ # ctx_request_timeout_s = 3600 # tune --ctx: how long a server may take to read one full context
319
339
 
320
340
  # Optional: llama-bench for the tuner's fast first stage (found on PATH as llama-bench otherwise).
321
341
  # [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.dev147'
22
- __version_tuple__ = version_tuple = (0, 2, 0, 'dev147')
21
+ __version__ = version = '0.2.0.dev152'
22
+ __version_tuple__ = version_tuple = (0, 2, 0, 'dev152')
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,424 @@
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 memory the server takes (how much less is available while it runs; VRAM on
11
+ discrete GPUs), macOS memory pressure and swapping
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 at half the context the model runs with now and doubles, up to the model's own
20
+ limit: what models.toml caps the context at (max_ctx, ctx, a context flag) doesn't bound it, since
21
+ the measurement replaces those. Memory grows about linearly with the context, so two probes that
22
+ passed predict the largest context that fits under the machine's limit; no probe goes above that
23
+ prediction, and a failed probe is bisected against the largest that passed. A probe is stopped at
24
+ once, while the server loads or works, when memory pressure rises, the machine starts swapping,
25
+ or memory runs out. Typically 3 to 5 server starts.
26
+
27
+ Memory is read off the machine, not the server's processes: available memory before the server
28
+ starts less the lowest it falls to. Resident memory would count files a server maps and reads on
29
+ demand, which the system can drop again, and that reading is what is compared with the memory
30
+ available, so both are in the same terms.
31
+
32
+ A server tuieval doesn't start, or can't set the context of, is only verified at the context its
33
+ model declares (max_context): one probe, nothing saved.
34
+ """
35
+ import dataclasses
36
+ import os
37
+ import threading
38
+
39
+ from . import engine as engine_mod
40
+ from . import machines
41
+ from . import profiles
42
+ from . import tune
43
+
44
+ ANSWER_TOKENS = 1024 # room for the answer (and any thinking) in a probe
45
+ STEP = 8192 # how close to the true maximum the search gets
46
+ FLOOR = machines.MIN_CTX # the smallest context tried
47
+ FIRST = 32768 # the first context tried for a model whose usual context isn't known
48
+ APART = 0.8 # memory per token is read off two probes at least this far apart (the lower one
49
+ # at most this share of the higher): closer ones differ by less than the noise
50
+ MAX_STARTS = 8
51
+ REQUEST_LIMIT_S = 3600 # reading a few hundred thousand tokens takes a while ([tune] ctx_request_timeout_s)
52
+ PRESSURE_WARNING = 2 # macOS memory pressure level that stops a probe (1 is normal)
53
+ SWAP_STOP_MB = 512 # swapped out while a probe ran: stop it
54
+ AVAILABLE_STOP_GB = 1.0 # memory available under this stops a probe
55
+ TOO_LITTLE = 0.5 # a reading under this share of the model's size on disk can't be right for a server
56
+ # that holds the model in memory: its resident memory is used instead
57
+ SAMPLE_CHARS = 12000 # the request that measures the server's characters per token
58
+ UNKNOWN_CHARS_PER_TOKEN = 3.0 # for a server that reports no token counts: short of full rather than over
59
+ NOT_ABOUT_CONTEXT = ("already in use", "isn't installed", "not found", "is not set", "skipped by user")
60
+ CODE = 481739 # six digits: no section number or step count in the document can equal it
61
+ WORDS = ("river", "station", "ledger", "orchard", "signal", "harbour", "copper", "meadow", "lantern",
62
+ "quarry", "window", "valley", "engine", "garden", "bridge", "tower")
63
+
64
+
65
+ @dataclasses.dataclass
66
+ class Probe:
67
+ ctx: int
68
+ ok: bool = False
69
+ error: str = ""
70
+ mem_gb: float | None = None # the server's peak memory with the context full
71
+ prompt_tokens: int | None = None # as the server counted them
72
+ pp_tps: float | None = None
73
+ tg_tps: float | None = None
74
+ total_s: float | None = None
75
+ load_s: float | None = None
76
+ filled: bool = False # the server's token count confirms the context was full
77
+
78
+ def summary(self):
79
+ if not self.ok:
80
+ return f"failed: {self.error}"
81
+ parts = ["ok"]
82
+ if self.mem_gb is not None:
83
+ parts.append(f"{self.mem_gb:.1f} GB")
84
+ if self.prompt_tokens:
85
+ parts.append(f"{self.prompt_tokens:,} prompt tokens" + ("" if self.filled else " (fill not confirmed)"))
86
+ if self.pp_tps:
87
+ parts.append(f"prompt {self.pp_tps:.0f} tok/s")
88
+ if self.tg_tps:
89
+ parts.append(f"gen {self.tg_tps:.1f} tok/s")
90
+ return ", ".join(parts)
91
+
92
+
93
+ # ------------------------------------------------------------------ the document
94
+ def document(chars):
95
+ """A ~chars-long synthetic document with one fact near its start and the question at its end
96
+ (the same text every time). A server that drops the start of a long prompt loses the fact."""
97
+ paras, size, i = [], 0, 0
98
+ while size < chars:
99
+ w = [WORDS[(i * 7 + k * 3) % len(WORDS)] for k in range(12)]
100
+ 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 "
101
+ f"{w[5]} was painted {w[6]} after the {w[7]} flooded. Visitors to the {w[8]} counted "
102
+ f"{(i * 37) % 900 + 100} steps to the {w[9]}, past a {w[10]} facing the {w[11]}.")
103
+ paras.append(p)
104
+ size += len(p) + 2
105
+ i += 1
106
+ paras.insert(max(1, len(paras) // 20), f"Note: the archive room code is {CODE}.")
107
+ return "\n\n".join(paras) + "\n\nWhat is the archive room code? Answer with the number only."
108
+
109
+
110
+ def _ask(eng, m, base_url, chars, max_tokens, name, emit, limit):
111
+ sampling = engine_mod.effective_sampling(eng.cfg, m)
112
+ request = eng.cfg["servers"][m["server"]].get("request", {})
113
+ body = tune._body(m, sampling, [{"role": "user", "content": document(chars)}], max_tokens, request)
114
+ body.pop("ignore_eos", None) # the answer should end where the model ends it
115
+ return tune._stream_request(eng, base_url, body, name, emit, limit)
116
+
117
+
118
+ def chars_per_token(eng, m, base_url, emit, limit):
119
+ """Characters of the document per token, by this server's count (None if it reports none)."""
120
+ from . import client
121
+ res = _ask(eng, m, base_url, SAMPLE_CHARS, 8, "sizing", emit, limit)
122
+ if res.get("error"):
123
+ raise engine_mod.ModelFailed(f"sizing request: {res['error']}")
124
+ tokens = client.metrics(res)["prompt_tokens"]
125
+ return SAMPLE_CHARS / tokens if tokens else None
126
+
127
+
128
+ def too_long(error):
129
+ e = (error or "").lower()
130
+ return "http 4" in e and any(w in e for w in ("context", "too long", "too large", "exceed", "maximum"))
131
+
132
+
133
+ class Guard:
134
+ """Watches the machine while a probe's server loads and works. When it gets unhealthy, the
135
+ server is stopped: a load is abandoned and a request is cut off."""
136
+
137
+ def __init__(self, eng, every_s=2.0):
138
+ self.eng, self.every_s, self.reason = eng, every_s, ""
139
+ self.pressure, self._stop = machines.memory_pressure_level(), threading.Event()
140
+ self._swap0 = machines.swapped_out_bytes()
141
+ self._own_memory = eng.machine().discrete # VRAM: the machine's memory isn't what runs out
142
+ self.available0 = self.lowest = None if self._own_memory else machines.available_memory_gb()
143
+
144
+ def __enter__(self):
145
+ self._thread = threading.Thread(target=self._run, daemon=True)
146
+ self._thread.start()
147
+ return self
148
+
149
+ def check(self):
150
+ lvl = machines.memory_pressure_level()
151
+ if lvl is not None:
152
+ self.pressure = max(self.pressure or 0, lvl)
153
+ if lvl >= PRESSURE_WARNING:
154
+ return f"macOS memory pressure rose to level {lvl}"
155
+ swap = machines.swapped_out_bytes()
156
+ if None not in (swap, self._swap0) and (swap - self._swap0) / 2**20 > SWAP_STOP_MB:
157
+ return f"the machine swapped out {(swap - self._swap0) / 2**20:.0f} MB"
158
+ if not self._own_memory:
159
+ free = machines.available_memory_gb()
160
+ if free is not None:
161
+ self.lowest = free if self.lowest is None else min(self.lowest, free)
162
+ if free < AVAILABLE_STOP_GB:
163
+ return f"only {free:.1f} GB of memory was left"
164
+ return ""
165
+
166
+ def taken_gb(self):
167
+ """Memory the machine lost while the block ran (None where it can't be read)."""
168
+ if None in (self.available0, self.lowest):
169
+ return None
170
+ return max(self.available0 - self.lowest, 0.0)
171
+
172
+ def _run(self):
173
+ while not self._stop.wait(self.every_s):
174
+ self.reason = self.reason or self.check()
175
+ if self.reason:
176
+ self.eng._stall = self.reason # ends the wait for a server that is still loading
177
+ stream = getattr(self.eng, "_stream", None)
178
+ if stream is not None:
179
+ stream.close()
180
+ return
181
+
182
+ def __exit__(self, *exc):
183
+ self._stop.set()
184
+ self._thread.join(self.every_s + 1)
185
+ self.reason = self.reason or self.check()
186
+ self.eng._stall = None
187
+
188
+
189
+ def probe(eng, m, ctx, emit=lambda *a, **k: None, limit=REQUEST_LIMIT_S):
190
+ """Serve the model with this context, fill it and ask for the fact. Returns a Probe."""
191
+ from . import client
192
+ out = Probe(ctx)
193
+ reserve = ANSWER_TOKENS + max(256, ctx // 50)
194
+ target = ctx - reserve
195
+ if target < 1024:
196
+ out.error = f"a context of {ctx:,} is too small to test"
197
+ return out
198
+ guard = Guard(eng)
199
+ try:
200
+ with guard, eng.serve(m, log_name=f"{m['label']}.ctx", ctx=ctx) as (url, info):
201
+ out.load_s = round(info["load_s"], 1) if info.get("load_s") else None
202
+ ratio = chars_per_token(eng, m, url, emit, limit)
203
+ chars = int(target * (ratio or UNKNOWN_CHARS_PER_TOKEN) * 0.98)
204
+ emit("tune_progress", message=f" filling the context: ~{target:,} tokens, {chars:,} characters"
205
+ + ("" if ratio else " (the server reports no token counts)"))
206
+ res = _ask(eng, m, url, chars, ANSWER_TOKENS, "fill", emit, limit)
207
+ if too_long(res.get("error")) and not guard.reason:
208
+ emit("tune_progress", message=" the server found that too long; trying 7% shorter")
209
+ res = _ask(eng, m, url, int(chars * 0.93), ANSWER_TOKENS, "fill", emit, limit)
210
+ met = client.metrics(res) if not res.get("error") else {}
211
+ out.prompt_tokens, out.pp_tps, out.tg_tps = met.get("prompt_tokens"), met.get("prompt_tps"), met.get("gen_tps")
212
+ out.total_s = round(res["total_s"], 1) if res.get("total_s") else None
213
+ guard.check()
214
+ out.mem_gb = memory_gb(eng, m, info, guard)
215
+ text = (res.get("answer") or "") + (res.get("reasoning") or "")
216
+ if res.get("error"):
217
+ out.error = res["error"]
218
+ elif not info["alive"]():
219
+ out.error = "the server stopped"
220
+ elif str(CODE) not in text:
221
+ out.error = "it didn't find a fact near the start of the document (the context isn't all used)"
222
+ elif out.prompt_tokens and out.prompt_tokens < 0.85 * target:
223
+ out.error = (f"the server read {out.prompt_tokens:,} of ~{target:,} tokens "
224
+ "(it cuts long prompts short)")
225
+ else:
226
+ out.ok = True
227
+ out.filled = bool(ratio and out.prompt_tokens and out.prompt_tokens >= 0.85 * target)
228
+ except engine_mod.ModelFailed as e:
229
+ out.error = str(e).splitlines()[0]
230
+ if not guard.reason and any(w in out.error for w in NOT_ABOUT_CONTEXT):
231
+ raise # a smaller context wouldn't help
232
+ if guard.reason: # the machine got unhealthy: that is why, whatever the server said as it was stopped
233
+ out.ok, out.error = False, guard.reason
234
+ return out
235
+
236
+
237
+ # ------------------------------------------------------------------ the search
238
+ def memory_gb(eng, m, info, guard):
239
+ """What the server took with its context full: VRAM on a discrete GPU, else how much less memory
240
+ the machine had available, else (where that can't be read, or reads implausibly low for a model
241
+ of this size) the resident memory of the server's processes."""
242
+ if eng.machine().discrete:
243
+ return round(info["vram_peak_gb"], 2) if info.get("vram_peak_gb") else None
244
+ taken, size = guard.taken_gb(), model_gb(m)
245
+ resident = (info["peak_mb"]() or 0) / 1024 if info.get("peak_mb") else 0
246
+ if not taken or (size and taken < TOO_LITTLE * size <= resident):
247
+ taken = resident
248
+ return round(taken, 2) if taken else None
249
+
250
+
251
+ def predict(passed, limit_gb):
252
+ """(base_gb, gb_per_token, largest context predicted to fit) from the largest context that
253
+ passed with a memory reading and the nearest one well below it (APART). The third is None when
254
+ memory doesn't grow with the context (nothing to predict) or there aren't two such readings."""
255
+ pts = sorted((p.ctx, p.mem_gb) for p in passed if p.mem_gb)
256
+ if len(pts) < 2:
257
+ return None, None, None
258
+ c2, g2 = pts[-1]
259
+ c1, g1 = next(((c, g) for c, g in reversed(pts[:-1]) if c <= APART * c2), pts[0])
260
+ per = (g2 - g1) / (c2 - c1)
261
+ base = g2 - per * c2
262
+ if per <= 0 or limit_gb is None:
263
+ return base, max(per, 0.0), None
264
+ return base, per, int((limit_gb - base) / per)
265
+
266
+
267
+ def _grid(n):
268
+ return int(n) // 1024 * 1024
269
+
270
+
271
+ def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_starts=MAX_STARTS,
272
+ emit=lambda *a, **k: None):
273
+ """Probe contexts until the largest that works is known to within `step`. try_ctx(ctx) -> Probe.
274
+ Returns (probes in the order tried, why it stopped)."""
275
+ tried, lo, hi, c = [], None, None, min(start, upper)
276
+ why = f"{max_starts} server starts used"
277
+ while len(tried) < max_starts:
278
+ emit("tune_step", message=f"[{len(tried) + 1}] context {c:,}", start=len(tried) + 1, max_starts=max_starts)
279
+ r = try_ctx(c)
280
+ tried.append(r)
281
+ emit("tune_result", message=" " + r.summary(), result=r)
282
+ if r.ok:
283
+ lo = max(lo or 0, c)
284
+ else:
285
+ hi = min(hi or c, c)
286
+ if lo is None: # nothing has worked yet: halve
287
+ c = _grid(hi // 2)
288
+ if c < floor:
289
+ why = f"nothing from {floor:,} up worked"
290
+ break
291
+ continue
292
+ if lo >= upper:
293
+ why = f"reached the upper bound ({upper:,})"
294
+ break
295
+ if hi is not None and hi - lo <= step:
296
+ why = f"{hi:,} failed: {next(p.error for p in tried if p.ctx == hi)}"
297
+ break
298
+ _, per, fit = predict([p for p in tried if p.ok], limit_gb)
299
+ nxt = min(upper, lo * 2) if hi is None else lo + _grid((hi - lo) / 2)
300
+ if fit is not None and fit < nxt:
301
+ if _grid(fit) - lo < min(step, upper - lo):
302
+ at = min(upper, lo + step)
303
+ why = (f"memory: {at:,} is predicted to need more than the {limit_gb:.1f} GB this machine has "
304
+ f"for it ({per * 1000:.3f} GB per 1,000 tokens)")
305
+ break
306
+ nxt = _grid(fit)
307
+ if nxt <= lo:
308
+ why = f"{hi:,} failed: {next(p.error for p in tried if p.ctx == hi)}" if hi else why
309
+ break
310
+ c = nxt
311
+ return tried, why
312
+
313
+
314
+ # ------------------------------------------------------------------ driver
315
+ def model_gb(m):
316
+ """The model's size on disk (a file with its other shards beside it, or a folder), or None."""
317
+ path = engine_mod.expand(str(m.get("model", "")))
318
+ try:
319
+ if os.path.isfile(path):
320
+ return os.path.getsize(path) / machines.GB
321
+ if os.path.isdir(path):
322
+ return sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(path) for f in fs) / machines.GB
323
+ except OSError:
324
+ pass
325
+ return None
326
+
327
+
328
+ def room_gb(eng):
329
+ """(memory this machine has for a model now, a reason not to load one at all or "")."""
330
+ mc = eng.machine()
331
+ headroom = eng.headroom_gb(mc)
332
+ if mc.discrete:
333
+ used = machines.vram_used_gb()
334
+ return mc.gpu_limit_gb - (used or 0) - headroom, ""
335
+ level = machines.memory_pressure_level()
336
+ if level is not None and level > 1:
337
+ return None, f"macOS memory pressure is already elevated (level {level}); close other apps or models first"
338
+ free = machines.available_memory_gb()
339
+ limit = mc.gpu_limit_gb - headroom
340
+ return (limit if free is None else min(limit, free - headroom)), ""
341
+
342
+
343
+ def upper_bound(m, asked=None):
344
+ """(the largest context worth trying, where that number comes from): the model's own limit.
345
+ What models.toml caps the context at (max_ctx, ctx, a context flag) isn't one: the measurement
346
+ replaces those."""
347
+ if asked:
348
+ return asked, "--max"
349
+ path = engine_mod.expand(str(m.get("model", "")))
350
+ if os.path.isfile(path):
351
+ try:
352
+ n = machines.read_gguf(path).get("context_length")
353
+ if n:
354
+ return n, "the model file"
355
+ except (OSError, ValueError):
356
+ pass
357
+ if m.get("max_context"):
358
+ return m["max_context"], "the model's max_context"
359
+ raise engine_mod.ModelFailed("the model's own context limit isn't known: pass --max N")
360
+
361
+
362
+ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=STEP, max_starts=MAX_STARTS):
363
+ """Measure the largest context one model can be served with here and save it. Returns the saved
364
+ measurement, or {"verified": bool, ...} for a server whose context tuieval can't set."""
365
+ m = eng.model(label)
366
+ server = eng.cfg["servers"][m["server"]]
367
+ if eng.hosted(m):
368
+ raise engine_mod.ModelFailed("it's a hosted model: its context doesn't depend on this machine")
369
+ how = engine_mod.takes_context(server)
370
+ limit_s = eng.cfg.get("tune", {}).get("ctx_request_timeout_s", REQUEST_LIMIT_S)
371
+ sv = eng.serving(m)
372
+ if not how:
373
+ ctx = m.get("max_context") or sv.ctx
374
+ if not ctx:
375
+ raise engine_mod.ModelFailed("tuieval can't set this server's context ({ctx} in its cmd, or ctx_flag), and "
376
+ "the model has no max_context to verify")
377
+ emit("tune_step", message=f"tuieval can't set this server's context: checking the {ctx:,} it declares")
378
+ r = probe(eng, m, ctx, emit, limit_s)
379
+ emit("tune_result", message=" " + r.summary(), result=r)
380
+ return {"verified": r.ok, "ctx": ctx, "probe": r}
381
+ upper, source = upper_bound(m, max_ctx)
382
+ upper = max(upper, FLOOR)
383
+ room, refuse = room_gb(eng)
384
+ if refuse:
385
+ raise engine_mod.ModelFailed(refuse)
386
+ size = model_gb(m)
387
+ if room is not None and size is not None and size > room:
388
+ raise engine_mod.ModelFailed(f"the model is {size:.1f} GB and {room:.1f} GB is free for it now: another "
389
+ "model or app is holding memory")
390
+ # Half of what it runs with now, so the second probe is a context expected to work and the two
391
+ # give the memory per token before anything larger is tried.
392
+ usual = sv.ctx if sv.fits and sv.ctx else None
393
+ first = min(upper, max(FLOOR, _grid(start or (usual // 2 if usual else FIRST))))
394
+ emit("tune_step", message=f"largest context up to {upper:,} ({source})"
395
+ + (f"; {room:.1f} GB of memory to work with" if room is not None else ""))
396
+
397
+ def try_ctx(ctx):
398
+ eng._check()
399
+ return probe(eng, m, ctx, emit, limit_s)
400
+
401
+ tried, why = search(try_ctx, first, upper, room, step, min(FLOOR, first), max_starts, emit)
402
+ passed = [p for p in tried if p.ok]
403
+ if not passed:
404
+ raise engine_mod.ModelFailed(f"no context worked ({why}); the last try: {tried[-1].error}")
405
+ best = max(passed, key=lambda p: p.ctx)
406
+ base, per, _ = predict(passed, room)
407
+ measured = {
408
+ "max_ctx": best.ctx,
409
+ "measured": {"memory_gb": best.mem_gb, "base_gb": round(base, 2) if base is not None else None,
410
+ "gb_per_1k_tokens": round(per * 1000, 4) if per is not None else None,
411
+ "prompt_tokens": best.prompt_tokens, "prompt_tps": best.pp_tps, "gen_tps": best.tg_tps,
412
+ "fill_s": best.total_s, "load_s": best.load_s, "limit_gb": round(room, 1) if room is not None else None,
413
+ "stopped": why},
414
+ "probes": {str(p.ctx): p.summary() for p in tried},
415
+ "meta": {"date": profiles.now(), "machine": sv.machine.summary, "server_version": eng.server_version(m),
416
+ "model_file": os.path.basename(str(m.get("model", ""))), "model_bytes": sv.identity.get("model_bytes"),
417
+ "kv_type": sv.kv_type, "upper_bound": upper, "upper_bound_from": source,
418
+ "fill_confirmed": best.filled, "server_starts": len(tried)},
419
+ }
420
+ path = profiles.save_context(sv.machine.id, label, measured, eng.tuning_dir)
421
+ eng._serving.clear()
422
+ shown = os.path.relpath(path, eng.root) if path.startswith(eng.root) else path
423
+ emit("tune_done", message=f"saved {shown}", profile=measured, path=path)
424
+ return measured