tuieval 0.2.0.dev160__tar.gz → 0.2.0.dev164__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.dev160 → tuieval-0.2.0.dev164}/CHANGELOG.md +3 -0
  2. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/PKG-INFO +1 -1
  3. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/models.md +16 -2
  4. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/_version.py +2 -2
  5. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/ctxbench.py +116 -23
  6. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/engine.py +76 -4
  7. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/machines.py +52 -3
  8. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/run_evals.py +2 -1
  9. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/tune.py +6 -2
  10. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/tests/test_tuieval.py +199 -3
  11. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/.gitignore +0 -0
  12. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/LICENSE +0 -0
  13. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/README.md +0 -0
  14. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/RELEASING.md +0 -0
  15. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/agent-packs.md +0 -0
  16. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/README.md +0 -0
  17. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/favicon.ico +0 -0
  18. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/readme-header.png +0 -0
  19. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/social-preview.png +0 -0
  20. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-1024.png +0 -0
  21. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-128.png +0 -0
  22. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-16.png +0 -0
  23. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-16.svg +0 -0
  24. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-256.png +0 -0
  25. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-32.png +0 -0
  26. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-48.png +0 -0
  27. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-512.png +0 -0
  28. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-64.png +0 -0
  29. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon-animated.svg +0 -0
  30. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/brand/tuieval-icon.svg +0 -0
  31. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/tui-answer-reasoning.png +0 -0
  32. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/tui-run-reasoning.png +0 -0
  33. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/images/tui-setup.png +0 -0
  34. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/docs/writing-packs.md +0 -0
  35. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/pyproject.toml +0 -0
  36. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/__init__.py +0 -0
  37. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/__main__.py +0 -0
  38. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/agents.py +0 -0
  39. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/builtin.toml +0 -0
  40. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/cli.py +0 -0
  41. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/client.py +0 -0
  42. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/compare.py +0 -0
  43. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/dates.py +0 -0
  44. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/doctor.py +0 -0
  45. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/export.py +0 -0
  46. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/__init__.py +0 -0
  47. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/answer.py +0 -0
  48. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/code.py +0 -0
  49. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/rag.py +0 -0
  50. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/reply.py +0 -0
  51. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/graders/tool_call.py +0 -0
  52. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/insights.py +0 -0
  53. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/logs.py +0 -0
  54. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/onboard.py +0 -0
  55. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/packs.py +0 -0
  56. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/profiles.py +0 -0
  57. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/pta.py +0 -0
  58. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/remove.py +0 -0
  59. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/scaffold.py +0 -0
  60. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/selftest.py +0 -0
  61. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/models.toml +0 -0
  62. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/answer/pack.toml +0 -0
  63. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/answer/system.txt +0 -0
  64. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/answer/tests.yaml +0 -0
  65. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/code/pack.toml +0 -0
  66. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/code/system.txt +0 -0
  67. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/code/tests.yaml +0 -0
  68. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/rag/pack.toml +0 -0
  69. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/rag/system.txt +0 -0
  70. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/rag/tests.yaml +0 -0
  71. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/reply/pack.toml +0 -0
  72. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/reply/system.txt +0 -0
  73. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/reply/tests.yaml +0 -0
  74. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/tool_call/pack.toml +0 -0
  75. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/tool_call/system.txt +0 -0
  76. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/tool_call/tests.yaml +0 -0
  77. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/templates/packs/tool_call/tools.yaml +0 -0
  78. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/tui.py +0 -0
  79. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/verdict.py +0 -0
  80. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/watch_proxy.py +0 -0
  81. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/workspace.py +0 -0
  82. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/src/tuieval/yamlout.py +0 -0
  83. {tuieval-0.2.0.dev160 → tuieval-0.2.0.dev164}/tests/mock_server.py +0 -0
@@ -2,6 +2,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `tuieval tune --ctx` starts where the model file says the limit is, instead of climbing from a small context: for a GGUF on a llama.cpp-style server it estimates the largest context that fits (weights, buffers, and the KV cache per token with sliding-window layers counted as llama.cpp keeps them), tries that first, and lets the first reading predict whether more fits. Typically 1 or 2 server starts, down from 3 to 6 (Gemma 4 31B: one, at its 262,144 limit, where it took five). The estimate is dropped when a try's memory is more than 25% off it; MLA models, models larger than memory and servers that size their own memory keep the doubling search. The saved measurement records where it started (`started_from`, `estimated_ctx`).
6
+
7
+ - Drafter files: a model can name a separate drafter file (`draft = "…gguf"`), and tune options that use `{draft}` are offered only to models that have one. A server's `[servers.<name>.drafts]` table names kinds of drafter by GGUF metadata, for options that use `{draft_<kind>}`. See docs/models.md.
5
8
  - Fix: `tuieval tune --ctx` stopped early ("predicted to need more memory") on servers that fill memory to their own budget whatever the context. When the smallest context that passed already took more than the memory set aside, the prediction no longer caps the search.
6
9
  - Fix: `tuieval tune --ctx` found no working context for servers that fill memory to their own budget and run with macOS memory pressure at the warning level. When the first try reaches that level with nothing swapped, tries are judged by swapping, memory running out and critical pressure instead.
7
10
  - Fix: `tuieval tune --ctx` refused models larger than the machine's memory ("another model or app is holding memory"), which servers that read the model from disk as needed run fine. Their size on disk is no longer checked against free memory.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tuieval
3
- Version: 0.2.0.dev160
3
+ Version: 0.2.0.dev164
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
@@ -32,6 +32,7 @@ In the TUI, `a` adds a model and `m` scans your model folders. Each model is one
32
32
  | `label` | names `results/<label>/`; default: the file or repo name, lowercased. Never rename a label that has results. |
33
33
  | `served_name` | the model name sent with each request (default: the label for llama, the model id elsewhere) |
34
34
  | `vision`, `mmproj` | the model reads images; `mmproj` is llama's vision projector and implies `vision` |
