tuieval 0.2.0.dev162__tar.gz → 0.2.0.dev166__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.dev162 → tuieval-0.2.0.dev166}/CHANGELOG.md +2 -0
  2. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/PKG-INFO +1 -1
  3. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/models.md +3 -2
  4. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/writing-packs.md +5 -2
  5. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/_version.py +2 -2
  6. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/ctxbench.py +116 -23
  7. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/engine.py +1 -0
  8. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/insights.py +20 -11
  9. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/machines.py +35 -0
  10. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/packs.py +9 -2
  11. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/run_evals.py +2 -1
  12. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/tui.py +52 -13
  13. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/verdict.py +20 -2
  14. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/tests/test_tuieval.py +156 -2
  15. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/.gitignore +0 -0
  16. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/LICENSE +0 -0
  17. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/README.md +0 -0
  18. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/RELEASING.md +0 -0
  19. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/agent-packs.md +0 -0
  20. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/README.md +0 -0
  21. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/favicon.ico +0 -0
  22. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/readme-header.png +0 -0
  23. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/social-preview.png +0 -0
  24. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-1024.png +0 -0
  25. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-128.png +0 -0
  26. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-16.png +0 -0
  27. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-16.svg +0 -0
  28. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-256.png +0 -0
  29. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-32.png +0 -0
  30. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-48.png +0 -0
  31. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-512.png +0 -0
  32. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-64.png +0 -0
  33. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon-animated.svg +0 -0
  34. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/brand/tuieval-icon.svg +0 -0
  35. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/tui-answer-reasoning.png +0 -0
  36. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/tui-run-reasoning.png +0 -0
  37. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/docs/images/tui-setup.png +0 -0
  38. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/pyproject.toml +0 -0
  39. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/__init__.py +0 -0
  40. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/__main__.py +0 -0
  41. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/agents.py +0 -0
  42. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/builtin.toml +0 -0
  43. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/cli.py +0 -0
  44. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/client.py +0 -0
  45. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/compare.py +0 -0
  46. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/dates.py +0 -0
  47. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/doctor.py +0 -0
  48. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/export.py +0 -0
  49. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/__init__.py +0 -0
  50. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/answer.py +0 -0
  51. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/code.py +0 -0
  52. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/rag.py +0 -0
  53. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/reply.py +0 -0
  54. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/graders/tool_call.py +0 -0
  55. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/logs.py +0 -0
  56. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/onboard.py +0 -0
  57. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/profiles.py +0 -0
  58. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/pta.py +0 -0
  59. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/remove.py +0 -0
  60. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/scaffold.py +0 -0
  61. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/selftest.py +0 -0
  62. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/models.toml +0 -0
  63. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/answer/pack.toml +0 -0
  64. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/answer/system.txt +0 -0
  65. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/answer/tests.yaml +0 -0
  66. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/code/pack.toml +0 -0
  67. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/code/system.txt +0 -0
  68. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/code/tests.yaml +0 -0
  69. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/rag/pack.toml +0 -0
  70. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/rag/system.txt +0 -0
  71. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/rag/tests.yaml +0 -0
  72. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/reply/pack.toml +0 -0
  73. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/reply/system.txt +0 -0
  74. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/reply/tests.yaml +0 -0
  75. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/tool_call/pack.toml +0 -0
  76. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/tool_call/system.txt +0 -0
  77. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/tool_call/tests.yaml +0 -0
  78. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/templates/packs/tool_call/tools.yaml +0 -0
  79. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/tune.py +0 -0
  80. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/watch_proxy.py +0 -0
  81. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/workspace.py +0 -0
  82. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/src/tuieval/yamlout.py +0 -0
  83. {tuieval-0.2.0.dev162 → tuieval-0.2.0.dev166}/tests/mock_server.py +0 -0
@@ -2,6 +2,8 @@
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
+ - Sections: pack.toml `use_case` (default: the pack's `group`) is what a pack's verdict counts toward, so a section (`group`) can hold several use cases. The model list's verdict codes, the Readiness tab and Insights' best model per use case show use cases section by section in pack order, with a divider or heading per section (the Readiness tab was alphabetical).
5
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.
6
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.
7
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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tuieval
3
- Version: 0.2.0.dev162
3
+ Version: 0.2.0.dev166
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
@@ -167,9 +167,10 @@ The fit check estimates the context from the model file, and only for servers th
167
167
 
168
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.
169
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.
170
- 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.
171
172
 
172
- 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).
173
174
 
174
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.
175
176
 
