tuieval 0.2.0.dev149__tar.gz → 0.2.0.dev152__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/CHANGELOG.md +1 -0
  2. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/PKG-INFO +1 -1
  3. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/models.md +7 -5
  4. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/_version.py +2 -2
  5. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/ctxbench.py +83 -49
  6. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/engine.py +4 -4
  7. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/machines.py +18 -2
  8. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/run_evals.py +4 -6
  9. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/tests/test_tuieval.py +74 -7
  10. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/.gitignore +0 -0
  11. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/LICENSE +0 -0
  12. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/README.md +0 -0
  13. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/RELEASING.md +0 -0
  14. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/agent-packs.md +0 -0
  15. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/README.md +0 -0
  16. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/favicon.ico +0 -0
  17. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/readme-header.png +0 -0
  18. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/social-preview.png +0 -0
  19. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-1024.png +0 -0
  20. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-128.png +0 -0
  21. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-16.png +0 -0
  22. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-16.svg +0 -0
  23. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-256.png +0 -0
  24. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-32.png +0 -0
  25. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-48.png +0 -0
  26. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-512.png +0 -0
  27. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-64.png +0 -0
  28. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon-animated.svg +0 -0
  29. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/brand/tuieval-icon.svg +0 -0
  30. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/tui-answer-reasoning.png +0 -0
  31. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/tui-run-reasoning.png +0 -0
  32. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/images/tui-setup.png +0 -0
  33. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/docs/writing-packs.md +0 -0
  34. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/pyproject.toml +0 -0
  35. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/__init__.py +0 -0
  36. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/__main__.py +0 -0
  37. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/agents.py +0 -0
  38. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/builtin.toml +0 -0
  39. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/cli.py +0 -0
  40. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/client.py +0 -0
  41. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/compare.py +0 -0
  42. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/dates.py +0 -0
  43. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/doctor.py +0 -0
  44. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/export.py +0 -0
  45. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/__init__.py +0 -0
  46. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/answer.py +0 -0
  47. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/code.py +0 -0
  48. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/rag.py +0 -0
  49. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/reply.py +0 -0
  50. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/graders/tool_call.py +0 -0
  51. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/insights.py +0 -0
  52. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/logs.py +0 -0
  53. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/onboard.py +0 -0
  54. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/packs.py +0 -0
  55. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/profiles.py +0 -0
  56. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/pta.py +0 -0
  57. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/remove.py +0 -0
  58. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/scaffold.py +0 -0
  59. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/selftest.py +0 -0
  60. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/models.toml +0 -0
  61. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/pack.toml +0 -0
  62. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/system.txt +0 -0
  63. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/answer/tests.yaml +0 -0
  64. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/pack.toml +0 -0
  65. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/system.txt +0 -0
  66. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/code/tests.yaml +0 -0
  67. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/pack.toml +0 -0
  68. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/system.txt +0 -0
  69. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/rag/tests.yaml +0 -0
  70. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/pack.toml +0 -0
  71. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/system.txt +0 -0
  72. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/reply/tests.yaml +0 -0
  73. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/pack.toml +0 -0
  74. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/system.txt +0 -0
  75. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/tests.yaml +0 -0
  76. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/templates/packs/tool_call/tools.yaml +0 -0
  77. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/tui.py +0 -0
  78. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/tune.py +0 -0
  79. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/verdict.py +0 -0
  80. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/watch_proxy.py +0 -0
  81. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/workspace.py +0 -0
  82. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/src/tuieval/yamlout.py +0 -0
  83. {tuieval-0.2.0.dev149 → tuieval-0.2.0.dev152}/tests/mock_server.py +0 -0
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `tuieval tune --ctx`: the measured context governs the caps in `models.toml` (`max_ctx`, a model's `ctx`, a context flag), not the other way around: the search runs up to the model's own limit, and runs use what was measured even above a cap. It starts at half the model's current context, and a try is also stopped while the server loads. Memory is measured as what the machine loses while the server runs (on a Mac from `vm_stat` page counts, not the rounded free percentage), so memory-mapped files a server reads on demand no longer count against it.
5
6
  - `tuieval tune <model> --ctx` measures the largest context a model can be served with on this machine, for any server tuieval starts: it fills each context it tries and checks the answer, the tokens the server read, memory pressure and swapping. Runs then use the measured context in place of the fit check's estimate (`tuning/<machine>/<model>.ctx.toml`; `tuieval machines` shows *measured*). See docs/models.md.
6
7
  - Results from more than one machine: a **Machine** dropdown in Results keeps only the answers that ran on one machine, in every tab (hosted models' answers count from any machine unless **Hosted from any machine** is unticked). `--ran-on <id>` (and `--ran-on-strict`) on `tuieval pta`, `compare`, `verdict`, `report` and `insights`.
7
8
  - Fix: the PTA index's Score ≥ filter did nothing once a pack was picked; it now filters the models that answered the pack (models picked by hand are still always shown).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tuieval
3
- Version: 0.2.0.dev149
3
+ Version: 0.2.0.dev152
4
4
  Summary: Evaluate local and frontier LLMs on your own questions: accuracy, speed, tokens and PASS/FAIL verdicts, in the terminal.
5
5
  Project-URL: Homepage, https://github.com/ashe-wb/tuieval
6
6
  Project-URL: Issues, https://github.com/ashe-wb/tuieval/issues
@@ -153,14 +153,16 @@ The knobs are `[servers.<name>.tune]` in `models.toml`: each knob is a list of o
153
153
  The fit check estimates the context from the model file, and only for servers that use memory the way llama.cpp does. `tuieval tune <model> --ctx` measures it instead, the same way for any server tuieval starts:
154
154
 
155
155
  1. It starts the server with a context, sends a built-in document that fills it (sized from the token counts the server reports, so any tokenizer works) with one fact near the start, and asks for that fact.
156
- 2. The try passes when the answer is right, the server read the whole document (a server that cuts long prompts short fails here), and the machine stayed healthy: no macOS memory pressure, no swapping, memory left on Linux. A try is stopped the moment one of those turns bad.
157
- 3. It starts at a quarter of the upper bound and doubles. Memory grows about linearly with the context, so two tries that passed predict the largest context that fits in the machine's memory (less `memory_headroom_gb`, and less whatever other apps hold now); no try goes above the prediction, and a failed try is bisected against the largest that passed.
156
+ 2. The try passes when the answer is right, the server read the whole document (a server that cuts long prompts short fails here), and the machine stayed healthy: no macOS memory pressure, no swapping, memory left on Linux. A try is stopped the moment one of those turns bad, also while the server is still loading.
157
+ 3. It starts at half the context the model runs with now (32768 when that isn't known) and doubles. Memory grows about linearly with the context, so two tries that passed predict the largest context that fits in the machine's memory (less `memory_headroom_gb`, and less whatever other apps hold now); no try goes above the prediction, and a failed try is bisected against the largest that passed.
158
158
 
159
159
  Expect 3 to 5 server starts; the largest ones take as long as the server needs to read that many tokens. It won't start when memory pressure is already elevated or the model is larger than the memory free now.
160
160
 
161
- The upper bound is `--max N`, else the smallest of the server's `max_ctx`, the model's `ctx` or `max_context` and a context flag written in `models.toml`, else the model file's own limit. `--start N` sets the first context tried, `--step N` how close to the true maximum to get (default 8192).
161
+ Memory is read off the machine, not the server's processes: the memory available before the server starts, less the lowest it falls to while the context is full (VRAM on discrete GPUs). On a Mac, available memory is RAM less what is held and can't be given back (anonymous and wired pages and the compressor, from `vm_stat`), so files a server maps and reads on demand don't count against it, and the reading is in the same terms as the memory it is compared with.
162
162
 
163
- The result is saved in `tuning/<machine>/<model>.ctx.toml`: the context, the memory with it full, the memory per 1,000 tokens and every try. Runs on that machine then use it in place of the estimate; your own caps still apply, so raise `max_ctx` if the measured context is above it. `tuieval machines` marks it *measured*. Delete the file to go back to the estimate; a measurement made with another model file or KV type is ignored.
163
+ The upper bound is the model's own limit: `--max N`, else the context length in the model file, else the model's `max_context`. What `models.toml` caps the context at (`max_ctx`, a model's `ctx`, a context flag in `server_args`) doesn't bound the search. `--start N` sets the first context tried, `--step N` how close to the true maximum to get (default 8192).
164
+
165
+ The result is saved in `tuning/<machine>/<model>.ctx.toml`: the context, the memory with it full, the memory per 1,000 tokens and every try. Runs on that machine then use it as the model's context, in place of the estimate and of the caps in `models.toml`: those were written without the measurement, so it governs them, also when it is larger. `tuieval machines` marks it *measured*. To hold a model below its maximum, lower the `max_ctx` line in that `.ctx.toml` file; delete the file to go back to the estimate and the caps. Also, a measurement made with another model file or KV type is ignored.
164
166
 
165
167
  tuieval sets the context through `{ctx}` in the server's `cmd`, or through its `ctx_flag`. For a server with neither (one already running, or one that sizes itself), `--ctx` only checks the `max_context` its model declares, with one try, and saves nothing.
166
168
 
@@ -201,7 +203,7 @@ On Apple Silicon Macs, once the system's GPU allocations pass about half of RAM,
201
203
  | `model_is_path` | `model` is a file or folder: check it exists before starting |
202
204
  | `fit_check` | size the context from the GGUF header and skip models that don't fit (the fit check; it assumes llama.cpp's memory use). Default: on for servers whose `cmd` takes `{ctx}`, off for others, whose context is the model's `max_context` |
203
205
  | `vision_args` | flags appended for models with `mmproj` |
204
- | `kv_type`, `max_ctx` | llama defaults: KV-cache type, upper bound on context |
206
+ | `kv_type`, `max_ctx` | llama defaults: KV-cache type, upper bound on context (until a model's context is measured with `tuieval tune --ctx`) |
205
207
  | `ctx_flag` | the server's context flag (e.g. `--max-context`), for servers whose `cmd` doesn't take `{ctx}`: long packs are skipped if a configured context is too small, and `tuieval tune --ctx` sets it to measure the largest context |
206
208
  | `request` | fields added to every request (e.g. `{ cache_prompt = false }`) |
207
209
  | `perf` | speed-only flags always applied |
@@ -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.dev149'
22
- __version_tuple__ = version_tuple = (0, 2, 0, 'dev149')
21
+ __version__ = version = '0.2.0.dev152'
22
+ __version_tuple__ = version_tuple = (0, 2, 0, 'dev152')
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -7,8 +7,8 @@ It works the same for every server tuieval starts, because it only uses what the
7
7
 
8
8
  the context set through {ctx} in the server's cmd, or its ctx_flag
9
9
  the API one chat request per try, and the token counts the server reports
10
- the machine the server's memory (its processes' resident memory; VRAM on discrete GPUs),
11
- macOS memory pressure and swapping, memory available on Linux
10
+ the machine the memory the server takes (how much less is available while it runs; VRAM on
11
+ discrete GPUs), macOS memory pressure and swapping
12
12
 
13
13
  One try ("probe") at a context: start the server with it, send a document that fills it (sized
14
14
  from the server's own token counts, so any tokenizer works) with one fact near the start, and ask
@@ -16,11 +16,18 @@ 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 small and doubles. Memory grows about linearly with the context, so two probes
20
- that passed predict the largest context that fits under the machine's limit; no probe goes above
21
- that prediction, and a failed probe is bisected against the largest that passed. A probe is
22
- stopped at once when memory pressure rises, the machine starts swapping, or (Linux) memory runs
23
- out. Typically 3 to 5 server starts.
19
+ The search starts at half the context the model runs with now and doubles, up to the model's own
20
+ limit: what models.toml caps the context at (max_ctx, ctx, a context flag) doesn't bound it, since
21
+ the measurement replaces those. Memory grows about linearly with the context, so two probes that
22
+ passed predict the largest context that fits under the machine's limit; no probe goes above that
23
+ prediction, and a failed probe is bisected against the largest that passed. A probe is stopped at
24
+ once, while the server loads or works, when memory pressure rises, the machine starts swapping,
25
+ or memory runs out. Typically 3 to 5 server starts.
26
+
27
+ Memory is read off the machine, not the server's processes: available memory before the server
28
+ starts less the lowest it falls to. Resident memory would count files a server maps and reads on
29
+ demand, which the system can drop again, and that reading is what is compared with the memory
30
+ available, so both are in the same terms.
24
31
 
25
32
  A server tuieval doesn't start, or can't set the context of, is only verified at the context its
26
33
  model declares (max_context): one probe, nothing saved.
@@ -37,11 +44,16 @@ from . import tune
37
44
  ANSWER_TOKENS = 1024 # room for the answer (and any thinking) in a probe
38
45
  STEP = 8192 # how close to the true maximum the search gets
39
46
  FLOOR = machines.MIN_CTX # the smallest context tried
47
+ FIRST = 32768 # the first context tried for a model whose usual context isn't known
48
+ APART = 0.8 # memory per token is read off two probes at least this far apart (the lower one
49
+ # at most this share of the higher): closer ones differ by less than the noise
40
50
  MAX_STARTS = 8
41
51
  REQUEST_LIMIT_S = 3600 # reading a few hundred thousand tokens takes a while ([tune] ctx_request_timeout_s)
42
52
  PRESSURE_WARNING = 2 # macOS memory pressure level that stops a probe (1 is normal)
43
53
  SWAP_STOP_MB = 512 # swapped out while a probe ran: stop it
44
- AVAILABLE_STOP_GB = 1.0 # Linux: memory available under this stops a probe
54
+ AVAILABLE_STOP_GB = 1.0 # memory available under this stops a probe
55
+ TOO_LITTLE = 0.5 # a reading under this share of the model's size on disk can't be right for a server
56
+ # that holds the model in memory: its resident memory is used instead
45
57
  SAMPLE_CHARS = 12000 # the request that measures the server's characters per token
46
58
  UNKNOWN_CHARS_PER_TOKEN = 3.0 # for a server that reports no token counts: short of full rather than over
47
59
  NOT_ABOUT_CONTEXT = ("already in use", "isn't installed", "not found", "is not set", "skipped by user")
@@ -119,13 +131,15 @@ def too_long(error):
119
131
 
120
132
 
121
133
  class Guard:
122
- """Watches the machine while a probe runs and stops the request when it gets unhealthy."""
134
+ """Watches the machine while a probe's server loads and works. When it gets unhealthy, the
135
+ server is stopped: a load is abandoned and a request is cut off."""
123
136
 
124
137
  def __init__(self, eng, every_s=2.0):
125
138
  self.eng, self.every_s, self.reason = eng, every_s, ""
126
139
  self.pressure, self._stop = machines.memory_pressure_level(), threading.Event()
127
140
  self._swap0 = machines.swapped_out_bytes()
128
- self._linux = self.pressure is None and not eng.machine().discrete
141
+ self._own_memory = eng.machine().discrete # VRAM: the machine's memory isn't what runs out
142
+ self.available0 = self.lowest = None if self._own_memory else machines.available_memory_gb()
129
143
 
130
144
  def __enter__(self):
131
145
  self._thread = threading.Thread(target=self._run, daemon=True)
@@ -141,16 +155,25 @@ class Guard:
141
155
  swap = machines.swapped_out_bytes()
142
156
  if None not in (swap, self._swap0) and (swap - self._swap0) / 2**20 > SWAP_STOP_MB:
143
157
  return f"the machine swapped out {(swap - self._swap0) / 2**20:.0f} MB"
144
- if self._linux:
158
+ if not self._own_memory:
145
159
  free = machines.available_memory_gb()
146
- if free is not None and free < AVAILABLE_STOP_GB:
147
- return f"only {free:.1f} GB of memory was left"
160
+ if free is not None:
161
+ self.lowest = free if self.lowest is None else min(self.lowest, free)
162
+ if free < AVAILABLE_STOP_GB:
163
+ return f"only {free:.1f} GB of memory was left"
148
164
  return ""
149
165
 
166
+ def taken_gb(self):
167
+ """Memory the machine lost while the block ran (None where it can't be read)."""
168
+ if None in (self.available0, self.lowest):
169
+ return None
170
+ return max(self.available0 - self.lowest, 0.0)
171
+
150
172
  def _run(self):
151
173
  while not self._stop.wait(self.every_s):
152
174
  self.reason = self.reason or self.check()
153
175
  if self.reason:
176
+ self.eng._stall = self.reason # ends the wait for a server that is still loading
154
177
  stream = getattr(self.eng, "_stream", None)
155
178
  if stream is not None:
156
179
  stream.close()
@@ -160,6 +183,7 @@ class Guard:
160
183
  self._stop.set()
161
184
  self._thread.join(self.every_s + 1)
162
185
  self.reason = self.reason or self.check()
186
+ self.eng._stall = None
163
187
 
164
188
 
165
189
  def probe(eng, m, ctx, emit=lambda *a, **k: None, limit=REQUEST_LIMIT_S):
@@ -171,28 +195,25 @@ def probe(eng, m, ctx, emit=lambda *a, **k: None, limit=REQUEST_LIMIT_S):
171
195
  if target < 1024:
172
196
  out.error = f"a context of {ctx:,} is too small to test"
173
197
  return out
198
+ guard = Guard(eng)
174
199
  try:
175
- with eng.serve(m, log_name=f"{m['label']}.ctx", ctx=ctx) as (url, info):
200
+ with guard, eng.serve(m, log_name=f"{m['label']}.ctx", ctx=ctx) as (url, info):
176
201
  out.load_s = round(info["load_s"], 1) if info.get("load_s") else None
177
- with Guard(eng) as guard:
178
- ratio = chars_per_token(eng, m, url, emit, limit)
179
- chars = int(target * (ratio or UNKNOWN_CHARS_PER_TOKEN) * 0.98)
180
- emit("tune_progress", message=f" filling the context: ~{target:,} tokens, {chars:,} characters"
181
- + ("" if ratio else " (the server reports no token counts)"))
182
- res = _ask(eng, m, url, chars, ANSWER_TOKENS, "fill", emit, limit)
183
- if too_long(res.get("error")) and not guard.reason:
184
- emit("tune_progress", message=" the server found that too long; trying 7% shorter")
185
- res = _ask(eng, m, url, int(chars * 0.93), ANSWER_TOKENS, "fill", emit, limit)
202
+ ratio = chars_per_token(eng, m, url, emit, limit)
203
+ chars = int(target * (ratio or UNKNOWN_CHARS_PER_TOKEN) * 0.98)
204
+ emit("tune_progress", message=f" filling the context: ~{target:,} tokens, {chars:,} characters"
205
+ + ("" if ratio else " (the server reports no token counts)"))
206
+ res = _ask(eng, m, url, chars, ANSWER_TOKENS, "fill", emit, limit)
207
+ if too_long(res.get("error")) and not guard.reason:
208
+ emit("tune_progress", message=" the server found that too long; trying 7% shorter")
209
+ res = _ask(eng, m, url, int(chars * 0.93), ANSWER_TOKENS, "fill", emit, limit)
186
210
  met = client.metrics(res) if not res.get("error") else {}
187
211
  out.prompt_tokens, out.pp_tps, out.tg_tps = met.get("prompt_tokens"), met.get("prompt_tps"), met.get("gen_tps")
188
212
  out.total_s = round(res["total_s"], 1) if res.get("total_s") else None
189
- peak = info.get("vram_peak_gb") if eng.machine().discrete else \
190
- (info["peak_mb"]() or 0) / 1024 if info.get("peak_mb") else None
191
- out.mem_gb = round(peak, 2) if peak else None
213
+ guard.check()
214
+ out.mem_gb = memory_gb(eng, m, info, guard)
192
215
  text = (res.get("answer") or "") + (res.get("reasoning") or "")
193
- if guard.reason:
194
- out.error = guard.reason
195
- elif res.get("error"):
216
+ if res.get("error"):
196
217
  out.error = res["error"]
197
218
  elif not info["alive"]():
198
219
  out.error = "the server stopped"
@@ -206,20 +227,36 @@ def probe(eng, m, ctx, emit=lambda *a, **k: None, limit=REQUEST_LIMIT_S):
206
227
  out.filled = bool(ratio and out.prompt_tokens and out.prompt_tokens >= 0.85 * target)
207
228
  except engine_mod.ModelFailed as e:
208
229
  out.error = str(e).splitlines()[0]
209
- if any(w in out.error for w in NOT_ABOUT_CONTEXT):
230
+ if not guard.reason and any(w in out.error for w in NOT_ABOUT_CONTEXT):
210
231
  raise # a smaller context wouldn't help
232
+ if guard.reason: # the machine got unhealthy: that is why, whatever the server said as it was stopped
233
+ out.ok, out.error = False, guard.reason
211
234
  return out
212
235
 
213
236
 
214
237
  # ------------------------------------------------------------------ the search
238
+ def memory_gb(eng, m, info, guard):
239
+ """What the server took with its context full: VRAM on a discrete GPU, else how much less memory
240
+ the machine had available, else (where that can't be read, or reads implausibly low for a model
241
+ of this size) the resident memory of the server's processes."""
242
+ if eng.machine().discrete:
243
+ return round(info["vram_peak_gb"], 2) if info.get("vram_peak_gb") else None
244
+ taken, size = guard.taken_gb(), model_gb(m)
245
+ resident = (info["peak_mb"]() or 0) / 1024 if info.get("peak_mb") else 0
246
+ if not taken or (size and taken < TOO_LITTLE * size <= resident):
247
+ taken = resident
248
+ return round(taken, 2) if taken else None
249
+
250
+
215
251
  def predict(passed, limit_gb):
216
- """(base_gb, gb_per_token, largest context predicted to fit) from the two largest contexts that
217
- passed with a memory reading. The third is None when memory doesn't grow with the context
218
- (nothing to predict) or there aren't two readings."""
252
+ """(base_gb, gb_per_token, largest context predicted to fit) from the largest context that
253
+ passed with a memory reading and the nearest one well below it (APART). The third is None when
254
+ memory doesn't grow with the context (nothing to predict) or there aren't two such readings."""
219
255
  pts = sorted((p.ctx, p.mem_gb) for p in passed if p.mem_gb)
220
256
  if len(pts) < 2:
221
257
  return None, None, None
222
- (c1, g1), (c2, g2) = pts[-2:]
258
+ c2, g2 = pts[-1]
259
+ c1, g1 = next(((c, g) for c, g in reversed(pts[:-1]) if c <= APART * c2), pts[0])
223
260
  per = (g2 - g1) / (c2 - c1)
224
261
  base = g2 - per * c2
225
262
  if per <= 0 or limit_gb is None:
@@ -303,20 +340,12 @@ def room_gb(eng):
303
340
  return (limit if free is None else min(limit, free - headroom)), ""
304
341
 
305
342
 
306
- def upper_bound(eng, m, server, how, asked=None):
307
- """(the largest context worth trying, where that number comes from)."""
343
+ def upper_bound(m, asked=None):
344
+ """(the largest context worth trying, where that number comes from): the model's own limit.
345
+ What models.toml caps the context at (max_ctx, ctx, a context flag) isn't one: the measurement
346
+ replaces those."""
308
347
  if asked:
309
348
  return asked, "--max"
310
- caps = [(server.get("max_ctx"), f"max_ctx in [servers.{m['server']}]"), (m.get("ctx"), "the model's ctx"),
311
- (m.get("max_context"), "the model's max_context")]
312
- caps = [(v, src) for v, src in caps if v]
313
- if how == "flag":
314
- sv = eng.serving(m)
315
- written = engine_mod.read_context(list(m.get("server_args", [])) + list(sv.perf_args), server["ctx_flag"])
316
- if written:
317
- caps.append((written, f"{server['ctx_flag']} in models.toml"))
318
- if caps:
319
- return min(caps)
320
349
  path = engine_mod.expand(str(m.get("model", "")))
321
350
  if os.path.isfile(path):
322
351
  try:
@@ -325,7 +354,9 @@ def upper_bound(eng, m, server, how, asked=None):
325
354
  return n, "the model file"
326
355
  except (OSError, ValueError):
327
356
  pass
328
- raise engine_mod.ModelFailed("no upper bound for its context is known: pass --max N (the model's own limit)")
357
+ if m.get("max_context"):
358
+ return m["max_context"], "the model's max_context"
359
+ raise engine_mod.ModelFailed("the model's own context limit isn't known: pass --max N")
329
360
 
330
361
 
331
362
  def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=STEP, max_starts=MAX_STARTS):
@@ -347,7 +378,7 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
347
378
  r = probe(eng, m, ctx, emit, limit_s)
348
379
  emit("tune_result", message=" " + r.summary(), result=r)
349
380
  return {"verified": r.ok, "ctx": ctx, "probe": r}
350
- upper, source = upper_bound(eng, m, server, how, max_ctx)
381
+ upper, source = upper_bound(m, max_ctx)
351
382
  upper = max(upper, FLOOR)
352
383
  room, refuse = room_gb(eng)
353
384
  if refuse:
@@ -356,7 +387,10 @@ def bench(eng, label, emit=lambda *a, **k: None, max_ctx=None, start=None, step=
356
387
  if room is not None and size is not None and size > room:
357
388
  raise engine_mod.ModelFailed(f"the model is {size:.1f} GB and {room:.1f} GB is free for it now: another "
358
389
  "model or app is holding memory")
359
- first = min(upper, max(FLOOR, _grid(start or upper // 4)))
390
+ # Half of what it runs with now, so the second probe is a context expected to work and the two
391
+ # give the memory per token before anything larger is tried.
392
+ usual = sv.ctx if sv.fits and sv.ctx else None
393
+ first = min(upper, max(FLOOR, _grid(start or (usual // 2 if usual else FIRST))))
360
394
  emit("tune_step", message=f"largest context up to {upper:,} ({source})"
361
395
  + (f"; {room:.1f} GB of memory to work with" if room is not None else ""))
362
396
 
@@ -1475,8 +1475,9 @@ class Engine:
1475
1475
  flag = server.get("ctx_flag") # e.g. --max-context-tokens, when the server takes one
1476
1476
  if flag and ctx is None:
1477
1477
  ctx = read_context(list(m.get("server_args", [])) + perf, flag)
1478
- # The largest context measured here (tuieval tune --ctx) replaces the estimate. Your own caps
1479
- # (max_ctx, ctx, max_context, a context flag you wrote) still apply.
1478
+ # The largest context measured here (tuieval tune --ctx) is the context: it replaces the estimate
1479
+ # and whatever models.toml caps it at (max_ctx, ctx, max_context, a context flag), which were
1480
+ # written without knowing it.
1480
1481
  how, source, ctx_note = takes_context(server), "", ""
1481
1482
  measured = profiles.load_context(mc.id, m["label"], self.tuning_dir) if how else None
1482
1483
  if measured:
@@ -1486,8 +1487,7 @@ class Engine:
1486
1487
  elif meta.get("kv_type") and kv and meta["kv_type"] != kv:
1487
1488
  ctx_note = f"its context was measured with {meta['kv_type']} KV, not {kv}; run tuieval tune --ctx again"
1488
1489
  else:
1489
- cap = want if how == "placeholder" else ctx
1490
- ctx, fits, source = min(cap, measured["max_ctx"]) if cap else measured["max_ctx"], True, "measured"
1490
+ ctx, fits, source = measured["max_ctx"], True, "measured"
1491
1491
  note = f"measured on {mc.id}: up to {measured['max_ctx'] // 1024}k context"
1492
1492
  at = measured.get("measured", {})
1493
1493
  if at.get("base_gb") is not None and at.get("gb_per_1k_tokens") is not None:
@@ -356,15 +356,31 @@ def swapped_out_bytes():
356
356
  return int(page.group(1)) * int(swaps.group(1)) if page and swaps else None
357
357
 
358
358
 
359
+ def vm_stat_available_gb(text, ram_bytes):
360
+ """Memory available on a Mac from vm_stat's page counts: RAM less what is held and can't be
361
+ given back (anonymous pages, wired pages, the compressor's own pages). File cache and
362
+ memory-mapped files the system can drop count as available. None if the counts aren't there."""
363
+ page = re.search(r"page size of (\d+)", text)
364
+ held = [re.search(name + r":\s+(\d+)", text) for name in
365
+ ("Anonymous pages", "Pages wired down", "Pages occupied by compressor")]
366
+ if not page or not all(held) or not ram_bytes:
367
+ return None
368
+ return (ram_bytes - int(page.group(1)) * sum(int(h.group(1)) for h in held)) / GB
369
+
370
+
359
371
  def available_memory_gb():
360
372
  """Memory a new process could take now without pushing anything to swap: free plus what the
361
- system gives back on demand (file cache). macOS: `memory_pressure`'s free percentage of RAM;
373
+ system gives back on demand (file cache). macOS: from vm_stat's page counts (`memory_pressure`'s
374
+ free percentage, which is rounded to 1% of RAM and reads higher, only if they are missing);
362
375
  Linux: MemAvailable. None where unknown."""
363
376
  try:
364
377
  if platform.system() == "Darwin":
378
+ ram = int(_sysctl("hw.memsize") or 0)
379
+ got = vm_stat_available_gb(subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=5).stdout, ram)
380
+ if got is not None:
381
+ return got
365
382
  out = subprocess.run(["memory_pressure"], capture_output=True, text=True, timeout=10).stdout
366
383
  pct = re.search(r"free percentage:\s*(\d+)%", out)
367
- ram = int(_sysctl("hw.memsize") or 0)
368
384
  return int(pct.group(1)) / 100 * ram / GB if pct and ram else None
369
385
  with open("/proc/meminfo") as f:
370
386
  kb = re.search(r"MemAvailable:\s+(\d+) kB", f.read())
@@ -652,10 +652,8 @@ def context_report(e, label, got):
652
652
  say(f"{label}: stopped there because: {at['stopped']}")
653
653
  if not got["meta"].get("fill_confirmed"):
654
654
  say(f"{label}: the server reports no token counts, so how full the context was isn't confirmed", YELLOW)
655
- if sv.ctx and sv.ctx < got["max_ctx"]:
656
- say(f"{label}: runs use {sv.ctx:,}, the cap set in models.toml")
657
- elif sv.ctx_source == "measured":
658
- say(f"{label}: runs use {sv.ctx:,} from now on")
655
+ if sv.ctx_source == "measured":
656
+ say(f"{label}: runs use {sv.ctx:,} from now on, whatever models.toml caps it at")
659
657
  return True
660
658
 
661
659
 
@@ -704,9 +702,9 @@ def cmd_tune(argv):
704
702
  "machine (ctxbench.py): a few server starts, each filling the context it tries. Runs then "
705
703
  "use it in place of the estimate")
706
704
  p.add_argument("--max", type=int, default=None, metavar="N",
707
- help="with --ctx: the largest context to try (default: the model's or server's own cap)")
705
+ help="with --ctx: the largest context to try (default: the model's own limit)")
708
706
  p.add_argument("--start", type=int, default=None, metavar="N",
709
- help="with --ctx: the first context to try (default: a quarter of the largest)")
707
+ help="with --ctx: the first context to try (default: half of what the model runs with now)")
710
708
  p.add_argument("--step", type=int, default=None, metavar="N",
711
709
  help="with --ctx: how close to the true maximum to get (default 8192)")
712
710
  p.add_argument("--models", default=None, help="default: the workspace's models.toml")
@@ -4094,8 +4094,9 @@ max_context = 8192
4094
4094
  e = self._engine(self._workspace(tmp))
4095
4095
  m = e.model("sized")
4096
4096
  self.assertEqual(e.serving(m).ctx, 32768)
4097
- got = ctxbench.bench(e, "sized", step=2048)
4097
+ got = ctxbench.bench(e, "sized", max_ctx=65536, step=2048)
4098
4098
  self.assertEqual(got["max_ctx"], 18432) # the mock stops loading above 20000; 20480 failed
4099
+ self.assertEqual(list(got["probes"])[:2], ["16384", "32768"]) # half its usual context, then that
4099
4100
  self.assertIn("20,480 failed", got["measured"]["stopped"])
4100
4101
  self.assertTrue(got["meta"]["fill_confirmed"])
4101
4102
  self.assertGreater(got["measured"]["prompt_tokens"], 0.85 * 16500)
@@ -4109,7 +4110,7 @@ max_context = 8192
4109
4110
  self.assertRegex(p.stdout, r"sized\s+ctx 18k measured")
4110
4111
 
4111
4112
  def test_bench_catches_a_server_that_cuts_prompts_short(self):
4112
- from tuieval import ctxbench
4113
+ from tuieval import ctxbench, engine
4113
4114
  with tempfile.TemporaryDirectory() as tmp:
4114
4115
  e = self._engine(self._workspace(tmp))
4115
4116
  got = ctxbench.bench(e, "flagged", max_ctx=32768, step=2048)
@@ -4118,12 +4119,78 @@ max_context = 8192
4118
4119
  self.assertIn("didn't find a fact near the start", got["probes"]["16384"])
4119
4120
  cmd = e.server_command(e.model("flagged"))[0]
4120
4121
  self.assertEqual(cmd[-2:], ["--context", "12288"]) # the flag is added for runs
4121
- # a context written in models.toml stays the cap, and is lowered when less was measured
4122
+ # a context written in models.toml doesn't bound the search, and the measurement replaces it
4122
4123
  cmd = e.server_command(e.model("capped"))[0]
4123
4124
  self.assertIn("--context=10240", cmd)
4124
- ctxbench.bench(e, "capped", step=2048)
4125
- self.assertEqual(e.serving(e.model("capped")).ctx, 10240)
4126
- self.assertIn("--context=10240", e.server_command(e.model("capped"))[0])
4125
+ with self.assertRaisesRegex(engine.ModelFailed, "own context limit isn't known: pass --max"):
4126
+ ctxbench.bench(e, "capped", step=2048)
4127
+ got = ctxbench.bench(e, "capped", max_ctx=32768, step=2048)
4128
+ self.assertEqual(got["max_ctx"], 12288)
4129
+ self.assertEqual(e.serving(e.model("capped")).ctx, 12288)
4130
+ cmd = e.server_command(e.model("capped"))[0]
4131
+ self.assertIn("--context=12288", cmd)
4132
+ self.assertNotIn("--context=10240", cmd)
4133
+
4134
+ def test_a_measurement_governs_the_caps_in_models_toml(self):
4135
+ from tuieval import profiles
4136
+ with tempfile.TemporaryDirectory() as tmp:
4137
+ e = self._engine(self._workspace(tmp))
4138
+ m = e.model("sized")
4139
+ self.assertEqual(e.serving(m).ctx, 32768) # max_ctx, while nothing is measured
4140
+ profiles.save_context(e.machine().id, "sized", {"max_ctx": 49152}, e.tuning_dir)
4141
+ e._serving.clear()
4142
+ sv = e.serving(m)
4143
+ self.assertEqual((sv.ctx, sv.ctx_source), (49152, "measured")) # above max_ctx = 32768
4144
+ cmd = e.server_command(m)[0]
4145
+ self.assertEqual(cmd[cmd.index("--context") + 1], "49152")
4146
+
4147
+ def test_memory_per_token_comes_from_probes_well_apart(self):
4148
+ from tuieval import ctxbench
4149
+ P = ctxbench.Probe
4150
+ # 125952 and 131072 are too close to tell memory growth from noise: 65536 is the other point
4151
+ passed = [P(32768, True, mem_gb=80.0), P(65536, True, mem_gb=82.0), P(125952, True, mem_gb=82.9),
4152
+ P(131072, True, mem_gb=83.0)]
4153
+ base, per, fit = ctxbench.predict(passed, 84.0)
4154
+ self.assertAlmostEqual(per, 1.0 / 65536)
4155
+ self.assertEqual(fit, 196608)
4156
+ self.assertEqual(ctxbench.predict(passed[:1], 84.0), (None, None, None))
4157
+
4158
+ def test_available_memory_on_a_mac_comes_from_page_counts(self):
4159
+ from tuieval import machines
4160
+ text = ("Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 1000.\n"
4161
+ "Pages wired down: 65536.\nAnonymous pages: 131072.\nFile-backed pages: 999999.\n"
4162
+ "Pages occupied by compressor: 65536.\n")
4163
+ # 16 GiB of RAM less (1 + 2 + 1) GiB held: the file cache counts as available
4164
+ self.assertAlmostEqual(machines.vm_stat_available_gb(text, 16 * 2**30), 12.0)
4165
+ self.assertIsNone(machines.vm_stat_available_gb("Pages free: 5.", 16 * 2**30))
4166
+
4167
+ def test_a_probe_measures_the_memory_the_machine_loses(self):
4168
+ from tuieval import ctxbench, machines
4169
+ with tempfile.TemporaryDirectory() as tmp:
4170
+ e = self._engine(self._workspace(tmp))
4171
+ readings = iter([64.0] + [57.5] * 1000) # before the server starts, then while it runs
4172
+ machines.available_memory_gb = lambda: next(readings)
4173
+ r = ctxbench.probe(e, e.model("sized"), 8192)
4174
+ self.assertEqual((r.ok, r.mem_gb), (True, 6.5))
4175
+
4176
+ def test_a_probe_stops_when_memory_runs_out(self):
4177
+ from tuieval import ctxbench, machines
4178
+ with tempfile.TemporaryDirectory() as tmp:
4179
+ e = self._engine(self._workspace(tmp))
4180
+ readings = iter([64.0] + [0.4] * 1000)
4181
+ machines.available_memory_gb = lambda: next(readings)
4182
+ r = ctxbench.probe(e, e.model("sized"), 8192)
4183
+ self.assertEqual((r.ok, r.error), (False, "only 0.4 GB of memory was left"))
4184
+
4185
+ def test_a_probe_stops_when_memory_pressure_rises(self):
4186
+ from tuieval import ctxbench, machines
4187
+ with tempfile.TemporaryDirectory() as tmp:
4188
+ e = self._engine(self._workspace(tmp))
4189
+ levels = iter([1] + [2] * 1000)
4190
+ machines.memory_pressure_level = lambda: next(levels)
4191
+ r = ctxbench.probe(e, e.model("sized"), 8192)
4192
+ self.assertEqual((r.ok, r.error), (False, "macOS memory pressure rose to level 2"))
4193
+ self.assertIsNone(e._stall) # the next server can load
4127
4194
 
4128
4195
  def test_a_server_whose_context_cant_be_set_is_only_verified(self):
4129
4196
  from tuieval import ctxbench, profiles
@@ -4150,7 +4217,7 @@ max_context = 8192
4150
4217
  e = self._engine(self._workspace(tmp))
4151
4218
  machines.memory_pressure_level = lambda: 2
4152
4219
  with self.assertRaisesRegex(engine.ModelFailed, "memory pressure is already elevated"):
4153
- ctxbench.bench(e, "sized")
4220
+ ctxbench.bench(e, "sized", max_ctx=65536)
4154
4221
  self.assertFalse(os.path.isdir(os.path.join(e.log_dir, "server"))) # no server was started
4155
4222
 
4156
4223
  def test_a_probe_stops_when_the_machine_starts_swapping(self):
File without changes
File without changes