quantcheck 0.0.1__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.
Files changed (79) hide show
  1. quantcheck/__init__.py +3 -0
  2. quantcheck/auth/__init__.py +6 -0
  3. quantcheck/auth/base.py +74 -0
  4. quantcheck/auth/callback.py +73 -0
  5. quantcheck/auth/fake.py +40 -0
  6. quantcheck/auth/service.py +49 -0
  7. quantcheck/auth/store.py +63 -0
  8. quantcheck/auth/supabase.py +168 -0
  9. quantcheck/bench.py +38 -0
  10. quantcheck/candidates.py +138 -0
  11. quantcheck/cli.py +251 -0
  12. quantcheck/config.py +63 -0
  13. quantcheck/executors/__init__.py +0 -0
  14. quantcheck/hardware.py +52 -0
  15. quantcheck/limits.py +19 -0
  16. quantcheck/pipeline.py +172 -0
  17. quantcheck/prompt.py +67 -0
  18. quantcheck/recommend.py +131 -0
  19. quantcheck/report/__init__.py +0 -0
  20. quantcheck/report/html.py +38 -0
  21. quantcheck/report/templates/report.html.j2 +272 -0
  22. quantcheck/report/terminal.py +90 -0
  23. quantcheck/report/tokens.py +41 -0
  24. quantcheck/report/view.py +161 -0
  25. quantcheck/runners/__init__.py +3 -0
  26. quantcheck/runners/base.py +87 -0
  27. quantcheck/runners/fake.py +68 -0
  28. quantcheck/runners/llamacpp_runner.py +185 -0
  29. quantcheck/runners/mlx_runner.py +153 -0
  30. quantcheck/runners/toolparse.py +107 -0
  31. quantcheck/scoring/__init__.py +0 -0
  32. quantcheck/scoring/checks.py +342 -0
  33. quantcheck/scoring/fake_judge.py +50 -0
  34. quantcheck/scoring/judge.py +171 -0
  35. quantcheck/scoring/language.py +99 -0
  36. quantcheck/scoring/models.py +92 -0
  37. quantcheck/scoring/score.py +167 -0
  38. quantcheck/scoring/stats.py +60 -0
  39. quantcheck/settings.py +14 -0
  40. quantcheck/store.py +88 -0
  41. quantcheck/tests_io.py +169 -0
  42. quantcheck/ui/__init__.py +1 -0
  43. quantcheck/ui/app.py +534 -0
  44. quantcheck/ui/catalog.py +47 -0
  45. quantcheck/ui/chat.py +211 -0
  46. quantcheck/ui/compare.py +63 -0
  47. quantcheck/ui/downloads.py +172 -0
  48. quantcheck/ui/jobs.py +173 -0
  49. quantcheck/ui/modeldetail.py +97 -0
  50. quantcheck/ui/reviews.py +59 -0
  51. quantcheck/ui/security.py +45 -0
  52. quantcheck/ui/static/chat.js +312 -0
  53. quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
  54. quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
  55. quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
  56. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
  57. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
  58. quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
  59. quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
  60. quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
  61. quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
  62. quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
  63. quantcheck/ui/static/fonts/README.md +14 -0
  64. quantcheck/ui/static/fonts.css +228 -0
  65. quantcheck/ui/static/index.html +24 -0
  66. quantcheck/ui/static/lab.css +768 -0
  67. quantcheck/ui/static/lab.js +896 -0
  68. quantcheck/ui/static/logo.svg +5 -0
  69. quantcheck/ui/static/review.js +127 -0
  70. quantcheck/ui/static/setup.js +132 -0
  71. quantcheck/ui/static/testsets.js +527 -0
  72. quantcheck/ui/summary.py +104 -0
  73. quantcheck/ui/system.py +101 -0
  74. quantcheck/ui/testsets.py +243 -0
  75. quantcheck-0.0.1.dist-info/METADATA +115 -0
  76. quantcheck-0.0.1.dist-info/RECORD +79 -0
  77. quantcheck-0.0.1.dist-info/WHEEL +4 -0
  78. quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
  79. quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