35
+ | `draft` | a separate drafter file for speculative decoding. Tune options that take one are offered to this model (see [Tuning](#tuning)) |
35
36
  | `thinking = false` | run with thinking off |
36
37
  | `tags = [...]` | filter by them in the TUI and with `--tags` |
37
38
  | `sampling = {...}` | override `[sampling]` for this model |
@@ -147,6 +148,18 @@ Expect 8–15 server starts, about 20–30 minutes for a 27B model, once per mod
147
148
 
148
149
  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
150
 
151
+ **Drafter files.** A model whose speculative decoding needs a separate file names it with `draft = "~/models/…gguf"`. An option that uses `{draft}` is offered only to models whose file exists. When the flag depends on what kind of drafter the file is, name the kinds on the server by the GGUF metadata that identifies them, and use `{draft_<kind>}`: the option is offered only when the file's header has those values (a key the file doesn't have counts as `false`).
152
+
153
+ ```toml
154
+ [servers.llama.drafts]
155
+ block = {"general.architecture" = "my-drafter", "my-drafter.block" = true}
156
+
157
+ [servers.llama.tune]
158
+ spec = [[], ["--spec-type", "<the type for block drafters>", "-md", "{draft_block}"]]
159
+ ```
160
+
161
+ The first option of a knob can't take a drafter file (it's every model's default). The file's size counts in the fit check. Like the other tune flags, drafting is treated as speed-only: it isn't part of a result's fingerprint, and the tuner's answer guard drops an option that changes greedy answers too much.
162
+
150
163
 
151
164
  ## Measuring the largest context
152
165
 
@@ -154,9 +167,10 @@ The fit check estimates the context from the model file, and only for servers th
154
167
 
155
168
  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
169
  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. The next try waits until the machine has recovered, so the pressure one try leaves behind can't fail the next. Some servers fill memory to a budget of their own and run with macOS memory pressure at the warning level: when the very first try reaches it with nothing swapped out, it is tried again, and from then on a try is stopped only for swapping, memory running out or critical pressure.
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. A server that takes more than that at the smallest context and still passes sizes its own memory (it fills a budget of its own, whatever the context): the prediction doesn't cap it, and it keeps doubling until a try fails or is stopped.
170
+ 3. For a GGUF on a server tuieval sizes from the model file (one whose `cmd` takes `{ctx}`, like llama.cpp), it first works out from the file where the limit is: the weights (with an `mmproj` and `draft`), an allowance for buffers, and the KV cache per token of context, counting sliding-window layers as llama.cpp keeps them (their window only, whatever the context). The first try is at that estimate (or at the model's own limit when that fits by the estimate), so there are no small tries on the way up. A try that passes predicts from its memory reading whether a larger context fits, and the next try goes straight there; a first try that fails is followed by one 15% lower, then halving. When a try's memory is more than 25% off the estimate, the estimate is dropped and the search goes by the tries alone. There is no estimate for MLA models (a compressed cache of its own shape), sliding windows without a per-layer pattern in the file, models larger than the machine's memory, or servers that size their own memory; the output says which.
171
+ 4. Without an estimate (or with `--start N`), 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. A server that takes more than that at the smallest context and still passes sizes its own memory (it fills a budget of its own, whatever the context): the prediction doesn't cap it, and it keeps doubling until a try fails or is stopped.
158
172
 
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 (unless the model is larger than the machine's memory altogether: a server that reads its model from disk as needed is judged by the tries alone).
173
+ Expect 1 or 2 server starts from an estimate (one when the model's own limit fits), 3 to 5 without one; the largest 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 (unless the model is larger than the machine's memory altogether: a server that reads its model from disk as needed is judged by the tries alone).
160
174
 
161
175
  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
176
 
@@ -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.dev160'
22
- __version_tuple__ = version_tuple = (0, 2, 0, 'dev160')
21
+ __version__ = version = '0.2.0.dev164'
22
+ __version_tuple__ = version_tuple = (0, 2, 0, 'dev164')
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -16,18 +16,24 @@ for that fact. The probe passes when the answer is right, the server read the wh
16
16
  server that cuts long prompts short reports fewer tokens, or loses the fact), and the machine
17
17
  stayed healthy. Filling matters: some servers only take memory as the context fills.
18
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 server that already
19
+ The search runs up to the model's own limit: what models.toml caps the context at (max_ctx, ctx,
20
+ a context flag) doesn't bound it, since the measurement replaces those. It starts where the model
21
+ file says the limit is (estimate: the weights, buffers and the KV cache per token, on llama.cpp's
22
+ terms, against the memory free now), so the first try usually settles it: a try that passes
23
+ predicts from its memory reading whether a larger one fits, and one that fails is halved. Without
24
+ an estimate (a server that sizes its own memory, MLA, a model larger than memory, --start) it
25
+ starts at half the context the model runs with now and doubles. Memory grows about linearly with
26
+ the context, so two probes that passed predict the largest context that fits under the machine's
27
+ limit; no probe goes above that prediction, and a failed probe is bisected against the largest that
28
+ passed. (A server that already
24
29
  takes more than that limit at the smallest context, and passes, sizes its own memory: the
25
30
  prediction doesn't cap it, and the probes and their guard decide.) A probe is stopped at
26
31
  once, while the server loads or works, when memory pressure rises, the machine starts swapping,
27
32
  or memory runs out. (A server that reaches the warning level at the smallest context, with nothing
28
33
  swapped, fills memory to a budget of its own: for it only critical pressure counts, besides
29
34
  swapping and memory running out.) The next probe waits until the machine has recovered (pressure back to normal,
30
- the memory given back), so one probe's pressure can't fail the next. Typically 3 to 5 server starts.
35
+ the memory given back), so one probe's pressure can't fail the next. Typically 1 or 2 server starts
36
+ from an estimate, 3 to 5 without one.
31
37
 
32
38
  Memory is read off the machine, not the server's processes: available memory before the server
33
39
  starts less the lowest it falls to. Resident memory would count files a server maps and reads on
@@ -38,7 +44,9 @@ A server tuieval doesn't start, or can't set the context of, is only verified at
38
44
  model declares (max_context): one probe, nothing saved.
39
45
  """
40
46
  import dataclasses
47
+ import glob
41
48
  import os
49
+ import re
42
50
  import threading
43
51
  import time
44
52
 
@@ -50,7 +58,13 @@ from . import tune
50
58
  ANSWER_TOKENS = 1024 # room for the answer (and any thinking) in a probe
51
59
  STEP = 8192 # how close to the true maximum the search gets
52
60
  FLOOR = machines.MIN_CTX # the smallest context tried
53
- FIRST = 32768 # the first context tried for a model whose usual context isn't known
61
+ FIRST = 32768 # the first context tried for a model whose usual context isn't known (and no
62
+ # estimate); also the largest at which pressure before a pass says how a server runs
63
+ ESTIMATE_BUFFERS_GB = 1.0 # the estimate's buffers: this, plus this share of the weights. Gemma 4 31B Q8_0 with
64
+ ESTIMATE_BUFFERS_SHARE = 0.15 # its mmproj (31.5 GB) took 38.2 GB on llama.cpp before its context: 6.7 GB more,
65
+ # 1.2 of them sliding windows; this allows 5.7 GB besides those
66
+ ESTIMATE_OFF = 0.25 # a reading further than this share from the estimate means it doesn't apply
67
+ ESTIMATE_BACKOFF = 0.85 # a first try at the estimate that fails: the next is this share of it
54
68
  APART = 0.8 # memory per token is read off two probes at least this far apart (the lower one
55
69
  # at most this share of the higher): closer ones differ by less than the noise
56
70
  MAX_STARTS = 8
@@ -297,16 +311,25 @@ def memory_gb(eng, m, info, guard):
297
311
  return round(taken, 2) if taken else None
298
312
 
299
313
 
300
- def predict(passed, limit_gb):
314
+ def predict(passed, limit_gb, per_gb=None):
301
315
  """(base_gb, gb_per_token, largest context predicted to fit) from the largest context that
302
316
  passed with a memory reading and the nearest one well below it (APART). The third is None when
303
- memory doesn't grow with the context (nothing to predict) or there aren't two such readings."""
317
+ memory doesn't grow with the context (nothing to predict) or there aren't two such readings.
318
+ per_gb: the memory per token estimated from the model file. With it, one reading is enough
319
+ (and it stands in for two readings too close together to tell growth from noise), unless that
320
+ reading is less than the cache alone would take: then the estimate doesn't describe this server."""
304
321
  pts = sorted((p.ctx, p.mem_gb) for p in passed if p.mem_gb)
305
- if len(pts) < 2:
322
+ if not pts:
306
323
  return None, None, None
307
324
  c2, g2 = pts[-1]
308
- c1, g1 = next(((c, g) for c, g in reversed(pts[:-1]) if c <= APART * c2), pts[0])
309
- per = (g2 - g1) / (c2 - c1)
325
+ lower = [(c, g) for c, g in pts[:-1] if c <= APART * c2]
326
+ if lower or (len(pts) >= 2 and not per_gb):
327
+ c1, g1 = lower[-1] if lower else pts[0]
328
+ per = (g2 - g1) / (c2 - c1)
329
+ elif per_gb and g2 > per_gb * c2:
330
+ per = per_gb
331
+ else:
332
+ return None, None, None
310
333
  base = g2 - per * c2
311
334
  if per <= 0 or limit_gb is None:
312
335
  return base, max(per, 0.0), None
@@ -318,10 +341,14 @@ def _grid(n):
318
341
 
319
342
 
320
343
  def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_starts=MAX_STARTS,
321
- emit=lambda *a, **k: None):
344
+ emit=lambda *a, **k: None, estimated=None):
322
345
  """Probe contexts until the largest that works is known to within `step`. try_ctx(ctx) -> Probe.
323
- Returns (probes in the order tried, why it stopped)."""
346
+ estimated: (fixed GB, GB per token) from the model file (see estimate), so that the first try that
347
+ passes already predicts the largest context that fits. A try whose memory reading is off the
348
+ estimate by more than ESTIMATE_OFF drops it: the search goes by the tries from there. Returns
349
+ (probes in the order tried, why it stopped)."""
324
350
  tried, lo, hi, c = [], None, None, min(start, upper)
351
+ per_gb = estimated[1] if estimated else None
325
352
  why = f"{max_starts} server starts used"
326
353
  budget = limit_gb # None once the tries show it doesn't describe this server
327
354
  while len(tried) < max_starts:
@@ -334,12 +361,19 @@ def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_sta
334
361
  break
335
362
  tried.append(r)
336
363
  emit("tune_result", message=" " + r.summary(), result=r)
364
+ if per_gb and r.ok and r.mem_gb:
365
+ expected = estimated[0] + estimated[1] * c
366
+ if abs(r.mem_gb - expected) > ESTIMATE_OFF * expected:
367
+ per_gb = None
368
+ emit("tune_step", message=f" it took {r.mem_gb:.1f} GB where the estimate said {expected:.1f} GB: the "
369
+ "model file doesn't describe this server's memory, so the search goes by the "
370
+ "tries from here")
337
371
  if r.ok:
338
372
  lo = max(lo or 0, c)
339
373
  else:
340
374
  hi = min(hi or c, c)
341
- if lo is None: # nothing has worked yet: halve
342
- c = _grid(hi // 2)
375
+ if lo is None: # nothing has worked yet: halve (a first try at the estimate: a little below it)
376
+ c = _grid(hi * ESTIMATE_BACKOFF) if estimated and len(tried) == 1 else _grid(hi // 2)
343
377
  if c < floor:
344
378
  why = f"nothing from {floor:,} up worked"
345
379
  break
@@ -358,7 +392,7 @@ def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_sta
358
392
  f"{budget:.1f} GB set aside, and passed: this server sizes its own memory, so "
359
393
  "the search goes by the tries, not by predicted memory")
360
394
  budget = None
361
- _, per, fit = predict([p for p in tried if p.ok], budget)
395
+ _, per, fit = predict([p for p in tried if p.ok], budget, per_gb)
362
396
  nxt = min(upper, lo * 2) if hi is None else lo + _grid((hi - lo) / 2)
363
397
  if fit is not None and fit < nxt:
364
398
  if _grid(fit) - lo < min(step, upper - lo):
@@ -367,6 +401,8 @@ def search(try_ctx, start, upper, limit_gb=None, step=STEP, floor=FLOOR, max_sta
367
401
  f"for it ({per * 1000:.3f} GB per 1,000 tokens)")
368
402
  break
369
403
  nxt = _grid(fit)
404
+ elif per_gb and fit is not None and hi is not None and lo < _grid(fit) < hi:
405
+ nxt = _grid(fit) # the estimate's memory per token, from a reading it matched: no need to bisect
370
406
  if nxt <= lo:
371
407
  why = f"{hi:,} failed: {next(p.error for p in tried if p.ctx == hi)}" if hi else why
372
408
  break
@@ -403,6 +439,48 @@ def room_gb(eng):
403
439
  return (limit if free is None else min(limit, free - headroom)), ""
404
440
 
405
441
 
442
+ def _file_gb(path):
443
+ """A file's size with the other shards of a split GGUF (-00001-of-00003), or 0 if it is missing."""
444
+ match = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", path)
445
+ paths = glob.glob(path[:match.start()] + f"-*-of-{match.group(2)}.gguf") if match else [path]
446
+ return sum(os.path.getsize(p) for p in paths if os.path.isfile(p)) / machines.GB
447
+
448
+
449
+ def estimate(eng, m, room, kv_type=None):
450
+ """(the largest context the model file says fits in `room` GB, (fixed GB, GB per token), the
451
+ arithmetic as text), or (None, None, why not). For servers tuieval sizes from the model file (machines.fit, on
452
+ llama.cpp's terms): the weights with an mmproj and drafter, buffers (ESTIMATE_BUFFERS_GB and
453
+ ESTIMATE_BUFFERS_SHARE of the weights) and sliding windows' fixed cache, then the KV cache per token
454
+ (machines.kv_cache_split). Errs a little large on the buffers, so a first try at the estimate
455
+ usually passes and its memory reading corrects the rest."""
456
+ server = eng.cfg["servers"][m["server"]]
457
+ path = engine_mod.expand(str(m.get("model", "")))
458
+ if room is None:
459
+ return None, None, "the memory this machine has free can't be read"
460
+ if not (server.get("model_is_path") and os.path.isfile(path) and path.endswith(".gguf")):
461
+ return None, None, "the model isn't a GGUF file"
462
+ if not engine_mod.fit_check(server):
463
+ return None, None, "its server sizes its own memory"
464
+ try:
465
+ info = machines.read_gguf(path)
466
+ except (OSError, ValueError) as e:
467
+ return None, None, f"couldn't read the GGUF header ({e})"
468
+ split = machines.kv_cache_split(info, kv_type or m.get("kv_type") or server.get("kv_type") or "f16")
469
+ if not split or not split[0]:
470
+ return None, None, "the model file doesn't describe its KV cache well enough (MLA, or sliding windows without a layer pattern)"
471
+ weights = _file_gb(path) + sum(_file_gb(engine_mod.expand(m[k])) for k in ("mmproj", "draft") if m.get(k))
472
+ whole = eng.machine().gpu_limit_gb if eng.machine().discrete else eng.machine().ram_gb
473
+ if weights > whole:
474
+ return None, None, "the model is larger than this machine's memory: its server reads it from disk as needed"
475
+ fixed = weights * (1 + ESTIMATE_BUFFERS_SHARE) + ESTIMATE_BUFFERS_GB + split[1] / machines.GB
476
+ per = split[0] / machines.GB
477
+ ctx = int((room - fixed) / per)
478
+ how = (f"{weights:.1f} GB of weights, ~{fixed - weights:.1f} GB of buffers"
479
+ + (" and sliding windows" if split[1] else "") + f", {per * 1000:.3f} GB per 1,000 tokens of context: "
480
+ f"about {max(ctx, 0):,} fit in {room:.1f} GB")
481
+ return ctx, (fixed, per), how
482
+
483
+
406
484
  def upper_bound(m, asked=None):
