tuieval 0.2.0.dev162__py3-none-any.whl → 0.2.0.dev166__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tuieval/_version.py CHANGED
@@ -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
tuieval/ctxbench.py CHANGED
@@ -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},
tuieval/engine.py CHANGED
@@ -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,
tuieval/insights.py CHANGED
@@ -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:
tuieval/machines.py CHANGED
@@ -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:
tuieval/packs.py CHANGED
@@ -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)),
tuieval/run_evals.py CHANGED
@@ -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")
tuieval/tui.py CHANGED
@@ -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
 
tuieval/verdict.py CHANGED
@@ -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:
@@ -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
@@ -1,30 +1,30 @@
1
1
  tuieval/__init__.py,sha256=myVXVX7htbwezW6k3x_FuKgn1RSZ2WcTaDEMByGn6Wg,312
2
2
  tuieval/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
- tuieval/_version.py,sha256=pxmDFVRvLYhGnEkyqrkqleADe-92ALGEewQiuRrBhxY,537
3
+ tuieval/_version.py,sha256=cEhq5-WTMFRjvcrzNDlck2FzPBVuw181KBozynLb4oY,537
4
4
  tuieval/agents.py,sha256=XmY4d4PAnC7BQcs_6KO9WTuIdpnwYVAdyhqItybWdAM,15408
5
5
  tuieval/builtin.toml,sha256=QLQP1nh577RW6x0Z38JKNES-MPTSmlZAcxD5Javbk4Q,4768
6
6
  tuieval/cli.py,sha256=Q9-b9sg6LSAfNq6o-c3J3hiOIoINgvH_Fe_U1x-0W4U,4915
7
7
  tuieval/client.py,sha256=O77uftaxqgQ8b8rMnpR5822kmYFfr574w1pZlaSOFEE,14304
8
8
  tuieval/compare.py,sha256=T5MDIkNzPGTFUvYr1EzxVGGlCdvTlO1v5De3gN0Eocw,39654
9
- tuieval/ctxbench.py,sha256=Xahl_o-r25Aq9LFaZXlZMzLhARIayT8gpsAQxYwuUYA,27898
9
+ tuieval/ctxbench.py,sha256=VLl6Em7iCbZz2wwI9rTHMaWFMehcaJ7SYUL7g93B3j8,34366
10
10
  tuieval/dates.py,sha256=CVazlwNjCRhD__D12zXLdeqF2ySt15X3xLUQeE-o6PY,6293
11
11
  tuieval/doctor.py,sha256=j2MdDORstsAGPnRmpsnxau1_fR6sTc_oEFGM5zugTJU,7246
12
- tuieval/engine.py,sha256=novRrmz7AeEs-sQqEImdN5qFW5m_QpD-GJgGZ_ZA8oM,145365
12
+ tuieval/engine.py,sha256=hw9gLuRCAeoQdpb_tURenz5hbd3trUAglx5q-ahogio,145417
13
13
  tuieval/export.py,sha256=dbHQgL_ubWtIPM1sLzAew_gETnrDJyd0zgqVA5vkpXM,9657
14
- tuieval/insights.py,sha256=hIJp1n0eZeoo9QCyS5-OChv70ItSqV8jSsInoh4Stm0,29591
14
+ tuieval/insights.py,sha256=32mpNiLgSoxxZaJq9LBZKj5iJJCKChpGQYHSnar7bSo,30074
15
15
  tuieval/logs.py,sha256=01gZK6tf53dIThaIrs1bEsz9eqKYVlcxpyaLnSPTVxo,8127
16
- tuieval/machines.py,sha256=a4bmR-EuNQ1l_w4g44Yjdn-xPQ6tLP-t0ZH-QoPAhOg,22410
16
+ tuieval/machines.py,sha256=pWbWw1_B29U2H_c3PTrrOJkPO-wW_o12buxMay5TNdA,24515
17
17
  tuieval/onboard.py,sha256=IYETVDWCCo9vF0Dtj4_rr9VanYeCky8PwP3-2g5A_l0,6215
18
- tuieval/packs.py,sha256=KOj0BkwsB2124aslGyauZonyyGqtSrCJ-WAozEntmqE,17466
18
+ tuieval/packs.py,sha256=LPB9qhuN6zfic0zfVJuSE9lx4BTCFQJoibdB4vvGDhQ,17859
19
19
  tuieval/profiles.py,sha256=3GribubCOCRTi_rClLxVynBeX2SBYTig0XObAlS8lzg,5300