@@ -27,7 +27,8 @@ Every pack has a fingerprint of what the model sees and what decides pass/fail (
27
27
 
28
28
  ```toml
29
29
  label = "Support bot" # shown in the TUI
30
- group = "Customer support" # the use case it counts toward (see below)
30
+ group = "Customer support" # the section it's listed under, and its use case unless use_case says otherwise
31
+ use_case = "Refunds" # optional: the use case its verdict counts toward (default: its group)
31
32
  description = "…"
32
33
  grader = "reply" # default grader for its tests (see Graders)
33
34
  system = "system.txt" # system prompt file (optional)
@@ -50,7 +51,9 @@ max_truncation = 0.01 # share of answers cut off by max_tokens
50
51
  min_consistency = 0.95 # share of variant groups where every variant passes
51
52
  ```
52
53
 
53
- `group` doubles as the **use case** in the readiness verdicts: all packs in a group must PASS for the use case to PASS. For example, a "Coding" use case could be a `coding` pack plus a `coding-sql` pack.
54
+ `group` is the **section** a pack is listed under, and its **use case** in the readiness verdicts unless `use_case` names another: all packs in a use case must PASS for the use case to PASS. For example, a "Coding" use case could be a `coding` pack plus a `coding-sql` pack.
55
+
56
+ Give packs a `use_case` when a section should hold several separately judged use cases. With `group = "Coding"` on all of them, `coding` and `coding-sql` (use case Coding) and `agentic-coding` (`use_case = "Agentic coding"`) are listed together, but a model that has never run the agentic pack still gets a Coding verdict. The model list, the Readiness tab and the Insights panel show use cases section by section, in pack order.
54
57
 
55
58
  `stop_early` suits packs a weak model fails quickly, like a regression set of routine cases: a run stops the pack at the first critical failure, or once the accuracy or truncation bar is out of reach even if every remaining answer passes, saves what it has (the verdict is FAIL) and moves on. It asks first the questions models have failed most often. `tuieval run --stop-early` (or **Stop a pack once it fails** in Setup) does this for every pack in the run. A later Certify fills in the rest.
56
59
 
@@ -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.dev162'
22
- __version_tuple__ = version_tuple = (0, 2, 0, 'dev162')
21
+ __version__ = version = '0.2.0.dev166'
22
+ __version_tuple__ = version_tuple = (0, 2, 0, 'dev166')
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},
@@ -2716,6 +2716,7 @@ class Engine:
2716
2716
  "model": {**{k: m.get(k) for k in ("label", "served_name", "server", "model", "tags", "vision", "mmproj")},
2717
2717
  **{k: m[k] for k in ("tools", "max_context", "thinking") if k in m}},
2718
2718
  "pack": {"name": job.pack.name, "label": job.pack.label, "group": job.pack.group,
2719
+ "use_case": job.pack.use_case,
2719
2720
  "fingerprint": job.pack.fingerprint, "tests": len(job.pack.tests),
2720
2721
  **({"max_tokens": job.pack.max_tokens} if job.pack.max_tokens else {})},
2721
2722
  "settings": job.sampling,
@@ -25,7 +25,7 @@ import statistics
25
25
 
26
26
  from rich.markup import escape as rich_escape
27
27
 
28
- from . import compare
28
+ from . import compare, verdict
29
29
 
30
30
  MIN_SHARE = 0.5 # like the PTA index: models with fewer answers than this share of the most-answered are left out
31
31
  HALF = 15 # half width of a diverging bar
@@ -140,20 +140,18 @@ def _heat(acc):
140
140
 
141
141
 
142
142
  def use_cases(rows, models, packs):
143
- """packs: {name: Pack} (for groups and question counts)."""
143
+ """packs: {name: Pack} (for use cases, their sections and question counts)."""
144
144
  title = "Best model per use case"
145
- groups = []
146
- for name, p in packs.items():
147
- if p.group not in groups:
148
- groups.append(p.group)
149
- groups = [g for g in groups if any(packs.get(r["suite"]) and packs[r["suite"]].group == g for r in rows)]
145
+ section_of = {u: sec for sec, ucs in verdict.sections(packs) for u in ucs}
146
+ uc = {name: verdict.use_case_of(p) for name, p in packs.items()}
147
+ groups = [u for u in section_of if any(uc.get(r["suite"]) == u for r in rows)]
150
148
  if not groups:
151
149
  return {"title": title, "lines": ["[dim]No results yet.[/dim]"], "actions": []}
152
- size = {g: sum(len(p.tests) for p in packs.values() if p.group == g) for g in groups}
153
- per = collections.defaultdict(lambda: collections.defaultdict(list)) # (model, group) -> test -> oks
150
+ size = {g: sum(len(p.tests) for name, p in packs.items() if uc[name] == g) for g in groups}
151
+ per = collections.defaultdict(lambda: collections.defaultdict(list)) # (model, use case) -> test -> oks
154
152
  for r in rows:
155
153
  if r["suite"] in packs:
156
- per[r["model"], packs[r["suite"]].group][r["test"]].append(r["ok"])
154
+ per[r["model"], uc[r["suite"]]][r["test"]].append(r["ok"])
157
155
  cell = {}
158
156
  for m in models:
159
157
  for g in groups:
@@ -168,7 +166,18 @@ def use_cases(rows, models, packs):
168
166
  best[g] = (sorted((m for m, a in full.items() if a == top)), sorted(full.items(), key=lambda x: -x[1]))