407
485
  """(the largest context worth trying, where that number comes from): the model's own limit.
408
486
  What models.toml caps the context at (max_ctx, ctx, a context flag) isn't one: the measurement
@@ -456,12 +534,24 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
456
534
  if size is not None and size > whole:
457
535
  emit("tune_step", message=f"the model is {size:.0f} GB on disk, more than this machine's memory: its server "
458
536
  "reads it from disk as needed, so its size isn't checked against free memory")
459
- # Half of what it runs with now, so the second probe is a context expected to work and the two
460
- # give the memory per token before anything larger is tried.
461
- usual = sv.ctx if sv.fits and sv.ctx else None
462
- first = min(upper, max(FLOOR, _grid(start or (usual // 2 if usual else FIRST))))
463
537
  emit("tune_step", message=f"largest context up to {upper:,} ({source})"
464
538
  + (f"; {room:.1f} GB of memory to work with" if room is not None else ""))
539
+ # Start where the model file says the limit is, and check it there. Without an estimate: half of
540
+ # what it runs with now, so the second probe is a context expected to work and the two give the
541
+ # memory per token before anything larger is tried.
542
+ est, est_mem, how_est = estimate(eng, m, room, sv.kv_type)
543
+ if start:
544
+ first, began = _grid(start), "--start"
545
+ elif est is not None:
546
+ first, began = _grid(est), "estimate"
547
+ emit("tune_step", message=f"estimate: {how_est}; "
548
+ + ("the model's own limit fits, so that is the first try" if first >= upper else
549
+ "the first try is there" if first >= FLOOR else f"the first try is {FLOOR:,}"))
550
+ else:
551
+ usual = sv.ctx if sv.fits and sv.ctx else None
552
+ first, began = _grid(usual // 2 if usual else FIRST), "half the usual context"
553
+ emit("tune_step", message=f"no estimate ({how_est}): starting at {min(upper, max(FLOOR, first)):,} and doubling")
554
+ first = min(upper, max(FLOOR, first))
465
555
 
466
556
  baseline = None if sv.machine.discrete else machines.available_memory_gb()
467
557
 
@@ -471,9 +561,10 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
471
561
  eng._check()
472
562
  settle(eng, baseline, emit)
473
563
  r = probe(eng, m, ctx, emit, limit_s, rule["level"])
474
- if r.stopped_for == "pressure" and not rule["passed"] and rule["level"] < PRESSURE_CRITICAL:
564
+ if r.stopped_for == "pressure" and not rule["passed"] and rule["level"] < PRESSURE_CRITICAL and ctx <= FIRST:
475
565
  # Before anything has passed, at the smallest contexts: this isn't the context being too
476
566
  # large. The server fills memory to a budget of its own and runs at the warning level.
567
+ # (A first try at a large estimate that reaches it is treated as too large, and halved.)
477
568
  rule["level"] = PRESSURE_CRITICAL
478
569
  emit("tune_result", message=" " + r.summary())
479
570
  emit("tune_step", message=f" memory pressure reaches the warning level at {ctx:,} already, with nothing "
@@ -484,7 +575,8 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
484
575
  rule["passed"] = rule["passed"] or r.ok
485
576
  return r
486
577
 
487
- tried, why = search(try_ctx, first, upper, room, step, min(FLOOR, first), max_starts, emit)
578
+ tried, why = search(try_ctx, first, upper, room, step, min(FLOOR, first), max_starts, emit,
579
+ est_mem if began == "estimate" else None)
488
580
  passed = [p for p in tried if p.ok]
489
581
  if not passed:
490
582
  raise engine_mod.ModelFailed(f"no context worked ({why}); the last try: {tried[-1].error}")
@@ -501,6 +593,7 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
501
593
  "meta": {"date": profiles.now(), "machine": sv.machine.summary, "server_version": eng.server_version(m),
502
594
  "model_file": os.path.basename(str(m.get("model", ""))), "model_bytes": sv.identity.get("model_bytes"),
503
595
  "kv_type": sv.kv_type, "upper_bound": upper, "upper_bound_from": source,
596
+ "started_at": first, "started_from": began, "estimated_ctx": est,
504
597
  "fill_confirmed": best.filled, "server_starts": len(tried),
505
598
  "stops_at_pressure": "critical" if rule["level"] >= PRESSURE_CRITICAL else "warning",
506
599
  "pressure_seen": max((p.pressure or 0 for p in passed), default=0) or None},
@@ -43,6 +43,7 @@ import shutil
43
43
  import signal
44
44
  import socket
45
45
  import statistics
46
+ import string
46
47
  import subprocess
47
48
  import tempfile
48
49
  import threading
@@ -133,9 +134,53 @@ def load_config(path):
133
134
  m.setdefault("served_name", m["label"] if server.get("model_is_path") else m["model"])
134
135
  m["vision"] = bool(m.get("vision") or m.get("mmproj"))
135
136
  m.setdefault("tags", [])
137
+ for name, server in cfg["servers"].items():
138
+ check_drafts(path, name, server)
136
139
  return cfg
137
140
 
138
141
 
142
+ DRAFT_KIND_RE = re.compile(r"^[a-z0-9_]+$")
143
+
144
+
145
+ def draft_names(server):
146
+ """The drafter placeholders a server's flags can use: {draft} (the model's `draft` file,
147
+ whatever it is) and {draft_<kind>} for each kind in the server's `drafts` table."""
148
+ return ["draft"] + [f"draft_{k}" for k in server.get("drafts", {})]
149
+
150
+
151
+ def draft_fields(args):
152
+ """The drafter placeholders a list of arguments uses."""
153
+ return {name for a in args for _, name, _, _ in string.Formatter().parse(str(a))
154
+ if name and (name == "draft" or name.startswith("draft_"))}
155
+
156
+
157
+ def draft_literals(server):
158
+ """Format values that leave the drafter placeholders in place: tune options and profiles keep
159
+ them, and the path is filled in when the server starts."""
160
+ return {n: "{" + n + "}" for n in draft_names(server)}
161
+
162
+
163
+ def check_drafts(path, name, server):
164
+ """A server's `drafts` table and the drafter placeholders in its tune options."""
165
+ kinds = server.get("drafts", {})
166
+ if not isinstance(kinds, dict) or not all(isinstance(v, dict) for v in kinds.values()):
167
+ raise ConfigError(f"{path}: [servers.{name}.drafts] must map each kind to the GGUF metadata "
168
+ f"that identifies it, e.g. kind = {{\"general.architecture\" = \"...\"}}")
169
+ for kind in kinds:
170
+ if not DRAFT_KIND_RE.match(kind):
171
+ raise ConfigError(f"{path}: [servers.{name}.drafts] kind {kind!r} must be lowercase letters, digits or '_'")
172
+ known = set(draft_names(server))
173
+ for knob, options in server.get("tune", {}).items():
174
+ for i, o in enumerate(options):
175
+ used = draft_fields(o)
176
+ if used - known:
177
+ raise ConfigError(f"{path}: [servers.{name}.tune] {knob} uses {{{sorted(used - known)[0]}}}, "
178
+ f"but [servers.{name}.drafts] has no such kind")
179
+ if used and i == 0:
180
+ raise ConfigError(f"{path}: [servers.{name}.tune] {knob}: the first option is the default for "
181
+ f"every model, so it can't need a drafter file")
182
+
183
+
139
184
  def fit_check(server):