quantcheck/ui/chat.py ADDED
@@ -0,0 +1,211 @@
1
+ """Chat side by side: a few versions loaded at once, one question sent to each in turn.
2
+
3
+ Each column has its own runner, so the test pipeline (one model at a time) is untouched.
4
+ Models are loaded one after another, a question goes to the columns one after another (the
5
+ MLX runtime is not safe to run twice at once), and everything runs in a background thread
6
+ that the screen polls. The combined memory is checked before anything loads.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import threading
13
+ import time
14
+ from dataclasses import dataclass, field
15
+ from typing import Any
16
+
17
+ from quantcheck import limits, pipeline
18
+ from quantcheck.candidates import Candidate, parse_bits
19
+ from quantcheck.prompt import build_prompt
20
+ from quantcheck.runners.base import GenSettings, Runner
21
+ from quantcheck.tests_io import SetHeader, TestCase
22
+
23
+ OVERHEAD = 1.1 # memory when running is about file size plus 10%
24
+ HEADROOM_GB = 2.0 # keep this much free for the system
25
+ LETTERS = "ABCD"
26
+
27
+
28
+ class ChatError(ValueError):
29
+ """A message that is safe to show to the user."""
30
+
31
+
32
+ class ChatBusy(RuntimeError):
33
+ """Chat cannot do that right now (loading, answering, or a test is running)."""
34
+
35
+
36
+ @dataclass
37
+ class Column:
38
+ letter: str
39
+ model: str
40
+ runtime: str
41
+ label: str
42
+ size_gb: float | None
43
+ runner: Runner | None = None
44
+ state: str = "waiting" # waiting | loading | warming | ready | error
45
+ error: str | None = None
46
+
47
+ def public(self) -> dict[str, Any]:
48
+ return {"letter": self.letter, "model": self.model, "runtime": self.runtime,
49
+ "label": self.label, "size_gb": self.size_gb, "state": self.state,
50
+ "error": self.error} # fmt: skip
51
+
52
+
53
+ def _label(model: str, runtime: str) -> str:
54
+ m = re.search(r"-(\d+bit)$", model)
55
+ if m:
56
+ return m.group(1)
57
+ return "GGUF" if runtime == "llamacpp" else model.rsplit("/", 1)[-1]
58
+
59
+
60
+ @dataclass
61
+ class ChatSession:
62
+ """At most one session; ``close()`` frees every loaded model."""
63
+
64
+ columns: list[Column] = field(default_factory=list)
65
+ turns: list[dict[str, Any]] = field(default_factory=list)
66
+ phase: str = "idle" # idle | loading | ready | answering
67
+ _lock: threading.RLock = field(default_factory=threading.RLock)
68
+ run_in_thread: bool = True
69
+
70
+ def active(self) -> bool:
71
+ """True while any model is loaded or loading (memory is in use)."""
72
+ return self.phase != "idle"
73
+
74
+ def load(
75
+ self,
76
+ specs: list[dict[str, str]],
77
+ sizes_gb: dict[str, float],
78
+ ram_gb: float,
79
+ available_gb: float | None = None,
80
+ ) -> None:
81
+ """Start loading the columns. Raises ChatError for bad input, ChatBusy if in use.
82
+
83
+ ``ram_gb`` is the Mac's total memory; ``available_gb`` is what is free right now (other
84
+ apps use the rest). Both limits apply.
85
+ """
86
+ if not 1 <= len(specs) <= limits.MAX_CHAT_COLUMNS:
87
+ raise ChatError(f"columns: choose 1 to {limits.MAX_CHAT_COLUMNS} versions")
88
+ with self._lock:
89
+ if self.active():
90
+ raise ChatBusy("Chat already has models loaded. Close it first.")
91
+ cols: list[Column] = []
92
+ for i, sp in enumerate(specs):
93
+ model = str(sp.get("model", "")).strip()
94
+ runtime = sp.get("runtime", "mlx")
95
+ if not model:
96
+ raise ChatError(f"column {LETTERS[i]}: pick a model version")
97
+ if runtime not in ("mlx", "llamacpp"):
98
+ raise ChatError(f"column {LETTERS[i]}: unknown runtime '{runtime}'")
99
+ gb = sizes_gb.get(model)
100
+ cols.append(Column(LETTERS[i], model, runtime, _label(model, runtime), gb))
101
+ need = sum((c.size_gb or 0) * OVERHEAD for c in cols)
102
+ if need and need > ram_gb - HEADROOM_GB:
103
+ raise ChatError(
104
+ f"These columns need about {need:.1f} GB together, but this Mac has "
105
+ f"{ram_gb:g} GB and the system needs {HEADROOM_GB:g} GB. "
106
+ "Remove a column or pick smaller versions."
107
+ )
108
+ if need and available_gb is not None and need > available_gb:
109
+ raise ChatError(
110
+ f"These columns need about {need:.1f} GB together, but only "
111
+ f"{available_gb:.1f} GB is free right now because other apps are using "
112
+ "memory. Close some apps, remove a column, or pick smaller versions."
113
+ )
114
+ self.columns, self.turns, self.phase = cols, [], "loading"
115
+ if self.run_in_thread:
116
+ threading.Thread(target=self._load_all, daemon=True).start()
117
+ else:
118
+ self._load_all()
119
+
120
+ def _warm_up(self, col: Column) -> None:
121
+ """Generate one token so the first real question is not slow (the first call compiles
122
+ kernels and fills caches). A failure here is ignored: the real answer will report it."""
123
+ try:
124
+ prompt = build_prompt(SetHeader(), TestCase(id="warmup", prompt="Hi"))
125
+ if col.runner is not None:
126
+ col.runner.generate(prompt, GenSettings(max_tokens=1))
127
+ except Exception: # noqa: BLE001
128
+ pass
129
+
130
+ def _load_all(self) -> None:
131
+ for col in self.columns:
132
+ col.state = "loading"
133
+ try:
134
+ runner = pipeline.get_runner(col.runtime)
135
+ fmt = "gguf" if col.runtime == "llamacpp" else "mlx"
136
+ bits = parse_bits(col.label)
137
+ runner.load(
138
+ Candidate(model=col.model, format=fmt, quantization=col.label, bits=bits)
139
+ )
140
+ col.runner, col.state = runner, "warming"
141
+ self._warm_up(col)
142
+ col.state = "ready"
143
+ except Exception as e: # a column that cannot load is shown, the others stay usable
144
+ col.state, col.error = "error", str(e)
145
+ with self._lock:
146
+ self.phase = "ready" if any(c.state == "ready" for c in self.columns) else "idle"
147
+
148
+ def ask(self, text: str, header: SetHeader, docs: list[str], max_tokens: int) -> None:
149
+ """Send one question to every ready column, in turn."""
150
+ text = text.strip()
151
+ if not text:
152
+ raise ChatError("question: type something to ask")
153
+ with self._lock:
154
+ if self.phase == "answering":
155
+ raise ChatBusy("Wait for the current answers to finish.")
156
+ if self.phase != "ready":
157
+ raise ChatBusy("Load the versions first.")
158
+ prompt = build_prompt(header, TestCase(id="chat", prompt=text, context=docs))
159
+ turn = {"question": text, "started_at": time.time(),
160
+ "answers": {c.letter: {"text": "", "state": "waiting", "error": None,
161
+ "tok_s": None, "seconds": None}
162
+ for c in self.columns if c.state == "ready"}} # fmt: skip
163
+ self.turns.append(turn)
164
+ self.phase = "answering"
165
+ args = (turn, prompt, GenSettings(max_tokens=max_tokens))
166
+ if self.run_in_thread:
167
+ threading.Thread(target=self._answer_all, args=args, daemon=True).start()
168
+ else:
169
+ self._answer_all(*args)
170
+
171
+ def _answer_all(self, turn: dict[str, Any], prompt: Any, settings: GenSettings) -> None:
172
+ try:
173
+ for col in self.columns:
174
+ ans = turn["answers"].get(col.letter)
175
+ if ans is None or col.runner is None:
176
+ continue
177
+ ans["state"] = "answering"
178
+ t0 = time.perf_counter()
179
+
180
+ def on_text(t: str, ans: dict[str, Any] = ans) -> None:
181
+ ans["text"] = t
182
+
183
+ try:
184
+ gen = col.runner.stream(prompt, settings, on_text)
185
+ ans["text"] = gen.text or ans["text"]
186
+ ans["error"] = gen.error
187
+ ans["tok_s"] = round(gen.gen_tps, 1) if gen.gen_tps else None
188
+ except Exception as e: # one failing column must not stop the others
189
+ ans["error"] = str(e)
190
+ ans["seconds"] = round(time.perf_counter() - t0, 1)
191
+ ans["state"] = "error" if ans["error"] else "done"
192
+ finally:
193
+ with self._lock:
194
+ self.phase = "ready"
195
+
196
+ def close(self) -> None:
197
+ """Unload every model and forget the conversation."""
198
+ with self._lock:
199
+ if self.phase in ("loading", "answering"):
200
+ raise ChatBusy("Wait until loading or answering has finished, then close.")
201
+ cols, self.columns, self.turns, self.phase = self.columns, [], [], "idle"
202
+ for col in cols:
203
+ if col.runner is not None:
204
+ try:
205
+ col.runner.unload()
206
+ except Exception: # freeing memory is best effort
207
+ pass
208
+
209
+ def public(self) -> dict[str, Any]:
210
+ return {"phase": self.phase, "columns": [c.public() for c in self.columns],
211
+ "turns": self.turns} # fmt: skip
@@ -0,0 +1,63 @@
1
+ """Compare models that were tested on the same test set, from saved runs only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from quantcheck.report.view import build_view
9
+ from quantcheck.ui.modeldetail import OVERHEAD, base_id
10
+
11
+
12
+ def _stem(run: Any) -> str:
13
+ return Path(str(run.config.get("tests", ""))).stem
14
+
15
+
16
+ def test_sets(runs: list[Any]) -> list[dict[str, Any]]:
17
+ """Test sets that have at least one scored run, with how many different models tested them."""
18
+ models: dict[str, set[str]] = {}
19
+ for r in runs:
20
+ if r.candidates and any(c.status == "ok" for c in r.candidates):
21
+ models.setdefault(_stem(r), set()).add(base_id(str(r.config.get("model", ""))).lower())
22
+ return [{"name": k, "models": len(v)} for k, v in sorted(models.items())]
23
+
24
+
25
+ def compare(runs: list[Any], tests: str) -> dict[str, Any]:
26
+ """One row per model: its newest scored run on ``tests``. Runs arrive newest first."""
27
+ rows: list[dict[str, Any]] = []
28
+ seen: set[str] = set()
29
+ tags: dict[str, int] = {}
30
+ for r in runs:
31
+ mid = base_id(str(r.config.get("model", "")))
32
+ if _stem(r) != tests or mid.lower() in seen or not r.candidates:
33
+ continue
34
+ v = build_view(r)
35
+ if not v.scored or not v.recommendation:
36
+ continue
37
+ seen.add(mid.lower())
38
+ rec = v.recommendation
39
+ proven = rec.status == "recommended" and rec.recommended
40
+ label = rec.recommended if proven else v.reference_label
41
+ row = next((x for x in v.rows if x.label == label), None)
42
+ if row is None:
43
+ continue
44
+ peak = row.bench.peak_memory_mb
45
+ size = row.bench.file_size_mb
46
+ mem = peak or (size * OVERHEAD if size else None)
47
+ tq = v.tag_quality.get(label, {})
48
+ for t in tq:
49
+ tags[t] = tags.get(t, 0) + 1
50
+ rows.append({
51
+ "model": mid.rsplit("/", 1)[-1], "model_id": mid, "run_id": r.run_id,
52
+ "version": label, "proven": bool(proven), "quality": row.quality,
53
+ "tag_quality": tq, "tok_s": row.bench.tokens_per_s,
54
+ "memory_gb": round(mem / 1000, 1) if mem else None, "memory_measured": bool(peak),
55
+ "n_prompts": v.n_prompts, "quality_limit": v.quality_limit,
56
+ }) # fmt: skip
57
+ shared = [t for t, n in sorted(tags.items(), key=lambda kv: (-kv[1], kv[0])) if n == len(rows)]
58
+ top = (
59
+ shared[:3]
60
+ if len(shared) >= 1
61
+ else [t for t, _ in sorted(tags.items(), key=lambda kv: -kv[1])][:3]
62
+ )
63
+ return {"tests": tests, "rows": rows, "tags": top}
@@ -0,0 +1,172 @@
1
+ """Model downloads for the first-run Setup screen.
2
+
3
+ Each download is started by the user's click and goes straight to Hugging Face; nothing about
4
+ the user's prompts or account is sent. Versions download one after another. Progress is read from
5
+ the size of the files on disk, so it is real, and a download that is interrupted resumes from the
6
+ partial files the next time it is started (``huggingface_hub`` keeps them).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from quantcheck.ui.system import hf_cache_dir
20
+
21
+ REPO = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*$")
22
+ DISK_MARGIN_GB = 1.0 # keep this much free after a download
23
+
24
+
25
+ class DownloadError(ValueError):
26
+ """A message that is safe to show to the user."""
27
+
28
+
29
+ class DownloadBusy(RuntimeError):
30
+ """A download is already running."""
31
+
32
+
33
+ def hub_size_bytes(repo: str) -> int | None:
34
+ """Total size of a repo's files according to Hugging Face (None if it cannot be found)."""
35
+ from huggingface_hub import HfApi
36
+ from huggingface_hub.errors import RepositoryNotFoundError
37
+
38
+ try:
39
+ info = HfApi().model_info(repo, files_metadata=True)
40
+ except RepositoryNotFoundError:
41
+ return None
42
+ return sum(s.size or 0 for s in info.siblings) or None
43
+
44
+
45
+ def hub_download(repo: str) -> None:
46
+ """Fetch a repo into the Hugging Face cache; resumes partial files."""
47
+ from huggingface_hub import snapshot_download
48
+
49
+ snapshot_download(repo)
50
+
51
+
52
+ def bytes_on_disk(repo: str, cache: Path | None = None) -> int:
53
+ """Bytes already stored for a repo, including files still downloading."""
54
+ blobs = (cache or hf_cache_dir()) / f"models--{repo.replace('/', '--')}" / "blobs"
55
+ if not blobs.is_dir():
56
+ return 0
57
+ return sum(f.stat().st_size for f in blobs.iterdir() if f.is_file())
58
+
59
+
60
+ @dataclass
61
+ class Item:
62
+ repo: str
63
+ label: str
64
+ expected: int | None = None
65
+ done: int = 0
66
+ state: str = "waiting" # waiting | downloading | done | error
67
+ error: str | None = None
68
+
69
+ def public(self) -> dict[str, Any]:
70
+ pct = None
71
+ if self.state == "done":
72
+ pct = 100
73
+ elif self.expected and self.state == "downloading":
74
+ pct = min(99, round(100 * self.done / self.expected))
75
+ elif self.state == "waiting":
76
+ pct = 0
77
+ return {"repo": self.repo, "label": self.label, "state": self.state, "error": self.error,
78
+ "total_bytes": self.expected, "done_bytes": self.done, "percent": pct} # fmt: skip
79
+
80
+
81
+ @dataclass
82
+ class DownloadManager:
83
+ """One batch at a time. The ``*_fn`` fields are replaceable in tests (no network)."""
84
+
85
+ size_fn: Callable[[str], int | None] = hub_size_bytes
86
+ download_fn: Callable[[str], None] = hub_download
87
+ free_gb_fn: Callable[[], float] = lambda: 1e9
88
+ disk_fn: Callable[[str], int] = bytes_on_disk
89
+ run_in_thread: bool = True
90
+ items: list[Item] = field(default_factory=list)
91
+ running: bool = False
92
+ _lock: threading.RLock = field(default_factory=threading.RLock)
93
+ _samples: list[tuple[float, int]] = field(default_factory=list)
94
+
95
+ def start(self, models: list[dict[str, str]]) -> None:
96
+ """Begin downloading ``[{repo, label}, ...]``. Raises DownloadError or DownloadBusy."""
97
+ if not 1 <= len(models) <= 6:
98
+ raise DownloadError("models: choose 1 to 6 versions to download")
99
+ items = []
100
+ for m in models:
101
+ repo = str(m.get("repo", "")).strip()
102
+ if not REPO.match(repo):
103
+ raise DownloadError(f"model: '{repo}' is not a Hugging Face repo id like org/name")
104
+ items.append(Item(repo=repo, label=str(m.get("label") or repo.split("/")[-1])))
105
+ with self._lock:
106
+ if self.running:
107
+ raise DownloadBusy("A download is already running.")
108
+ self.items, self.running, self._samples = items, True, []
109
+ if self.run_in_thread:
110
+ threading.Thread(target=self._run, daemon=True).start()
111
+ else:
112
+ self._run()
113
+
114
+ def _run(self) -> None:
115
+ try:
116
+ for it in self.items: # sizes first, so the total is known before the first byte
117
+ try:
118
+ it.expected = self.size_fn(it.repo)
119
+ except Exception as e:
120
+ it.state, it.error = "error", str(e) or type(e).__name__
121
+ else:
122
+ if it.expected is None:
123
+ it.state = "error"
124
+ it.error = "not found on Hugging Face (it may not exist in this size)"
125
+ for it in self.items:
126
+ if it.state != "error":
127
+ self._one(it)
128
+ finally:
129
+ with self._lock:
130
+ self.running = False
131
+
132
+ def _one(self, it: Item) -> None:
133
+ it.state = "downloading"
134
+ try:
135
+ expected = it.expected or 0
136
+ need = max(0, expected - self.disk_fn(it.repo)) / 1e9
137
+ free = self.free_gb_fn()
138
+ if need + DISK_MARGIN_GB > free:
139
+ raise DownloadError(
140
+ f"not enough free disk space: needs {need:.1f} GB more, {free:.1f} GB free"
141
+ )
142
+ self.download_fn(it.repo)
143
+ it.done = expected
144
+ it.state = "done"
145
+ except Exception as e: # one failing version must not stop the others
146
+ it.state, it.error = "error", str(e) or type(e).__name__
147
+
148
+ def public(self) -> dict[str, Any]:
149
+ """State for the screen: per-version progress, overall bytes, speed, time left."""
150
+ with self._lock:
151
+ for it in self.items:
152
+ if it.state == "downloading":
153
+ it.done = min(self.disk_fn(it.repo), it.expected or 0)
154
+ live = [i for i in self.items if i.state != "error"]
155
+ total = (
156
+ sum(i.expected or 0 for i in live)
157
+ if live and all(i.expected for i in live)
158
+ else None
159
+ )
160
+ done = sum(i.done for i in live)
161
+ now = time.monotonic()
162
+ if self.running:
163
+ self._samples = [x for x in self._samples if now - x[0] <= 5] + [(now, done)]
164
+ speed = None
165
+ if self.running and len(self._samples) >= 2:
166
+ t0, d0 = self._samples[0]
167
+ speed = max(0.0, (done - d0) / (now - t0)) if now > t0 else None
168
+ left = (total - done) / speed if speed and total and total > done else None
169
+ return {"running": self.running, "items": [i.public() for i in self.items],
170
+ "done_bytes": done, "total_bytes": total,
171
+ "bytes_per_s": round(speed) if speed else None,
172
+ "seconds_left": round(left) if left is not None else None} # fmt: skip
quantcheck/ui/jobs.py ADDED
@@ -0,0 +1,173 @@
1
+ """Runs started from the lab: one at a time, in a background thread, same pipeline as the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ import threading
7
+ import time
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from quantcheck.pipeline import PreparedJob, run_job, score_job
14
+ from quantcheck.report.html import write_report
15
+ from quantcheck.store import JsonResultsStore
16
+
17
+
18
+ class Busy(RuntimeError):
19
+ """A run is already in progress (models are loaded one at a time)."""
20
+
21
+
22
+ @dataclass
23
+ class VersionProgress:
24
+ label: str
25
+ state: str = "waiting" # waiting | running | done | skipped
26
+ done: int = 0
27
+ total: int = 0
28
+ reason: str | None = None
29
+ started_at: float | None = None
30
+ ended_at: float | None = None
31
+ tps_sum: float = 0.0
32
+ tps_n: int = 0
33
+ peak_mb: float = 0.0
34
+ failed: int = 0 # answers the model could not produce (error from the runner)
35
+
36
+ def public(self) -> dict[str, Any]:
37
+ """Progress plus live measurements. Speed and memory are None until measured."""
38
+ return {
39
+ "label": self.label, "state": self.state, "done": self.done, "total": self.total,
40
+ "reason": self.reason, "started_at": self.started_at, "ended_at": self.ended_at,
41
+ "tok_s": round(self.tps_sum / self.tps_n, 1) if self.tps_n else None,
42
+ "peak_gb": round(self.peak_mb / 1000, 1) if self.peak_mb else None,
43
+ "failed": self.failed,
44
+ } # fmt: skip
45
+
46
+
47
+ @dataclass
48
+ class Job:
49
+ id: str
50
+ model: str
51
+ n_prompts: int
52
+ versions: list[VersionProgress]
53
+ state: str = "running" # running | done | error
54
+ phase: str = "generating" # generating | judging | done
55
+ judge_done: int = 0
56
+ judge_total: int = 0
57
+ run_id: str | None = None
58
+ error: str | None = None
59
+ warnings: list[str] = field(default_factory=list)
60
+ tests: str = ""
61
+ quality_limit: float = 0.97
62
+ started_at: float = field(default_factory=time.time)
63
+ latest: dict[str, Any] | None = None # the most recent finished answer
64
+
65
+ def public(self) -> dict[str, Any]:
66
+ """What the front end sees. ``saved`` counts answers already written to memory."""
67
+ return {
68
+ "id": self.id, "model": self.model, "state": self.state, "phase": self.phase,
69
+ "n_prompts": self.n_prompts, "run_id": self.run_id, "error": self.error,
70
+ "versions": [v.public() for v in self.versions],
71
+ "tests": self.tests, "quality_limit": self.quality_limit,
72
+ "started_at": self.started_at, "latest": self.latest,
73
+ "judge": {"done": self.judge_done, "total": self.judge_total},
74
+ "warnings": self.warnings,
75
+ } # fmt: skip
76
+
77
+
78
+ class JobManager:
79
+ """Starts and tracks runs. Only one runs at a time."""
80
+
81
+ def __init__(self, runs_dir: Path, run_in_thread: bool = True) -> None:
82
+ self.runs_dir = runs_dir
83
+ self.run_in_thread = run_in_thread
84
+ self.jobs: dict[str, Job] = {}
85
+ self._lock = threading.Lock()
86
+
87
+ def active(self) -> Job | None:
88
+ """The running job, if any."""
89
+ return next((j for j in self.jobs.values() if j.state == "running"), None)
90
+
91
+ def start(self, prepared: PreparedJob) -> Job:
92
+ """Begin a run. Raises Busy if one is already running."""
93
+ with self._lock:
94
+ if self.active():
95
+ raise Busy("a run is already in progress")
96
+ cfg, ts = prepared.config, prepared.testset
97
+ versions = [VersionProgress(c.quantization, total=len(ts.cases))
98
+ for c in prepared.resolution.candidates] # fmt: skip
99
+ versions += [VersionProgress(label, "skipped", reason=why)
100
+ for label, why in prepared.resolution.skipped.items()] # fmt: skip
101
+ job = Job(secrets.token_hex(4), cfg.model, len(ts.cases), versions,
102
+ warnings=list(ts.warnings), tests=Path(cfg.tests).stem,
103
+ quality_limit=cfg.quality_limit) # fmt: skip
104
+ self.jobs[job.id] = job
105
+ if self.run_in_thread:
106
+ threading.Thread(target=self._work, args=(job, prepared), daemon=True).start()
107
+ else:
108
+ self._work(job, prepared)
109
+ return job
110
+
111
+ def get(self, job_id: str) -> Job | None:
112
+ return self.jobs.get(job_id)
113
+
114
+ def _work(self, job: Job, prepared: PreparedJob) -> None:
115
+ cfg = prepared.config
116
+ store = JsonResultsStore(self.runs_dir)
117
+ by_label = {v.label: v for v in job.versions}
118
+
119
+ def on_generate(label: str, done: int, total: int) -> None:
120
+ v = by_label[label]
121
+ v.state, v.done, v.total = ("done" if done == total else "running"), done, total
122
+ if v.state == "done":
123
+ v.ended_at = time.time()
124
+
125
+ def on_answer(label: str, case: Any, record: Any) -> None:
126
+ v = by_label[label]
127
+ if v.started_at is None:
128
+ v.started_at = time.time()
129
+ g = record.generation
130
+ if g.error:
131
+ v.failed += 1
132
+ if g.gen_tps:
133
+ v.tps_sum, v.tps_n = v.tps_sum + g.gen_tps, v.tps_n + 1
134
+ if g.peak_memory_mb:
135
+ v.peak_mb = max(v.peak_mb, g.peak_memory_mb)
136
+ job.latest = {"version": label, "case_id": case.id, "prompt": case.prompt,
137
+ "answer": g.text[:1500], "error": g.error} # fmt: skip
138
+
139
+ try:
140
+ result = run_job(cfg, prepared.testset, prepared.resolution, prepared.runner,
141
+ store, on_generate, on_answer) # fmt: skip
142
+ job.run_id = result.run_id
143
+ for v in job.versions: # versions that failed to load
144
+ if v.state == "waiting":
145
+ v.state, v.reason = "skipped", "failed to load"
146
+ for c in result.candidates:
147
+ if c.status != "ok" and c.label in by_label:
148
+ by_label[c.label].state, by_label[c.label].reason = "skipped", c.reason
149
+ job.phase = "judging"
150
+ job.judge_total = sum(len(c.answers) for c in result.candidates if c.status == "ok")
151
+
152
+ def on_judge(_label: str, _done: int, _n: int) -> None:
153
+ job.judge_done += 1
154
+
155
+ error = score_job(result, prepared.judge, prepared.rubric, store,
156
+ cfg.quality_limit, on_judge) # fmt: skip
157
+ write_report(result, self.runs_dir / result.run_id / "report.html")
158
+ if error:
159
+ job.state, job.error = (
160
+ "error",
161
+ (
162
+ f"Scoring stopped: {error}. The answers are saved; fix the judge and "
163
+ "score again with `quantcheck rescore`."
164
+ ),
165
+ )
166
+ else:
167
+ job.state = "done"
168
+ job.phase = "done"
169
+ except Exception as e: # never leave a job stuck in "running"
170
+ job.state, job.error, job.phase = "error", str(e), "done"
171
+
172
+
173
+ JobFactory = Callable[[], JobManager]