169
167
  w = max(len(m) for m in models)
170
168
  short = {g: (g if len(g) <= CELL - 1 else f"{groups.index(g) + 1} {g[:CELL - 4]}…") for g in groups}
171
- lines = [" " * (w + 2) + "".join(f"[b]{short[g]:<{CELL}}[/b]" for g in groups)]
169
+ spans, prev = [], None # the section names over their use cases' columns
170
+ for g in groups:
171
+ if section_of[g] != prev:
172
+ spans.append([section_of[g], 0])
173
+ prev = section_of[g]
174
+ spans[-1][1] += 1
175
+ heading = ""
176
+ for sec, n in spans:
177
+ name = sec.upper()[:n * CELL - 2]
178
+ heading += f"[b underline]{_esc(name)}[/]" + " " * (n * CELL - len(name))
179
+ lines = [" " * (w + 2) + heading]
180
+ lines.append(" " * (w + 2) + "".join(f"[b]{short[g]:<{CELL}}[/b]" for g in groups))
172
181
  for m in models:
173
182
  cells = []
174
183
  for g in groups:
@@ -307,12 +307,25 @@ def read_gguf(path):
307
307
  per_layer = [0 if r else h for h, r in zip(per_layer, recurrent)]
308
308
  elif interval > 1:
309
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
310
319
  return {
311
320
  "path": path, "bytes": os.path.getsize(path), "architecture": arch, "name": kv.get("general.name", ""),
312
321
  "layers": layers, "context_length": int(get("context_length", 0) or 0), "embedding": embd,
313
322
  "kv_heads_per_layer": per_layer, "head_dim_k": head_dim_k, "head_dim_v": head_dim_v,
314
323
  "experts": int(get("expert_count", 0) or 0), "experts_used": int(get("expert_used_count", 0) or 0),
315
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
316
329
  "mtp_layers": int(get("nextn_predict_layers", 0) or 0), # built-in draft layers (draft-mtp)
317
330
  }
318
331
 
@@ -325,6 +338,28 @@ def kv_bytes_per_token(info, kv_type="f16"):
325
338
  return sum(h * (info["head_dim_k"] + info["head_dim_v"]) * per for h in info["kv_heads_per_layer"])
326
339
 
327
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
+
328
363
  # ---------------------------------------------------------------- fit
329
364
  @dataclasses.dataclass
330
365
  class Fit:
@@ -63,6 +63,11 @@ class Pack:
63
63
  agent: str = "" # agent packs: the [agents.<name>] that runs them ("" = [defaults] agent)
64
64
  python: str = "" # agent packs: the Python the tasks and their tests run with ("" = tuieval's)
65
65
  min_context: int = 0 # context the pack needs, when its prompts don't show it (agent packs)
66
+ use_case: str = "" # what its verdict counts toward (pack.toml use_case; "" = its group). The group is
67
+ # the section it's listed under: a section can hold several use cases.
68
+
69
+ def __post_init__(self):
70
+ self.use_case = self.use_case or self.group
66
71
 
67
72
  @property
68
73
  def modules(self):
@@ -238,7 +243,8 @@ def _load_agent_pack(name, path, meta, meta_path):
238
243
  raise PackError(f"{meta_path}: min_context must be a whole number above 0, not {min_context!r}")
239
244
  gate = {"min_accuracy": 0.8, **meta.get("gate", {})}