140
185
  """Whether tuieval sizes the context for this server's models from GGUF headers (machines.fit,
141
186
  which assumes llama.cpp's memory use). By default only servers whose command takes {ctx}, i.e.
@@ -290,6 +335,7 @@ class Serving:
290
335
  identity: dict # output-affecting settings, part of the results fingerprint
291
336
  profile: dict | None = None
292
337
  mtp_layers: int = 0
338
+ drafts: tuple = () # drafter placeholders this model's `draft` file fills ({draft}, {draft_<kind>})
293
339
  need_gb: float | None = None # estimated GPU memory at ctx (from the fit check); None when unknown
294
340
  ctx_source: str = "" # "measured" when ctx comes from tuieval tune --ctx on this machine
295
341
  ctx_measured: dict | None = None # that measurement (profiles.load_context), also when it's out of date
@@ -1435,6 +1481,21 @@ class Engine:
1435
1481
  vals = self.knob_values(machine)
1436
1482
  return [a.format(**vals) for opts in server.get("tune", {}).values() if opts for a in opts[0]]
1437
1483
 
1484
+ def drafts(self, m):
1485
+ """The drafter placeholders a model's `draft` file fills: {draft} when the file exists, and
1486
+ {draft_<kind>} for each kind of its server whose GGUF metadata the file has."""
1487
+ path = expand(m.get("draft", ""))
1488
+ if not path or not os.path.isfile(path):
1489
+ return ()
1490
+ names = ["draft"]
1491
+ for kind, want in self.cfg["servers"][m["server"]].get("drafts", {}).items():
1492
+ try:
1493
+ if machines.gguf_matches(path, want):
1494
+ names.append(f"draft_{kind}")
1495
+ except (OSError, ValueError):
1496
+ break # not a readable GGUF: no kind
1497
+ return tuple(names)
1498
+
1438
1499
  def serving(self, m, machine=None):
1439
1500
  """Serving for a model on this machine: context from the fit check, speed flags from its