20
20
  tuieval/pta.py,sha256=MBn2EkDysayv8XOqiTKp5zomuUmZnZTuQ5jGBR2-Z4s,19281
21
21
  tuieval/remove.py,sha256=ckep4iZUkuWE2JTcZFovCy7snNd_WLkJ6b602eGKZws,5339
22
- tuieval/run_evals.py,sha256=OwS4HGkCOlU0cGcToqJKxFpL8GQdMFW5PB6SitSAfrE,56337
22
+ tuieval/run_evals.py,sha256=vvLAJJUD6SJmJJ2LwCXl3IRj9h4dydvYpmzRgxOE7I8,56440
23
23
  tuieval/scaffold.py,sha256=YBOqniJpf_GtKKAFF3_OHxxMGbmTWdFjcClGcOnrrKE,12130
24
24
  tuieval/selftest.py,sha256=cIGSDCrCK-QISAXjKSJDB4sD-WwS32bn3Gn4Y0oGoF8,11502
25
- tuieval/tui.py,sha256=5BtqHoEtqBHRCrh0qPn2Vmg-4hSjjtlfPQ5qoysHlb0,211349
25
+ tuieval/tui.py,sha256=2ijU3DnaGLcoqaxKTsQdQd75U2MT7Q12u5BA7f4XZ2g,213337
26
26
  tuieval/tune.py,sha256=V43Lo3x-flTuUFYXRt2_aqmpo4RML0adP-XUHWTgfRQ,41659
27
- tuieval/verdict.py,sha256=l51SiZt50LdPdcHuyAB1us6cZrARlJdgjrKgl2AluME,21229
27
+ tuieval/verdict.py,sha256=eBPTAS6GTtslOe5t3PkH80bf-ZGu6TfK5-0448yFfwU,21843
28
28
  tuieval/watch_proxy.py,sha256=bnDO1i6n6yUs1hODoUWcMppJMGPavoQqs6aNYrIxpT8,11416
29
29
  tuieval/workspace.py,sha256=V_HhkaN1odr0OpjNsPYradRWLpzDldM7SwpvxohBL4U,895
30
30
  tuieval/yamlout.py,sha256=r1IokjLqW-Ztpg1fSn33ZW3VK00v1VvxymmU5Qy7GEw,606
@@ -51,8 +51,8 @@ tuieval/templates/packs/tool_call/pack.toml,sha256=n4bx0lGJHSmW41uVqhfIXJ2BWZpmT
51
51
  tuieval/templates/packs/tool_call/system.txt,sha256=mKxu-lB-0YjLHXdgeFJa8x2C180OvcNz5cHv2N5Bg3U,254
52
52
  tuieval/templates/packs/tool_call/tests.yaml,sha256=Nv7c4syrzJ9cU8EBKSK_1ZSFx9V02aCjW4-2TBCPT7s,1859
53
53
  tuieval/templates/packs/tool_call/tools.yaml,sha256=HgxCkh0On2VwbHSsjAGM8tNCK7ZtKLGrs7lMCn3Fprs,1048
54
- tuieval-0.2.0.dev162.dist-info/METADATA,sha256=QuoFHbrGop9LK3iWs23AV5To3AhtkXJqcQbepEEHW8w,15306
55
- tuieval-0.2.0.dev162.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
56
- tuieval-0.2.0.dev162.dist-info/entry_points.txt,sha256=7eIhi1GpFxBP2OLJV02Nn8LwsNuO512eKOGt1IBbj04,45
57
- tuieval-0.2.0.dev162.dist-info/licenses/LICENSE,sha256=7wfRgGtBGH1aXhZkIn47oUznqKC18kEPMvUVgol7Ffc,1077
58
- tuieval-0.2.0.dev162.dist-info/RECORD,,
54
+ tuieval-0.2.0.dev166.dist-info/METADATA,sha256=CU6QWZcgLtNVH274udWZs-dqIUMyq2HkUMPtPiNKaZ8,15306
55
+ tuieval-0.2.0.dev166.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
56
+ tuieval-0.2.0.dev166.dist-info/entry_points.txt,sha256=7eIhi1GpFxBP2OLJV02Nn8LwsNuO512eKOGt1IBbj04,45
57
+ tuieval-0.2.0.dev166.dist-info/licenses/LICENSE,sha256=7wfRgGtBGH1aXhZkIn47oUznqKC18kEPMvUVgol7Ffc,1077
58
+ tuieval-0.2.0.dev166.dist-info/RECORD,,