240
245
  return Pack(name=name, path=path, label=meta.get("label", name), group=meta.get("group", "Other"),
241
- description=meta.get("description", ""), grader="agent", system="", needs=[], tools=[],
246
+ use_case=meta.get("use_case", ""), description=meta.get("description", ""), grader="agent",
247
+ system="", needs=[], tools=[],
242
248
  tests=tests, fingerprint=_task_fingerprint(tests), gate=gate, screen=int(meta.get("screen", 10)),
243
249
  certify_repeat=int(meta.get("certify", {}).get("repeat", 0)),
244
250
  stop_early=bool(meta.get("stop_early", False)), kind="agent", agent=str(meta.get("agent", "")),
@@ -323,7 +329,8 @@ def load_pack(path):
323
329
  if "max_tokens" in meta and (isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens < 1):
324
330
  raise PackError(f"{meta_path}: max_tokens must be a whole number above 0, not {max_tokens!r}")
325
331
  return Pack(name=name, path=path, label=meta.get("label", name), group=meta.get("group", "Other"),
326
- description=meta.get("description", ""), grader=meta.get("grader", "answer"),
332
+ use_case=meta.get("use_case", ""), description=meta.get("description", ""),
333
+ grader=meta.get("grader", "answer"),
327
334
  system=system, needs=list(needs), tools=tools, tests=tests,
328
335
  fingerprint=_fingerprint(system, tools, meta.get("grader", "answer"), tests, images, max_tokens),
329
336
  gate=gate, screen=int(meta.get("screen", 10)),
@@ -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")
@@ -65,7 +65,7 @@ def model_verdicts(e):
65
65
  results (when = None) or, failing that, the last recorded one (when = its date)."""
66
66
  current = verdict.readiness(e)
67
67
  last = verdict.latest(verdict.load_history(e))
68
- groups = list(dict.fromkeys(pk.group for pk in e.packs.values()))
68
+ groups = use_case_order(e)
69
69
  out = {}
70
70
  for m in e.cfg["models"]:
71
71
  label, rows = m["label"], []
@@ -82,10 +82,20 @@ def model_verdicts(e):
82
82
  VERDICT_MARK = {"PASS": "✓", "FAIL": "✗", "INCONCLUSIVE": "?"}
83
83
 
84
84
 
85
+ def use_case_order(e):
86
+ """Every use case, section by section in pack order (see verdict.sections)."""
87
+ return [u for _, ucs in verdict.sections(e.packs) for u in ucs]
88
+
89
+
90
+ def section_starts(e):
91
+ """The use cases that open a section after the first: the model list puts a divider before each."""
92
+ return {ucs[0] for _, ucs in verdict.sections(e.packs)[1:]}
93
+
94
+
85
95
  def group_codes(e):
86
96
  """{use case: short code}: its first letter, or its words' initials, or more letters, whichever
87
97
  is the shortest that keeps every code unique (Coding -> C; Demo answer, Demo code -> DA, DC)."""
88
- groups = list(dict.fromkeys(pk.group for pk in e.packs.values()))
98
+ groups = use_case_order(e)
89
99
 
90
100
  def initials(g, extra=0):
91
101
  words = g.split() or [g]
@@ -98,12 +108,15 @@ def group_codes(e):
98
108
  return {g: f"{g[:1].upper()}{i + 1}" for i, g in enumerate(groups)}
99
109
 
100
110
 
101
- def verdict_codes(rows, codes):
102
- """Compact markup, e.g. C✗ D? T✓ (colour = verdict, dim = from earlier results), one fixed
103
- column per use case so rows line up; blank where a use case has no verdict."""
111
+ def verdict_codes(rows, codes, starts=()):
112
+ """Compact markup, e.g. C✗ D? │ T✓ (colour = verdict, dim = from earlier results), one fixed
113
+ column per use case so rows line up; blank where a use case has no verdict. starts: use cases that
114
+ open a section (a divider goes before each)."""
104
115
  by_group = {g: (status, when) for g, status, when in rows}
105
116
  out = []
106
117
  for g in list(codes) + [g for g in by_group if g not in codes]:
118
+ if g in starts and out:
119
+ out.append("│")
107
120
  code = codes.get(g, g[:1].upper())
108
121
  if g not in by_group:
109
122
  out.append(" " * (len(code) + 1))
@@ -757,7 +770,7 @@ class SetupScreen(Screen):
757
770
  yield Header()
758
771
  yield Static(id="machine")
759
772
  with Horizontal(id="pickers"):
760
- with Vertical(classes="picker"):
773
+ with Vertical(classes="picker", id="packs-picker"):
761
774
  yield Label("[b]Eval packs[/b] (space to toggle · e picks tests)")
762
775
  yield SelectionList(id="suites")
763
776
  with Vertical(classes="picker"):
@@ -849,6 +862,21 @@ class SetupScreen(Screen):
849
862
  if not e.packs:
850
863
  for i, line in enumerate(NO_PACKS):
851
864
  packs.add_option(Selection(line, f"\x00nopacks:{i}", disabled=True))
865
+ self.fit_packs_panel()
866
+
867
+ def fit_packs_panel(self):
868
+ """Eval packs gets the width its longest line needs (at most 45% of the screen); the models
869
+ panel, whose lines are longer, gets the rest."""
870
+ packs = self.query_one("#suites", SelectionList)
871
+ if not self.size.width or not packs.option_count:
872
+ return
873
+ widest = max(Text.from_markup(str(packs.get_option_at_index(i).prompt)).cell_len
874
+ for i in range(packs.option_count))
875
+ need = max(widest, len("Eval packs (space to toggle · e picks tests)")) + 10 # tick box, scrollbar, padding
876
+ self.query_one("#packs-picker").styles.width = max(30, min(need, int(self.size.width * 0.45)))
877
+
878
+ def on_resize(self, event):
879
+ self.fit_packs_panel()
852
880
 
853
881
  def refresh_models(self, select=None):
854
882
  """Local models, then each hosted API's models tried so far, best verdicts first. Hidden
@@ -870,7 +898,7 @@ class SetupScreen(Screen):
870
898
  except Exception as err: # a broken results file must not hide the model list
871
899
  self.verdicts = {}
872
900
  self.app.log(f"verdicts failed: {err!r}")
873
- codes = group_codes(e)
901
+ codes, starts = group_codes(e), section_starts(e)
874
902
  self.legend_codes = codes
875
903
  n_hidden = sum(m["label"] in hidden for m in e.cfg["models"])
876
904
  self.query_one("#show-hidden", Checkbox).label = f"Show hidden ({n_hidden})"
@@ -897,7 +925,8 @@ class SetupScreen(Screen):
897
925
  (" [dim italic]hidden[/dim italic]" if label in hidden else "")
898
926
  where = "" if m.get("remote") else f" [dim]{m['server']}[/dim]{serving_badge(e, m, newcomer)}"
899
927
  rows = self.verdicts.get(label, [])
900
- vcodes = verdict_codes(rows, codes) if rows else f"[dim]{'not run':<{len(verdict_codes([], codes))}}[/dim]"
928
+ vcodes = (verdict_codes(rows, codes, starts) if rows
929
+ else f"[dim]{'not run':<{len(verdict_codes([], codes, starts))}}[/dim]")
901
930
  # a Selection shows one line only: keep it short, the detail line has the rest
902
931
  models.add_option(Selection(f"{label:<{width}} {vcodes}{flags}{where}{extra}",
903
932
  label, label in self.selected_models))
@@ -3660,9 +3689,18 @@ class ResultsScreen(Screen):
3660
3689
  short.append(" [dim]To run Certify: in Setup tick the model and pack, choose Certify, press s.[/dim]")
3661
3690
  self.query_one("#readiness-short", Static).update("\n".join(short) if table else
3662
3691
  "[dim]No verdicts yet: run something from Setup.[/dim]")
3663
- groups = sorted({g for t in table.values() for g in t})
3664
- matrix.add_columns("Model", *groups)
3665
- detail.add_columns("Model", "Use case", "Pack", "Verdict", "Answers right", "Answered", "Why")
3692
+ present = {g for t in table.values() for g in t}
3693
+ section_of = {u: sec for sec, ucs in verdict.sections(self.app.engine.packs) for u in ucs}
3694
+ groups = [u for u in use_case_order(self.app.engine) if u in present] + sorted(present - set(section_of))
3695
+ # two header lines: the section over its first use case, then the use case
3696
+ matrix.header_height = 2
3697
+ heads, prev = [], None
3698
+ for g in groups:
3699
+ sec = section_of.get(g, "")
3700
+ heads.append(Text(f"{sec.upper() if sec != prev else ''}\n{g}", style="bold"))
3701
+ prev = sec
3702
+ matrix.add_columns(Text("\nModel", style="bold"), *heads)
3703
+ detail.add_columns("Model", "Section", "Use case", "Pack", "Verdict", "Answers right", "Answered", "Why")
3666
3704
  right = collections.Counter((r["model"], r["suite"]) for r in self.rows if r["ok"])
3667
3705
  answered = collections.Counter((r["model"], r["suite"]) for r in self.rows)
3668
3706
  when = collections.defaultdict(list)
@@ -3681,11 +3719,12 @@ class ResultsScreen(Screen):
3681
3719
  for g in gs:
3682
3720
  row = lat.get(label, {}).get(g, {})
3683
3721
  lt.add_row(label, g, *[latency_cell(row.get(mid)) for mid in machine_ids])
3684
- for g, (_, packs) in gs.items():
3722
+ for g in sorted(gs, key=lambda u: groups.index(u) if u in groups else len(groups)):
3723
+ packs = gs[g][1]
3685
3724
  for name, pv in packs.items():
3686
3725
  if pv.status != "NO DATA":
3687
3726
  n = answered[(label, name)]
3688
- detail.add_row(label, g, name, f"[{style[pv.status]}]{pv.status}[/]",
3727
+ detail.add_row(label, section_of.get(g, ""), g, name, f"[{style[pv.status]}]{pv.status}[/]",
3689
3728
  f"{right[(label, name)]}/{n}" if n else "-", dates.span(when[(label, name)]),
3690
3729
  "; ".join(pv.reasons)[:160])
3691
3730
 
@@ -265,9 +265,27 @@ def latency_table(engine, labels=None, table=None, ran_on=None):
265
265
  return out
266
266
 
267
267
 
268
+ def sections(packs):
269
+ """[(section, [use case, ...])] in pack order: a section is a pack.toml `group`, a use case is a pack's
270
+ `use_case` (its group when it has none), listed in the section of its first pack."""
271
+ out, seen = {}, set()
272
+ for p in packs.values():
273
+ uc = use_case_of(p)
274
+ if uc not in seen:
275
+ seen.add(uc)
276
+ out.setdefault(p.group, []).append(uc)
277
+ return list(out.items())
278
+
279
+
280
+ def use_case_of(pack):
281
+ """A pack's use case: pack.toml use_case, or its group."""
282
+ return getattr(pack, "use_case", "") or pack.group
283
+
284
+
268
285
  def readiness(engine, labels=None, ran_on=None):
269
286
  """{label: {use_case: (verdict, {pack: verdict})}} for every model with results.
270
- A use case is a pack group (pack.toml `group`), e.g. Coding = the coding and coding-advanced packs.
287
+ A use case is a pack's `use_case` (pack.toml; its `group` when it has none), e.g. Coding = the coding and
288
+ coding-advanced packs.
271
289
  ran_on: (machine, hosted_any) judges only the answers that ran on that machine (see records)."""
272
290
  out = {}
273
291
  for m in engine.cfg["models"]:
@@ -278,7 +296,7 @@ def readiness(engine, labels=None, ran_on=None):
278
296
  recs = records(engine, m["label"], name, ran_on)
279
297
  if engine.result_status(m["label"], name) not in ("certified", "screened"):
280
298
  recs = [] # missing or outdated results don't count
281
- by_group.setdefault(pack.group, {})[name] = evaluate(pack, recs, engine.certify_repeat(pack))
299
+ by_group.setdefault(pack.use_case, {})[name] = evaluate(pack, recs, engine.certify_repeat(pack))
282
300
  groups = {g: (combine(v), v) for g, v in by_group.items()
283
301
  if any(x.status != "NO DATA" for x in v.values())}
284
302
  if groups:
@@ -2873,16 +2873,21 @@ class PackMaxTokens(unittest.TestCase):
2873
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
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)."""
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."""
2877
2878
  import struct
2878
2879
  s = lambda t: struct.pack("<Q", len(t)) + t.encode() # noqa: E731
2879
2880
  kv = [("general.architecture", 8, "qwen35"), ("qwen35.block_count", 4, 64),
2880
2881
  ("qwen35.embedding_length", 4, embedding), ("qwen35.attention.head_count", 4, 24),
2881
2882
  ("qwen35.attention.head_count_kv", 9 if isinstance(kv_heads, list) else 4, kv_heads),
2882
2883
  ("qwen35.attention.key_length", 4, 256),
2883
- ("qwen35.full_attention_interval", 4, 4), ("qwen35.nextn_predict_layers", 4, 1), *extra]
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)
2884
2886
  out = b"GGUF" + struct.pack("<IQQ", 3, 0, len(kv))
2885
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
2886
2891
  out += s(key) + struct.pack("<I", t)
2887
2892
  if t == 8:
2888
2893
  out += s(v)
@@ -3761,6 +3766,56 @@ class Insights(unittest.TestCase):
3761
3766
  self.assertEqual(p.stdout.split(), ["True", "True", "True", "True", "bad"], p.stderr[-2000:])
3762
3767
 
3763
3768
 
3769
+ class UseCaseSections(unittest.TestCase):
3770
+ """pack.toml `group` is the section a pack is listed under; `use_case` (default: the group) is what its
3771
+ verdict counts toward, so one section can hold several use cases."""
3772
+
3773
+ def test_use_case_and_sections(self):
3774
+ from tuieval import packs, verdict
3775
+ with tempfile.TemporaryDirectory() as tmp:
3776
+ spec = [("coding", "Coding", None, 1), ("agentic", "Coding", "Agentic coding", 2),
3777
+ ("trading", "Data", "Trading", 3), ("coding-max", "Coding", "Coding", 4)]
3778
+ for name, group, uc, order in spec:
3779
+ d = os.path.join(tmp, name)
3780
+ os.makedirs(d)
3781
+ write(os.path.join(d, "pack.toml"), f'label = "{name}"\ngroup = "{group}"\norder = {order}\n'
3782
+ + (f'use_case = "{uc}"\n' if uc else ""))
3783
+ write(os.path.join(d, "tests.yaml"), "- {input: hi, expected: 1}\n")
3784
+ ps = packs.load_packs(tmp)
3785
+ self.assertEqual({n: p.use_case for n, p in ps.items()},
3786
+ {"coding": "Coding", "agentic": "Agentic coding", "trading": "Trading", "coding-max": "Coding"})
3787
+ # a section's use cases in pack order; a section split by `order` is still listed once
3788
+ self.assertEqual(verdict.sections(ps), [("Coding", ["Coding", "Agentic coding"]), ("Data", ["Trading"])])
3789
+
3790
+ def test_verdict_codes_divide_sections(self):
3791
+ from rich.text import Text
3792
+ from tuieval import tui
3793
+ codes = {"Coding": "C", "Agentic coding": "A", "Trading": "T"}
3794
+ rows = [("Coding", "PASS", None), ("Trading", "FAIL", "2026-11-01")]
3795
+ text = Text.from_markup(tui.verdict_codes(rows, codes, {"Trading"})).plain
3796
+ self.assertEqual(text, "C✓ │ T✗")
3797
+ # an empty row is as wide as a full one, so the "not run" padding lines up
3798
+ self.assertEqual(len(tui.verdict_codes([], codes, {"Trading"})), len(text))
3799
+
3800
+ def test_use_case_panel_by_section(self):
3801
+ from types import SimpleNamespace
3802
+ from rich.text import Text
3803
+ from tuieval import insights
3804
+ rows = [{"model": m, "suite": s, "test": f"{s}{i}", "ok": ok, "tokens": 100, "secs": 1, "truncated": False,
3805
+ "reason": "", "severity": None, "raw": {}}
3806
+ for s in ("coding", "agentic", "trading") for i in range(4)
3807
+ for m, ok in (("a", True), ("b", i % 2 == 0))]
3808
+ ps = {"coding": SimpleNamespace(group="Coding", use_case="Coding", label="Coding", tests=[{}] * 4),
3809
+ "agentic": SimpleNamespace(group="Coding", use_case="Agentic coding", label="Agentic", tests=[{}] * 4),
3810
+ "trading": SimpleNamespace(group="Data", use_case="Trading", label="Trading", tests=[{}] * 4)}
3811
+ rows, models = insights.prepare(rows)
3812
+ p = insights.use_cases(rows, models, ps)
3813
+ lines = [Text.from_markup(l).plain for l in p["lines"]]
3814
+ self.assertTrue(lines[0].strip().startswith("CODING"), lines[0])
3815
+ self.assertIn("DATA", lines[0])
3816
+ self.assertEqual([a.split(":")[0] for a in p["actions"]], ["Coding", "Agentic coding", "Trading"])
3817
+
3818
+
3764
3819
  class ServerCrash(unittest.TestCase):
3765
3820
  """A server that crashes mid-request (the stream just ends) never judges the model: the run says the
3766
3821
  server stopped and records no answer."""
@@ -4415,6 +4470,105 @@ max_context = 8192
4415
4470
  self.assertFalse(r.ok)
4416
4471
  self.assertIn("swapped out 1024 MB", r.error)
4417
4472
 
4473
+ def test_kv_cache_grows_only_in_full_attention_layers(self):
4474
+ from tuieval import machines
4475
+ # Gemma 4 31B's shape: 60 layers, every sixth full attention (4 KV heads of 512), the rest
4476
+ # sliding windows of 1024 (16 KV heads of 256)
4477
+ swa = [(i + 1) % 6 != 0 for i in range(60)]
4478
+ info = {"kv_heads_per_layer": [16 if s else 4 for s in swa], "head_dim_k": 512, "head_dim_v": 512,
4479
+ "head_dim_k_swa": 256, "head_dim_v_swa": 256, "sliding_window": 1024, "swa_layers": swa,
4480
+ "kv_lora_rank": 0}
4481
+ grows, fixed = machines.kv_cache_split(info)
4482
+ self.assertEqual(grows, 10 * 4 * 1024 * 2) # 0.076 GB per 1,000 tokens; 0.078 measured
4483
+ self.assertEqual(fixed, 50 * 16 * 512 * 2 * (1024 + 512))
4484
+ self.assertGreater(machines.kv_bytes_per_token(info), 15 * grows) # the fit check's safe overestimate
4485
+ self.assertIsNone(machines.kv_cache_split(dict(info, swa_layers=None))) # a window, no pattern
4486
+ self.assertIsNone(machines.kv_cache_split(dict(info, kv_lora_rank=512))) # MLA
4487
+ plain = dict(info, sliding_window=0, swa_layers=None)
4488
+ self.assertEqual(machines.kv_cache_split(plain), (machines.kv_bytes_per_token(plain), 0.0))
4489
+
4490
+ def test_the_sliding_window_pattern_is_read_in_both_spellings(self):
4491
+ from tuieval import machines
4492
+ with tempfile.TemporaryDirectory() as tmp:
4493
+ flags = [(i + 1) % 4 != 0 for i in range(64)]
4494
+ fake_gguf(f"{tmp}/listed.gguf", extra=[("qwen35.attention.sliding_window", 4, 1024),
4495
+ ("qwen35.attention.sliding_window_pattern", "bools", flags),
4496
+ ("qwen35.attention.key_length_swa", 4, 128)])
4497
+ info = machines.read_gguf(f"{tmp}/listed.gguf")
4498
+ self.assertEqual((info["swa_layers"], info["head_dim_k_swa"], info["head_dim_v_swa"]), (flags, 128, 256))
4499
+ fake_gguf(f"{tmp}/every.gguf", extra=[("qwen35.attention.sliding_window", 4, 1024),
4500
+ ("qwen35.attention.sliding_window_pattern", 4, 4)])
4501
+ self.assertEqual(machines.read_gguf(f"{tmp}/every.gguf")["swa_layers"], flags)
4502
+ fake_gguf(f"{tmp}/none.gguf")
4503
+ self.assertIsNone(machines.read_gguf(f"{tmp}/none.gguf")["swa_layers"])
4504
+
4505
+ def test_search_from_an_estimate_settles_in_one_or_two_tries(self):
4506
+ # truth: 38.7 GB + 0.198 GB per 1,000 tokens against 85.3 GB, so 234,848 fit
4507
+ truth = lambda base: (lambda c: base + 0.000198 * c) # noqa: E731
4508
+ best, tried, why = self._search(234848, gb=truth(38.7), start=234496, upper=524288, limit_gb=85.3,
4509
+ estimated=(38.7, 0.000198))
4510
+ self.assertEqual((best, tried), (234496, [234496])) # the estimate was right: one try
4511
+ self.assertTrue(why.startswith("memory:"), why)
4512
+ # a cautious estimate: the first try's reading says more fits, and the second goes straight there
4513
+ best, tried, why = self._search(250880, gb=truth(35.5), start=234496, upper=524288, limit_gb=85.3,
4514
+ estimated=(38.7, 0.000198))
4515
+ self.assertEqual(tried, [234496, 250880])
4516
+ # an optimistic one: a little below it, then straight to what that reading predicts
4517
+ works = int((85.3 - 41.0) / 0.000198)
4518
+ best, tried, why = self._search(works, gb=truth(41.0), start=234496, upper=524288, limit_gb=85.3,
4519
+ estimated=(38.7, 0.000198))
4520
+ self.assertEqual(tried, [234496, 198656, 223232])
4521
+ self.assertEqual(best, 223232)
4522
+ # the model's own limit fits: one try
4523
+ best, tried, why = self._search(10**9, gb=truth(38.7), start=262144, upper=262144, limit_gb=85.3,
4524
+ estimated=(38.7, 0.000198))
4525
+ self.assertEqual((tried, why), ([262144], "reached the upper bound (262,144)"))
4526
+
4527
+ def test_an_estimate_the_readings_dont_match_is_dropped(self):
4528
+ said = []
4529
+ # the file says 0.015 GB per 1,000 tokens; this server takes 0.23 (a looped model)
4530
+ best, tried, why = self._search(276000, gb=lambda c: 21.8 + 0.00023 * c, start=1048576, upper=1048576,
4531
+ limit_gb=85.3, estimated=(26.2, 0.0000153), max_starts=12,
4532
+ emit=lambda kind, **d: said.append(d.get("message", "")))
4533
+ self.assertEqual(tried[:4], [1048576, 890880, 445440, 222208])
4534
+ self.assertEqual(sum("the model file doesn't describe this server's memory" in s for s in said), 1)
4535
+ self.assertGreaterEqual(best, 270336)
4536
+
4537
+ def test_bench_starts_at_the_estimate(self):
4538
+ from tuieval import ctxbench
4539
+ self.addCleanup(setattr, ctxbench, "room_gb", ctxbench.room_gb)
4540
+ with tempfile.TemporaryDirectory() as tmp:
4541
+ gguf = os.path.join(tmp, "m.gguf")
4542
+ fake_gguf(gguf, size=1000) # 16 full-attention layers of 4 KV heads of 256: 64 KiB per token
4543
+ mock = json.dumps([sys.executable, os.path.join(HERE, "mock_server.py"), "--port", "{port}", "--packs",
4544
+ os.path.join(tmp, "ws", "packs"), "--mode", "fixed", "--model", "{served_name}"])[1:-1]
4545
+ ws = self._workspace(tmp, f"""
4546
+ [servers.files]
4547
+ cmd = [{mock}, "--context", "{{ctx}}", "--breaks-above", "20000"]
4548
+ port = {free_port()}
4549
+ model_is_path = true
4550
+
4551
+ [[models]]
4552
+ label = "file"
4553
+ server = "files"
4554
+ model = "{gguf}"
4555
+ """)
4556
+ e = self._engine(ws)
4557
+ ctxbench.room_gb = lambda eng: (2.13, "") # 1 GB of buffers, then room for 18,432 tokens
4558
+ said = []
4559
+ got = ctxbench.bench(e, "file", lambda kind, **d: said.append(d.get("message", "")), max_ctx=65536, step=2048)
4560
+ self.assertEqual(list(got["probes"])[0], "18432")
4561
+ self.assertEqual((got["meta"]["started_from"], got["meta"]["estimated_ctx"]), ("estimate", 18513))
4562
+ self.assertTrue(any(s.startswith("estimate: ") and "about 18,513 fit in 2.1 GB" in s for s in said), said)
4563
+ self.assertEqual(got["max_ctx"], 18432)
4564
+ # --start still decides where it starts
4565
+ got = ctxbench.bench(e, "file", max_ctx=65536, start=16384, step=2048)
4566
+ self.assertEqual((list(got["probes"])[0], got["meta"]["started_from"]), ("16384", "--start"))
4567
+ # a server that isn't sized from the model file keeps the old start
4568
+ got = ctxbench.bench(e, "sized", lambda kind, **d: said.append(d.get("message", "")), max_ctx=65536, step=2048)
4569
+ self.assertEqual(got["meta"]["started_from"], "half the usual context")
4570
+ self.assertTrue(any(s.startswith("no estimate (the model isn't a GGUF file)") for s in said))
4571
+
4418
4572
  def test_tune_ctx_command(self):
4419
4573
  with tempfile.TemporaryDirectory() as tmp:
4420
4574
  ws = self._workspace(tmp)
File without changes
File without changes