1440
1501
  tuned profile (or the defaults), and the output-affecting identity."""
@@ -1455,16 +1516,23 @@ class Engine:
1455
1516
  if fit_check(server):
1456
1517
  mmproj = expand(m.get("mmproj", ""))
1457
1518
  extra = os.path.getsize(mmproj) if mmproj and os.path.isfile(mmproj) else 0
1519
+ draft = expand(m.get("draft", "")) # counted whether or not the tuned flags use it
1520
+ extra += os.path.getsize(draft) if draft and os.path.isfile(draft) else 0
1458
1521
  f = machines.fit(path, mc, kv_type=kv or "f16", headroom_gb=self.headroom_gb(mc), extra_bytes=extra,
1459
1522
  want_ctx=want)
1460
1523
  ctx, fits, note, need = f.max_ctx, f.fits, f.note, f.need_gb
1461
1524
  except (OSError, ValueError) as e:
1462
1525
  note = f"couldn't read the GGUF header ({e}); context not checked"
1463
1526
  profile, perf, perf_source = None, [], "n/a"
1527
+ drafts = self.drafts(m)
1464
1528
  if server.get("cmd") and (server.get("perf") or server.get("tune")):
1465
1529
  perf = list(server.get("perf", []))
1466
1530
  profile = profiles.load(mc.id, m["label"], self.tuning_dir)
1467
- if profile:
1531
+ if profile and draft_fields(profile["args"]) - set(drafts):
1532
+ # tuned with a drafter file that is gone or is another kind now: its flags can't run
1533
+ perf += self.default_knob_args(server, mc)
1534
+ perf_source = "outdated: the drafter file it was tuned with is missing or changed"
1535
+ elif profile:
1468
1536
  perf += list(profile["args"])
1469
1537
  why = profiles.stale(profile, self.server_version(m), size)
1470
1538
  perf_source = f"outdated: {why}" if why else \
@@ -1498,7 +1566,7 @@ class Engine:
1498
1566
  # resident), so both are part of what a result is valid for.
1499
1567
  identity["machine"] = mc.id
1500
1568
  identity["perf"] = perf
1501
- sv = Serving(mc, ctx, kv, fits, note, perf, perf_source, identity, profile, mtp, need,
1569
+ sv = Serving(mc, ctx, kv, fits, note, perf, perf_source, identity, profile, mtp, drafts, need,
1502
1570
  ctx_source=source, ctx_measured=measured, ctx_note=ctx_note)
1503
1571
  self._serving[key] = sv
1504
1572
  return sv
@@ -1515,7 +1583,8 @@ class Engine:
1515
1583
  ident["endpoint"], ident["quantization"] = ep.get("tag"), ep.get("quantization")
1516
1584
  return ident
1517
1585
  values = {"model": os.path.basename(m["model"]), "served_name": "<name>", "port": "<port>", "ctx": "<ctx>",
1518
- "kv_type": kv or "", "mmproj": os.path.basename(m.get("mmproj", ""))}
1586
+ "kv_type": kv or "", "mmproj": os.path.basename(m.get("mmproj", "")),
1587
+ **{n: os.path.basename(m.get("draft", "")) for n in draft_names(server)}}
1519
1588
  cmd = [a.format(**values) for a in server["cmd"]]
1520
1589
  if m.get("mmproj"):
1521
1590
  cmd += [a.format(**values) for a in server.get("vision_args", [])]
@@ -1541,7 +1610,8 @@ class Engine:
1541
1610
  port = port or server["port"]
1542
1611
  values = {"model": expand(m["model"]), "served_name": m["served_name"], "port": port,
1543
1612
  "mmproj": expand(m.get("mmproj", "")), "ctx": ctx or sv.ctx or "", "kv_type": sv.kv_type or "",
1544
- "root": self.root, **self.knob_values(sv.machine)}
1613
+ "root": self.root, **self.knob_values(sv.machine),
1614
+ **{n: expand(m.get("draft", "")) for n in draft_names(server)}}
1545
1615
  cmd = [expand(a, **values) for a in server["cmd"]]
1546
1616
  cmd += [expand(a, **values) for a in (sv.perf_args if perf_args is None else perf_args)]
1547
1617
  if m.get("mmproj"):
@@ -2046,6 +2116,8 @@ class Engine:
2046
2116
  raise ModelFailed(f"model not found: {model_path}")
2047
2117
  if m.get("mmproj") and not os.path.isfile(expand(m["mmproj"])):
2048
2118
  raise ModelFailed(f"mmproj file not found: {expand(m['mmproj'])}")
2119
+ if m.get("draft") and not os.path.isfile(expand(m["draft"])):
2120
+ raise ModelFailed(f"draft file not found: {expand(m['draft'])}")
2049
2121
  if cwd and not os.path.isdir(cwd):
2050
2122
  raise ModelFailed(f"server directory not found: {cwd}")
2051
2123
  missing = missing_program(cmd, cwd)
@@ -252,9 +252,9 @@ def _value(f, vtype, keep_arrays):
252
252
 
253
253
 
254
254
  @functools.lru_cache(maxsize=64)
255
- def read_gguf(path):
256
- """Metadata from a GGUF file's header (no tensors are read). Arrays are kept only for the
257
- per-layer attention keys; tokenizer arrays are skipped."""
255
+ def gguf_metadata(path):
256
+ """The key-value pairs of a GGUF file's header (no tensors are read). Arrays are kept only for
257
+ the per-layer attention keys; other arrays (the tokenizer's) are skipped."""
258
258
  path = os.path.expanduser(path)
259
259
  with open(path, "rb") as f:
260
260
  if f.read(4) != b"GGUF":
@@ -272,6 +272,20 @@ def read_gguf(path):
272
272
  val = _value(f, vtype, keep)
273
273
  if val is not None:
274
274
  kv[key] = val
275
+ return kv
276
+
277
+
278
+ def gguf_matches(path, want):
279
+ """Whether a GGUF file's header has these values: {"key": value, …}. A key the file doesn't
280
+ have counts as false."""
281
+ kv = gguf_metadata(path)
282
+ return all(kv.get(k, False) == v for k, v in want.items())
283
+
284
+
285
+ def read_gguf(path):
286
+ """What tuieval needs to know about a model, from its GGUF header."""
287
+ path = os.path.expanduser(path)
288
+ kv = gguf_metadata(path)
275
289
  arch = kv.get("general.architecture", "")
276
290
  get = lambda k, d=None: kv.get(f"{arch}.{k}", d) # noqa: E731
277
291
  layers = int(get("block_count", 0) or 0)
@@ -293,12 +307,25 @@ def read_gguf(path):
293
307
  per_layer = [0 if r else h for h, r in zip(per_layer, recurrent)]
294
308
  elif interval > 1:
295
309
  per_layer = [h if (i + 1) % interval == 0 else 0 for i, h in enumerate(per_layer)]
310
+ # Which layers use the sliding window: a flag per layer, or (llama.cpp's other spelling) a
311
+ # number n, where the last layer of every n is full attention. None when the file doesn't say.
312
+ pattern = get("attention.sliding_window_pattern")
313
+ if isinstance(pattern, list) and len(pattern) == len(per_layer):
314
+ swa_layers = [bool(x) for x in pattern]
315
+ elif isinstance(pattern, int) and not isinstance(pattern, bool) and pattern > 1:
316
+ swa_layers = [i % pattern < pattern - 1 for i in range(len(per_layer))]
317
+ else:
318
+ swa_layers = None
296
319
  return {
297
320
  "path": path, "bytes": os.path.getsize(path), "architecture": arch, "name": kv.get("general.name", ""),
298
321
  "layers": layers, "context_length": int(get("context_length", 0) or 0), "embedding": embd,
299
322
  "kv_heads_per_layer": per_layer, "head_dim_k": head_dim_k, "head_dim_v": head_dim_v,
300
323
  "experts": int(get("expert_count", 0) or 0), "experts_used": int(get("expert_used_count", 0) or 0),
301
324
  "sliding_window": int(get("attention.sliding_window", 0) or 0),
325
+ "swa_layers": swa_layers,
326
+ "head_dim_k_swa": int(get("attention.key_length_swa", 0) or head_dim_k),
327
+ "head_dim_v_swa": int(get("attention.value_length_swa", 0) or head_dim_v),
328
+ "kv_lora_rank": int(get("attention.kv_lora_rank", 0) or 0), # MLA: a compressed cache of its own shape
302
329
  "mtp_layers": int(get("nextn_predict_layers", 0) or 0), # built-in draft layers (draft-mtp)
303
330
  }
304
331
 
@@ -311,6 +338,28 @@ def kv_bytes_per_token(info, kv_type="f16"):
311
338
  return sum(h * (info["head_dim_k"] + info["head_dim_v"]) * per for h in info["kv_heads_per_layer"])
312
339
 
313
340
 
341
+ def kv_cache_split(info, kv_type="f16", ubatch=512):
342
+ """(bytes per token of context, fixed bytes) of llama.cpp's KV cache, counting sliding windows as
343
+ llama.cpp keeps them: a sliding-window layer holds its window (plus a batch) whatever the context,
344
+ so only full-attention layers grow with it. Checked on Gemma 4 31B: 0.076 GB per 1,000 tokens
345
+ against 0.078 measured, where kv_bytes_per_token says 1.6. None when the layout isn't known well
346
+ enough to say: a sliding window with no per-layer pattern, or MLA's compressed cache."""
347
+ if info.get("kv_lora_rank"):
348
+ return None
349
+ per = KV_BYTES.get(kv_type, 2.0)
350
+ heads = info["kv_heads_per_layer"]
351
+ full = (info["head_dim_k"] + info["head_dim_v"]) * per
352
+ if not info.get("sliding_window"):
353
+ return sum(h * full for h in heads), 0.0
354
+ swa = info.get("swa_layers")
355
+ if not swa or len(swa) != len(heads):
356
+ return None
357
+ windowed = (info.get("head_dim_k_swa", info["head_dim_k"]) + info.get("head_dim_v_swa", info["head_dim_v"])) * per
358
+ grows = sum(h * full for h, s in zip(heads, swa) if not s)
359
+ fixed = sum(h * windowed for h, s in zip(heads, swa) if s) * (info["sliding_window"] + ubatch)
360
+ return grows, fixed
361
+
362
+
314
363
  # ---------------------------------------------------------------- fit
315
364
  @dataclasses.dataclass
316
365
  class Fit:
@@ -707,7 +707,8 @@ def cmd_tune(argv):
707
707
  p.add_argument("--max", type=int, default=None, metavar="N",
708
708
  help="with --ctx: the largest context to try (default: the model's own limit)")
709
709
  p.add_argument("--start", type=int, default=None, metavar="N",
710
- help="with --ctx: the first context to try (default: half of what the model runs with now)")
710
+ help="with --ctx: the first context to try (default: the largest the model file says fits, "
711
+ "where tuieval can work that out; else half of what the model runs with now)")
711
712
  p.add_argument("--step", type=int, default=None, metavar="N",
712
713
  help="with --ctx: how close to the true maximum to get (default 8192)")
713
714
  p.add_argument("--models", default=None, help="default: the workspace's models.toml")
@@ -354,14 +354,18 @@ def similarity(texts, reference, chars=600):
354
354
  # ------------------------------------------------------------------ knobs
355
355
  def knobs(eng, m, sv=None):
356
356
  """{knob: [resolved option args, …]} for this model on this machine, with options that can't
357
- apply removed (draft-mtp on a model without MTP layers) and duplicates merged."""
357
+ apply removed (draft-mtp on a model without MTP layers, an option that takes a drafter file the
358
+ model doesn't have) and duplicates merged. Drafter placeholders stay as written: the profile
359
+ keeps them and the path is filled in when the server starts."""
358
360
  server = eng.cfg["servers"][m["server"]]
359
361
  sv = sv or eng.serving(m)
360
- vals = eng.knob_values(sv.machine)
362
+ vals = {**eng.knob_values(sv.machine), **engine_mod.draft_literals(server)}
361
363
  out = {}
362
364
  for name, options in server.get("tune", {}).items():
363
365
  seen, opts = set(), []
364
366
  for o in options:
367
+ if engine_mod.draft_fields(o) - set(sv.drafts):
368
+ continue # needs a drafter file (of a kind) this model doesn't have
365
369
  args = [a.format(**vals) for a in o]
366
370
  if sv.mtp_layers == 0 and any("draft-mtp" in a for a in args) and sv.identity.get("model_bytes"):
367
371
  continue # the GGUF was read and has no MTP layers
@@ -2870,9 +2870,11 @@ class PackMaxTokens(unittest.TestCase):
2870
2870
  self.assertIsNotNone(self.result("h", "plain"))
2871
2871
 
2872
2872
 
2873
- def fake_gguf(path, embedding=5120, size=0, kv_heads=4):
2873
+ def fake_gguf(path, embedding=5120, size=0, kv_heads=4, extra=()):
2874
2874
  """A GGUF header with just the keys machines.read_gguf reads, padded to size bytes. kv_heads: a
2875
- number, or one per layer (a list, as some GGUFs store it)."""
2875
+ number, or one per layer (a list, as some GGUFs store it). extra: more (key, type, value) pairs
2876
+ (type 8 a string, 7 a bool, 4 a uint32, "bools" an array of bools). A key in extra replaces the
2877
+ default one of that name."""
2876
2878
  import struct
2877
2879
  s = lambda t: struct.pack("<Q", len(t)) + t.encode() # noqa: E731
2878
2880
  kv = [("general.architecture", 8, "qwen35"), ("qwen35.block_count", 4, 64),
@@ -2880,13 +2882,19 @@ def fake_gguf(path, embedding=5120, size=0, kv_heads=4):
2880
2882
  ("qwen35.attention.head_count_kv", 9 if isinstance(kv_heads, list) else 4, kv_heads),
2881
2883
  ("qwen35.attention.key_length", 4, 256),
2882
2884
  ("qwen35.full_attention_interval", 4, 4), ("qwen35.nextn_predict_layers", 4, 1)]
2885
+ kv = [k for k in kv if k[0] not in {e[0] for e in extra}] + list(extra)
2883
2886
  out = b"GGUF" + struct.pack("<IQQ", 3, 0, len(kv))
2884
2887
  for key, t, v in kv:
2888
+ if t == "bools":
2889
+ out += s(key) + struct.pack("<IIQ", 9, 7, len(v)) + b"".join(struct.pack("<?", x) for x in v)
2890
+ continue
2885
2891
  out += s(key) + struct.pack("<I", t)
2886
2892
  if t == 8:
2887
2893
  out += s(v)
2888
2894
  elif t == 9: # an array of uint32
2889
2895
  out += struct.pack("<IQ", 4, len(v)) + b"".join(struct.pack("<I", x) for x in v)
2896
+ elif t == 7:
2897
+ out += struct.pack("<?", v)
2890
2898
  else:
2891
2899
  out += struct.pack("<I", v)
2892
2900
  with open(path, "wb") as f:
@@ -2993,6 +3001,95 @@ class FitCheck(unittest.TestCase):
2993
3001
  self.assertEqual(out, ["131072", "True"]) # own server: its max_context; llama: fit-checked
2994
3002
 
2995
3003
 
3004
+ class DraftFiles(unittest.TestCase):
3005
+ """A model's `draft` file: tune options that take it ({draft}, {draft_<kind>}) are offered only
3006
+ to models whose file exists and, for a kind, has the kind's GGUF metadata."""
3007
+ SERVER = """
3008
+ [servers.d]
3009
+ cmd = ["srv", "-m", "{model}", "-c", "{ctx}"]
3010
+ port = 18600
3011
+ model_is_path = true
3012
+ [servers.d.drafts]
3013
+ block = {"general.architecture" = "qwen35", "qwen35.block" = true}
3014
+ head = {"general.architecture" = "qwen35", "qwen35.block" = false}
3015
+ [servers.d.tune]
3016
+ spec = [[], ["--spec", "block", "-md", "{draft_block}"], ["--spec", "head", "-md", "{draft_head}"],
3017
+ ["--spec", "any", "-md", "{draft}"]]
3018
+ """
3019
+
3020
+ def setUp(self):
3021
+ self.tmp = tempfile.TemporaryDirectory()
3022
+ self.addCleanup(self.tmp.cleanup)
3023
+ d = self.tmp.name
3024
+ self.ws = os.path.join(d, "ws")
3025
+ tuieval(d, "init", self.ws)
3026
+ fake_gguf(f"{d}/m.gguf", size=1000)
3027
+ fake_gguf(f"{d}/block.gguf", size=500, extra=[("qwen35.block", 7, True)])
3028
+ fake_gguf(f"{d}/head.gguf", size=500) # no "block" key: counts as false
3029
+ with open(f"{d}/junk.gguf", "w") as f:
3030
+ f.write("not a GGUF")
3031
+ models = "".join(f'\n[[models]]\nlabel = "{label}"\nserver = "d"\nmodel = "{d}/m.gguf"\n{draft}'
3032
+ for label, draft in (("plain", ""), ("block", f'draft = "{d}/block.gguf"\n'),
3033
+ ("head", f'draft = "{d}/head.gguf"\n'),
3034
+ ("junk", f'draft = "{d}/junk.gguf"\n'),
3035
+ ("missing", f'draft = "{d}/gone.gguf"\n')))
3036
+ with open(os.path.join(self.ws, "models.toml"), "a") as f:
3037
+ f.write(self.SERVER + models)
3038
+
3039
+ def run_code(self, code):
3040
+ p = subprocess.run([sys.executable, "-c", "import json; from tuieval import engine, tune, profiles; "
3041
+ "e = engine.Engine(); " + code], capture_output=True, text=True,
3042
+ env=dict(os.environ, TUIEVAL_HOME=self.ws))
3043
+ self.assertEqual(p.returncode, 0, p.stderr)
3044
+ return json.loads(p.stdout)
3045
+
3046
+ def test_options_follow_the_draft_file(self):
3047
+ out = self.run_code("print(json.dumps({l: tune.knobs(e, e.model(l)).get('spec') for l in "
3048
+ "('plain', 'block', 'head', 'junk', 'missing')}))")
3049
+ block, head, any_ = (["--spec", "block", "-md", "{draft_block}"], ["--spec", "head", "-md", "{draft_head}"],
3050
+ ["--spec", "any", "-md", "{draft}"])
3051
+ self.assertEqual(out["plain"], [[]])
3052
+ self.assertEqual(out["block"], [[], block, any_])
3053
+ self.assertEqual(out["head"], [[], head, any_])
3054
+ self.assertEqual(out["junk"], [[], any_]) # not a GGUF: no kind
3055
+ self.assertEqual(out["missing"], [[]])
3056
+
3057
+ def test_the_path_is_filled_in_when_the_server_starts(self):
3058
+ out = self.run_code("m = e.model('block'); "
3059
+ "print(json.dumps(e.server_command(m, perf_args=['-md', '{draft_block}'])[0]))")
3060
+ self.assertEqual(out[-2:], ["-md", f"{self.tmp.name}/block.gguf"])
3061
+
3062
+ def test_draft_file_is_not_part_of_the_fingerprint(self):
3063
+ out = self.run_code("a, b = (e.serving(e.model(l)) for l in ('plain', 'block')); "
3064
+ "print(json.dumps([a.identity == b.identity, "
3065
+ "list(a.drafts), list(b.drafts)]))")
3066
+ self.assertEqual(out, [True, [], ["draft", "draft_block"]])
3067
+
3068
+ def test_a_profile_whose_draft_file_is_gone_falls_back_to_the_defaults(self):
3069
+ code = ("mc = e.machine().id; "
3070
+ "[profiles.save(mc, l, {'choices': {'spec': 1}, 'args': ['--spec', 'block', '-md', '{draft_block}'], "
3071
+ "'measured': {}, 'meta': {}}, e.tuning_dir) for l in ('block', 'head')]; "
3072
+ "a, b = (e.serving(e.model(l)) for l in ('block', 'head')); "
3073
+ "print(json.dumps([a.perf_args, a.perf_source, b.perf_args, b.perf_source]))")
3074
+ args, source, other_args, other_source = self.run_code(code)
3075
+ self.assertEqual((args, source), (["--spec", "block", "-md", "{draft_block}"], "tuned"))
3076
+ self.assertEqual(other_args, [])
3077
+ self.assertIn("outdated: the drafter file", other_source)
3078
+
3079
+ def test_config_errors(self):
3080
+ from tuieval import engine
3081
+ path = os.path.join(self.ws, "models.toml")
3082
+ with open(path) as f:
3083
+ base = f.read()
3084
+ for change, error in ((('spec = [[],', 'spec = [["-md", "{draft}"], [],'), "the first option is the default"),
3085
+ (('{draft_head}', '{draft_other}'), "no such kind"),
3086
+ (('block = {', 'Block = {'), "must be lowercase")):
3087
+ with open(path, "w") as f:
3088
+ f.write(base.replace(*change))
3089
+ with self.assertRaisesRegex(engine.ConfigError, error):
3090
+ engine.load_config(path)
3091
+
3092
+
2996
3093
  class WarmTune(unittest.TestCase):
2997
3094
  """tune.tune starting from a tuned model of the same family, on a fake engine whose speed is a
2998
3095
  function of the flags."""
@@ -3016,7 +3113,7 @@ class WarmTune(unittest.TestCase):
3016
3113
  "defaults": {"request_timeout_ms": 1000}},
3017
3114
  tuning_dir=f"{d}/tuning", root=d, _serving={}, starts=[])
3018
3115
  eng.model = lambda label: {**next(m for m in eng.cfg["models"] if m["label"] == label), "served_name": label}
3019
- eng.serving = lambda m: types.SimpleNamespace(fits=True, ctx=8192, machine=machine, mtp_layers=1,
3116
+ eng.serving = lambda m: types.SimpleNamespace(fits=True, ctx=8192, machine=machine, mtp_layers=1, drafts=(),
3020
3117
  identity={"model_bytes": 1000})
3021
3118
  eng.knob_values = lambda mc: {}
3022
3119
  eng.machine = lambda: machine
@@ -4323,6 +4420,105 @@ max_context = 8192
4323
4420
  self.assertFalse(r.ok)
4324
4421
  self.assertIn("swapped out 1024 MB", r.error)
4325
4422
 
4423
+ def test_kv_cache_grows_only_in_full_attention_layers(self):
4424
+ from tuieval import machines
4425
+ # Gemma 4 31B's shape: 60 layers, every sixth full attention (4 KV heads of 512), the rest
4426
+ # sliding windows of 1024 (16 KV heads of 256)
4427
+ swa = [(i + 1) % 6 != 0 for i in range(60)]
4428
+ info = {"kv_heads_per_layer": [16 if s else 4 for s in swa], "head_dim_k": 512, "head_dim_v": 512,
4429
+ "head_dim_k_swa": 256, "head_dim_v_swa": 256, "sliding_window": 1024, "swa_layers": swa,
4430
+ "kv_lora_rank": 0}
4431
+ grows, fixed = machines.kv_cache_split(info)
4432
+ self.assertEqual(grows, 10 * 4 * 1024 * 2) # 0.076 GB per 1,000 tokens; 0.078 measured
4433
+ self.assertEqual(fixed, 50 * 16 * 512 * 2 * (1024 + 512))
4434
+ self.assertGreater(machines.kv_bytes_per_token(info), 15 * grows) # the fit check's safe overestimate
4435
+ self.assertIsNone(machines.kv_cache_split(dict(info, swa_layers=None))) # a window, no pattern
4436
+ self.assertIsNone(machines.kv_cache_split(dict(info, kv_lora_rank=512))) # MLA
4437
+ plain = dict(info, sliding_window=0, swa_layers=None)
4438
+ self.assertEqual(machines.kv_cache_split(plain), (machines.kv_bytes_per_token(plain), 0.0))
4439
+
4440
+ def test_the_sliding_window_pattern_is_read_in_both_spellings(self):
4441
+ from tuieval import machines
4442
+ with tempfile.TemporaryDirectory() as tmp:
4443
+ flags = [(i + 1) % 4 != 0 for i in range(64)]
4444
+ fake_gguf(f"{tmp}/listed.gguf", extra=[("qwen35.attention.sliding_window", 4, 1024),
4445
+ ("qwen35.attention.sliding_window_pattern", "bools", flags),
4446
+ ("qwen35.attention.key_length_swa", 4, 128)])
4447
+ info = machines.read_gguf(f"{tmp}/listed.gguf")
4448
+ self.assertEqual((info["swa_layers"], info["head_dim_k_swa"], info["head_dim_v_swa"]), (flags, 128, 256))
4449
+ fake_gguf(f"{tmp}/every.gguf", extra=[("qwen35.attention.sliding_window", 4, 1024),
4450
+ ("qwen35.attention.sliding_window_pattern", 4, 4)])
4451
+ self.assertEqual(machines.read_gguf(f"{tmp}/every.gguf")["swa_layers"], flags)
4452
+ fake_gguf(f"{tmp}/none.gguf")
4453
+ self.assertIsNone(machines.read_gguf(f"{tmp}/none.gguf")["swa_layers"])
4454
+
4455
+ def test_search_from_an_estimate_settles_in_one_or_two_tries(self):
4456
+ # truth: 38.7 GB + 0.198 GB per 1,000 tokens against 85.3 GB, so 234,848 fit
4457
+ truth = lambda base: (lambda c: base + 0.000198 * c) # noqa: E731
4458
+ best, tried, why = self._search(234848, gb=truth(38.7), start=234496, upper=524288, limit_gb=85.3,
4459
+ estimated=(38.7, 0.000198))
4460
+ self.assertEqual((best, tried), (234496, [234496])) # the estimate was right: one try
4461
+ self.assertTrue(why.startswith("memory:"), why)
4462
+ # a cautious estimate: the first try's reading says more fits, and the second goes straight there
4463
+ best, tried, why = self._search(250880, gb=truth(35.5), start=234496, upper=524288, limit_gb=85.3,
4464
+ estimated=(38.7, 0.000198))
4465
+ self.assertEqual(tried, [234496, 250880])
4466
+ # an optimistic one: a little below it, then straight to what that reading predicts
4467
+ works = int((85.3 - 41.0) / 0.000198)
4468
+ best, tried, why = self._search(works, gb=truth(41.0), start=234496, upper=524288, limit_gb=85.3,
4469
+ estimated=(38.7, 0.000198))
4470
+ self.assertEqual(tried, [234496, 198656, 223232])
4471
+ self.assertEqual(best, 223232)
4472
+ # the model's own limit fits: one try
4473
+ best, tried, why = self._search(10**9, gb=truth(38.7), start=262144, upper=262144, limit_gb=85.3,
4474
+ estimated=(38.7, 0.000198))
4475
+ self.assertEqual((tried, why), ([262144], "reached the upper bound (262,144)"))
4476
+
4477
+ def test_an_estimate_the_readings_dont_match_is_dropped(self):
4478
+ said = []
4479
+ # the file says 0.015 GB per 1,000 tokens; this server takes 0.23 (a looped model)
4480
+ best, tried, why = self._search(276000, gb=lambda c: 21.8 + 0.00023 * c, start=1048576, upper=1048576,
4481
+ limit_gb=85.3, estimated=(26.2, 0.0000153), max_starts=12,
4482
+ emit=lambda kind, **d: said.append(d.get("message", "")))
4483
+ self.assertEqual(tried[:4], [1048576, 890880, 445440, 222208])
4484
+ self.assertEqual(sum("the model file doesn't describe this server's memory" in s for s in said), 1)
4485
+ self.assertGreaterEqual(best, 270336)
4486
+
4487
+ def test_bench_starts_at_the_estimate(self):
4488
+ from tuieval import ctxbench
4489
+ self.addCleanup(setattr, ctxbench, "room_gb", ctxbench.room_gb)
4490
+ with tempfile.TemporaryDirectory() as tmp:
4491
+ gguf = os.path.join(tmp, "m.gguf")
4492
+ fake_gguf(gguf, size=1000) # 16 full-attention layers of 4 KV heads of 256: 64 KiB per token
4493
+ mock = json.dumps([sys.executable, os.path.join(HERE, "mock_server.py"), "--port", "{port}", "--packs",
4494
+ os.path.join(tmp, "ws", "packs"), "--mode", "fixed", "--model", "{served_name}"])[1:-1]
4495
+ ws = self._workspace(tmp, f"""
4496
+ [servers.files]
4497
+ cmd = [{mock}, "--context", "{{ctx}}", "--breaks-above", "20000"]
4498
+ port = {free_port()}
4499
+ model_is_path = true
4500
+
4501
+ [[models]]
4502
+ label = "file"
4503
+ server = "files"
4504
+ model = "{gguf}"
4505
+ """)
4506
+ e = self._engine(ws)
4507
+ ctxbench.room_gb = lambda eng: (2.13, "") # 1 GB of buffers, then room for 18,432 tokens
4508
+ said = []
4509
+ got = ctxbench.bench(e, "file", lambda kind, **d: said.append(d.get("message", "")), max_ctx=65536, step=2048)
4510
+ self.assertEqual(list(got["probes"])[0], "18432")
4511
+ self.assertEqual((got["meta"]["started_from"], got["meta"]["estimated_ctx"]), ("estimate", 18513))
4512
+ self.assertTrue(any(s.startswith("estimate: ") and "about 18,513 fit in 2.1 GB" in s for s in said), said)
4513
+ self.assertEqual(got["max_ctx"], 18432)
4514
+ # --start still decides where it starts
4515
+ got = ctxbench.bench(e, "file", max_ctx=65536, start=16384, step=2048)
4516
+ self.assertEqual((list(got["probes"])[0], got["meta"]["started_from"]), ("16384", "--start"))
4517
+ # a server that isn't sized from the model file keeps the old start
4518
+ got = ctxbench.bench(e, "sized", lambda kind, **d: said.append(d.get("message", "")), max_ctx=65536, step=2048)
4519
+ self.assertEqual(got["meta"]["started_from"], "half the usual context")
4520
+ self.assertTrue(any(s.startswith("no estimate (the model isn't a GGUF file)") for s in said))
4521
+
4326
4522
  def test_tune_ctx_command(self):
4327
4523
  with tempfile.TemporaryDirectory() as tmp:
4328
4524
  ws = self._workspace(tmp)
File without changes
File without changes