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
@@ -0,0 +1,104 @@
1
+ """Facts for Home and Runs, computed only from saved runs. No runs means no numbers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime, timedelta
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import psutil
10
+
11
+ from quantcheck.store import JsonResultsStore, RunResult
12
+
13
+ WEEK = timedelta(days=7)
14
+
15
+
16
+ def memory_now() -> dict[str, float]:
17
+ """Memory in use and total, in GB."""
18
+ vm = psutil.virtual_memory()
19
+ return {
20
+ "used_gb": round((vm.total - vm.available) / 1e9, 1),
21
+ "total_gb": round(vm.total / 1e9, 1),
22
+ }
23
+
24
+
25
+ def _name(r: RunResult) -> str:
26
+ model = str(r.config.get("model", "?")).rsplit("/", 1)[-1].lower()
27
+ tests = Path(str(r.config.get("tests", ""))).stem
28
+ return f"{model}-{tests}" if tests else model
29
+
30
+
31
+ def _sizes(r: RunResult) -> dict[str, float]:
32
+ return {c.label: c.file_size_mb for c in r.candidates if c.file_size_mb}
33
+
34
+
35
+ def run_row(r: RunResult) -> dict[str, Any]:
36
+ """One line of the runs table."""
37
+ rec = r.recommendation
38
+ kept = None
39
+ if rec and rec.recommended:
40
+ v = next((x for x in rec.verdicts if x.label == rec.recommended), None)
41
+ kept = v.relative if v else None
42
+ return {
43
+ "run_id": r.run_id, "name": _name(r), "created_at": r.created_at,
44
+ "model": r.config.get("model"), "n_prompts": len(r.testset.cases),
45
+ "versions": [c.label for c in r.candidates if c.status == "ok"],
46
+ "status": rec.status if rec else "not_scored",
47
+ "message": rec.message if rec else "Not scored: the judge did not run.",
48
+ "recommended": rec.recommended if rec else None,
49
+ "reference": rec.reference_label if rec else None,
50
+ "quality_kept": kept,
51
+ } # fmt: skip
52
+
53
+
54
+ def load_runs(runs_dir: Path) -> list[RunResult]:
55
+ """Every readable run, newest first. A damaged run never hides the others."""
56
+ store = JsonResultsStore(runs_dir)
57
+ out: list[RunResult] = []
58
+ if not runs_dir.is_dir():
59
+ return out
60
+ for d in sorted(runs_dir.iterdir(), reverse=True):
61
+ if not (d / "results.json").is_file():
62
+ continue
63
+ try:
64
+ out.append(store.load(d.name))
65
+ except (ValueError, FileNotFoundError):
66
+ continue
67
+ return out
68
+
69
+
70
+ def _when(r: RunResult) -> datetime | None:
71
+ try:
72
+ t = datetime.fromisoformat(r.created_at)
73
+ except ValueError:
74
+ return None
75
+ return t if t.tzinfo else t.replace(tzinfo=UTC)
76
+
77
+
78
+ def weekly(runs: list[RunResult], now: datetime | None = None) -> dict[str, Any]:
79
+ """Last 7 days. ``None`` values mean there is nothing to count yet (the screen shows a dash)."""
80
+ now = now or datetime.now(UTC)
81
+ recent = [r for r in runs if (t := _when(r)) is not None and now - t <= WEEK]
82
+ if not recent:
83
+ return {
84
+ "tests_run": 0,
85
+ "prompts_checked": None,
86
+ "memory_saved_gb": None,
87
+ "worse_answers": None,
88
+ }
89
+ prompts = sum(
90
+ len(r.testset.cases) * sum(c.status == "ok" for c in r.candidates) for r in recent
91
+ )
92
+ worse, saved = 0, 0.0
93
+ for r in recent:
94
+ rec = r.recommendation
95
+ if not rec:
96
+ continue
97
+ worse += sum(v.n_worse for v in rec.verdicts if v.verdict != "reference")
98
+ sizes = _sizes(r)
99
+ if rec.recommended and rec.reference_label in sizes and rec.recommended in sizes:
100
+ saved += max(0.0, sizes[rec.reference_label] - sizes[rec.recommended])
101
+ return {
102
+ "tests_run": len(recent), "prompts_checked": prompts,
103
+ "memory_saved_gb": round(saved / 1000, 1), "worse_answers": worse,
104
+ } # fmt: skip
@@ -0,0 +1,101 @@
1
+ """What this machine can do: chip, memory, runtimes, models already on disk."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import subprocess
8
+ from importlib import util
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from rich.console import Console
13
+
14
+ from quantcheck.hardware import hardware_info
15
+ from quantcheck.ui.summary import memory_now
16
+
17
+
18
+ def runtimes() -> dict[str, bool]:
19
+ """Which runtimes are installed (found without importing them)."""
20
+ return {
21
+ "mlx": util.find_spec("mlx_lm") is not None,
22
+ "llamacpp": util.find_spec("llama_cpp") is not None,
23
+ }
24
+
25
+
26
+ def ollama_models() -> list[str]:
27
+ """Names from ``ollama list``. Empty if Ollama is missing or not running."""
28
+ try:
29
+ out = subprocess.run(["ollama", "list"], capture_output=True, text=True, timeout=3)
30
+ except (OSError, subprocess.SubprocessError):
31
+ return []
32
+ if out.returncode != 0:
33
+ return []
34
+ return [line.split()[0] for line in out.stdout.splitlines()[1:] if line.strip()]
35
+
36
+
37
+ def hf_cache_dir() -> Path:
38
+ """The Hugging Face model cache folder."""
39
+ if "HF_HUB_CACHE" in os.environ:
40
+ return Path(os.environ["HF_HUB_CACHE"])
41
+ return Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface")) / "hub"
42
+
43
+
44
+ def cached_models(cache: Path | None = None) -> list[dict[str, Any]]:
45
+ """Models in the Hugging Face cache: id and size on disk (MB)."""
46
+ root = cache or hf_cache_dir()
47
+ found: list[dict[str, Any]] = []
48
+ if not root.is_dir():
49
+ return found
50
+ for d in sorted(root.glob("models--*")):
51
+ repo = d.name.removeprefix("models--").replace("--", "/", 1)
52
+ blobs = d / "blobs"
53
+ size = 0
54
+ if blobs.is_dir():
55
+ size = sum(f.stat().st_size for f in blobs.iterdir() if f.is_file())
56
+ found.append({"id": repo, "size_mb": round(size / 1e6, 1)})
57
+ return found
58
+
59
+
60
+ def system_status(data_path: Path) -> dict[str, Any]:
61
+ """Everything the status block and the Settings screen show."""
62
+ hw = hardware_info(data_path if data_path.exists() else Path.home())
63
+ return {
64
+ "hardware": hw,
65
+ "runtimes": runtimes(),
66
+ "python": platform.python_version(),
67
+ "ollama_models": ollama_models(),
68
+ "data_dir": str(data_path),
69
+ "memory": memory_now(),
70
+ }
71
+
72
+
73
+ def print_status(
74
+ console: Console, status: dict[str, Any], url: str, opening_browser: bool = True
75
+ ) -> None:
76
+ """The short block printed when ``quantcheck ui`` starts (design: Lab-AfterInstall).
77
+
78
+ Each line says what was checked on this Mac. A missing runtime is a warning with the fix,
79
+ never a green tick.
80
+ """
81
+ from quantcheck import __version__
82
+
83
+ hw, rt = status["hardware"], status["runtimes"]
84
+ ok, warn, dim = "[green]✓[/green]", "[yellow]![/yellow]", "[dim]–[/dim]"
85
+ ready = [name for name, found in (("MLX", rt["mlx"]), ("llama.cpp", rt["llamacpp"])) if found]
86
+ n = len(status["ollama_models"])
87
+ console.print(f"\n [bold green]QuantCheck Lab[/bold green] [dim]v{__version__} · beta[/dim]\n")
88
+ console.print(
89
+ f" {ok} {hw['chip']} · {hw['ram_gb']:g} GB memory · {hw['free_disk_gb']:g} GB free"
90
+ )
91
+ if ready:
92
+ console.print(f" {ok} {' and '.join(ready)} ready")
93
+ else:
94
+ console.print(f' {warn} No runtime installed. Run: pip install "quantcheck\\[mlx]"')
95
+ if n:
96
+ console.print(f" {ok} Found {n} Ollama model{'s' if n != 1 else ''}")
97
+ else:
98
+ console.print(f" {dim} No Ollama models found (optional)")
99
+ console.print(f"\n Lab running at [bold green underline]{url}[/bold green underline]")
100
+ console.print(" Opening your browser…" if opening_browser else " Open it in your browser.")
101
+ console.print("\n [dim]Runs only on this Mac. Press Ctrl+C to stop.[/dim]\n")
@@ -0,0 +1,243 @@
1
+ """Test-set files for the lab: list, read, validate, save, preview.
2
+
3
+ Everything is a plain ``tests.jsonl`` in the tests folder, the same file the CLI reads.
4
+ Saving goes through the CLI loader, so the lab can never write a file the CLI would reject.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from quantcheck import limits
15
+ from quantcheck.prompt import build_prompt
16
+ from quantcheck.scoring.checks import CHECKS, validate_checks
17
+ from quantcheck.tests_io import SetHeader, TestCase, TestFileError, TestSet, loads_tests
18
+
19
+ NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
20
+ TYPICAL_CONTEXT_TOKENS = 8192 # a common default window; the real one depends on the model
21
+
22
+ # One-line meaning for every check, shown in the checks picker. A test asserts none is missing.
23
+ CHECK_HELP: dict[str, dict[str, str]] = {
24
+ "language": {"what": "Answer is written in this language.", "value": "language code, e.g. hi"},
25
+ "json": {"what": "Answer is valid JSON (one code fence allowed).", "value": "none"},
26
+ "json_schema": {"what": "Answer is JSON matching your schema.", "value": "JSON schema"},
27
+ "regex": {"what": "Answer matches this pattern.", "value": "pattern"},
28
+ "contains": {"what": "Answer includes every one of these words.", "value": "text or list"},
29
+ "not_contains": {"what": "Answer includes none of these words.", "value": "text or list"},
30
+ "min_length": {"what": "Answer is at least this many characters.", "value": "number"},
31
+ "max_length": {"what": "Answer is at most this many characters.", "value": "number"},
32
+ "tool_call": {"what": "Model calls the expected tool with valid arguments.", "value": "none"},
33
+ "grounded": {"what": "Answer uses only the documents given (judge-assisted).", "value": "none"},
34
+ "refusal": {"what": "Model says it does not know if the documents lack the answer.",
35
+ "value": "none"},
36
+ } # fmt: skip
37
+
38
+ EXAMPLES: dict[str, Any] = {
39
+ "system": (
40
+ "You are Acme's support assistant. Reply in the customer's language. "
41
+ "Use only the documents provided. If the documents do not cover the question, "
42
+ "say you do not know."
43
+ ),
44
+ "documents": [
45
+ "Delivery policy: orders arrive in 3–5 working days after dispatch.",
46
+ "Returns: items can be returned within 7 days if unused. Refunds take 5 working days.",
47
+ "ரத்து செய்தல்: அனுப்புவதற்கு முன் 'My Orders' பகுதியில் ஆர்டரை ரத்து செய்யலாம்.",
48
+ ],
49
+ "tools": [
50
+ {
51
+ "name": "get_order_status",
52
+ "description": "Look up the status of an order by its id. Read-only.",
53
+ "parameters": {
54
+ "type": "object",
55
+ "properties": {"order_id": {"type": "string"}},
56
+ "required": ["order_id"],
57
+ },
58
+ },
59
+ {
60
+ "name": "cancel_order",
61
+ "description": "Cancel an order. Changes data.",
62
+ "changes_data": True,
63
+ "parameters": {
64
+ "type": "object",
65
+ "properties": {"order_id": {"type": "string"}},
66
+ "required": ["order_id"],
67
+ },
68
+ },
69
+ ],
70
+ "prompts": [
71
+ {
72
+ "id": "en-001",
73
+ "prompt": "When will my order arrive?",
74
+ "context": ["Delivery policy: orders arrive in 3–5 working days after dispatch."],
75
+ "expected": "Your order will arrive in 3 to 5 working days.",
76
+ "checks": [{"type": "language", "value": "en"}, {"type": "grounded"}],
77
+ "tags": ["english", "rag"],
78
+ },
79
+ {
80
+ "id": "hi-001",
81
+ "prompt": "रिटर्न की प्रक्रिया क्या है?",
82
+ "context": ["Returns: items can be returned within 7 days if unused."],
83
+ "checks": [{"type": "language", "value": "hi"}],
84
+ "tags": ["hindi", "rag"],
85
+ },
86
+ {
87
+ "id": "tl-031",
88
+ "prompt": "Where is my order A1043?",
89
+ "expected_tool_call": {"name": "get_order_status", "arguments": {"order_id": "A1043"}},
90
+ "tool_results": {"get_order_status": {"status": "shipped", "arrives": "Friday"}},
91
+ "checks": [{"type": "tool_call"}],
92
+ "tags": ["tools"],
93
+ },
94
+ {
95
+ "id": "oos-05",
96
+ "prompt": "Do you sell car insurance?",
97
+ "context": [],
98
+ "checks": [{"type": "refusal"}],
99
+ "tags": ["refusal"],
100
+ },
101
+ ],
102
+ }
103
+
104
+
105
+ def _dump(obj: object) -> str:
106
+ return json.dumps(obj, ensure_ascii=False)
107
+
108
+
109
+ def to_jsonl(header: dict[str, Any], cases: list[dict[str, Any]]) -> str:
110
+ """Serialize the editor's state as tests.jsonl text (header line only when it has content)."""
111
+ lines: list[str] = []
112
+ if header.get("system") or header.get("tools"):
113
+ lines.append(_dump({"type": "set", **{k: v for k, v in header.items() if k != "type"}}))
114
+ lines.extend(_dump(c) for c in cases)
115
+ return "\n".join(lines) + "\n"
116
+
117
+
118
+ def validate(header: dict[str, Any], cases: list[dict[str, Any]]) -> tuple[TestSet, str]:
119
+ """Run the same checks the CLI runs. Returns the parsed set and the jsonl text.
120
+
121
+ Raises ``TestFileError`` with a message naming the line (line 1 is the header when present).
122
+ """
123
+ text = to_jsonl(header, cases)
124
+ parsed = loads_tests(text)
125
+ if problems := validate_checks(parsed):
126
+ raise TestFileError("; ".join(problems))
127
+ return parsed, text
128
+
129
+
130
+ def safe_path(folder: Path, name: str) -> Path:
131
+ """Path of ``name`` inside ``folder``. Refuses anything that could land outside it."""
132
+ stem = name.removesuffix(".jsonl")
133
+ if not NAME.match(stem) or ".." in stem:
134
+ raise ValueError("name: use letters, digits, dash, underscore (max 64 characters)")
135
+ path = (folder / f"{stem}.jsonl").resolve()
136
+ if path.parent != folder.resolve():
137
+ raise ValueError("name: must stay inside the tests folder")
138
+ return path
139
+
140
+
141
+ def summarize(path: Path) -> dict[str, Any]:
142
+ """One row for the Test sets list. A broken file is listed with its error, never hidden."""
143
+ row: dict[str, Any] = {
144
+ "name": path.stem,
145
+ "file": path.name,
146
+ "path": str(path),
147
+ "modified": path.stat().st_mtime,
148
+ }
149
+ try:
150
+ ts = loads_tests(path.read_text(encoding="utf-8"))
151
+ except (TestFileError, UnicodeDecodeError) as e:
152
+ return {**row, "error": str(e), "prompts": 0, "tools": 0, "tags": [], "warnings": []}
153
+ tags = sorted({t for c in ts.cases for t in c.tags})
154
+ return {
155
+ **row,
156
+ "error": None,
157
+ "prompts": len(ts.cases),
158
+ "tools": len(ts.header.tools),
159
+ "documents": sum(len(c.context) for c in ts.cases),
160
+ "tags": tags,
161
+ "warnings": ts.warnings,
162
+ }
163
+
164
+
165
+ def read_set(path: Path) -> dict[str, Any]:
166
+ """The editor's state for an existing file: raw header and cases as plain JSON."""
167
+ ts = loads_tests(path.read_text(encoding="utf-8"))
168
+ return {
169
+ "name": path.stem,
170
+ "header": ts.header.model_dump(exclude={"type"}),
171
+ "cases": [c.model_dump(exclude_defaults=True) for c in ts.cases],
172
+ "warnings": ts.warnings,
173
+ }
174
+
175
+
176
+ def estimate_tokens(text: str) -> int:
177
+ """Rough size without loading a tokenizer: ~4 characters per token for Latin text,
178
+ ~1.5 for other scripts (Indian scripts split into many tokens)."""
179
+ ascii_chars = sum(1 for ch in text if ord(ch) < 128)
180
+ return round(ascii_chars / 4 + (len(text) - ascii_chars) / 1.5)
181
+
182
+
183
+ def _header_obj(header: dict[str, Any]) -> dict[str, Any]:
184
+ return {"type": "set", **{k: v for k, v in header.items() if k != "type"}}
185
+
186
+
187
+ def preview(header: dict[str, Any], case: dict[str, Any], context_tokens: int) -> dict[str, Any]:
188
+ """The full prompt for one case, built by the same code a run uses, plus a size estimate."""
189
+ h = SetHeader.model_validate(
190
+ {"type": "set", **{k: v for k, v in header.items() if k != "type"}}
191
+ )
192
+ c = TestCase.model_validate({"id": "preview", **case, "prompt": case.get("prompt") or "…"})
193
+ prompt = build_prompt(h, c)
194
+ tool_text = json.dumps(prompt.tools, ensure_ascii=False)
195
+ message_text = "\n".join(str(m["content"]) for m in prompt.messages)
196
+ tokens = estimate_tokens(message_text + tool_text)
197
+ fraction = tokens / context_tokens if context_tokens else 0
198
+ warning = None
199
+ if fraction >= 1:
200
+ warning = "This is more than the context window: the model could not read it all."
201
+ elif fraction >= limits.CONTEXT_WARN_FRACTION:
202
+ warning = f"This fills {fraction:.0%} of the context window: answers may be cut short."
203
+ return {
204
+ "messages": prompt.messages,
205
+ "tools": prompt.tools,
206
+ "tokens": tokens,
207
+ "context_tokens": context_tokens,
208
+ "fraction": round(fraction, 3),
209
+ "warning": warning,
210
+ }
211
+
212
+
213
+ def check_catalog() -> list[dict[str, str]]:
214
+ """Registered checks with their one-line meaning, for the picker."""
215
+ return [{"type": t, **CHECK_HELP.get(t, {"what": "", "value": "none"})} for t in sorted(CHECKS)]
216
+
217
+
218
+ def context_fit(
219
+ path: Path, context_tokens: int = TYPICAL_CONTEXT_TOKENS, answer_tokens: int = 512
220
+ ) -> dict[str, Any]:
221
+ """Size of the longest full prompt in a set, split into instructions+tools, documents, question.
222
+
223
+ Uses the same estimate as the preview. ``room`` is the answer space the run reserves.
224
+ """
225
+ ts = loads_tests(path.read_text(encoding="utf-8"))
226
+ tools = json.dumps([t.model_dump() for t in ts.header.tools], ensure_ascii=False)
227
+ fixed = estimate_tokens((ts.header.system or "") + tools)
228
+ worst: dict[str, Any] = {"fixed": fixed, "documents": 0, "question": 0, "id": None}
229
+ for c in ts.cases:
230
+ docs = estimate_tokens("\n".join(c.context))
231
+ question = estimate_tokens(c.prompt)
232
+ if docs + question >= worst["documents"] + worst["question"]:
233
+ worst = {"fixed": fixed, "documents": docs, "question": question, "id": c.id}
234
+ total = worst["fixed"] + worst["documents"] + worst["question"] + answer_tokens
235
+ fraction = total / context_tokens if context_tokens else 0
236
+ return {
237
+ **worst,
238
+ "room": answer_tokens,
239
+ "total": total,
240
+ "context_tokens": context_tokens,
241
+ "fraction": round(fraction, 3),
242
+ "warn": fraction >= limits.CONTEXT_WARN_FRACTION,
243
+ }
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.5
2
+ Name: quantcheck
3
+ Version: 0.0.1
4
+ Summary: Find the cheapest quantized version of an open model that still passes your own tests.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: fastapi>=0.165.0
9
+ Requires-Dist: huggingface-hub>=0.24
10
+ Requires-Dist: jinja2>=3.1
11
+ Requires-Dist: jsonschema>=4
12
+ Requires-Dist: keyring>=25.7.0
13
+ Requires-Dist: psutil>=5.9
14
+ Requires-Dist: pydantic>=2
15
+ Requires-Dist: pyyaml>=6
16
+ Requires-Dist: rich>=13
17
+ Requires-Dist: typer>=0.12
18
+ Requires-Dist: uvicorn>=0.54.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: httpx>=0.27; extra == 'dev'
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Requires-Dist: ruff>=0.5; extra == 'dev'
23
+ Provides-Extra: llamacpp
24
+ Requires-Dist: llama-cpp-python>=0.3; extra == 'llamacpp'
25
+ Provides-Extra: mlx
26
+ Requires-Dist: mlx-lm>=0.20; extra == 'mlx'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # quantcheck
30
+
31
+ Find the smallest quantized version of an open model that still passes **your** tests.
32
+
33
+ > **Early preview (0.0.1).** This release reserves the name and shows where the project is going. Sign-in settings are not bundled yet, so the lab stops at the sign-in screen; a usable beta follows. Runs only on your Mac: prompts, answers and models never leave the machine.
34
+
35
+ A quantized model stores its numbers with fewer bits (8, 6, 4, 3). It is smaller and faster, but can quietly get worse.
36
+ quantcheck runs every version on your own prompts, with the same instructions, documents and tools your app sends, then tells you:
37
+
38
+ - which version is the smallest one that is still safe, with a statistical check, or "cannot tell yet";
39
+ - every answer that changed or failed, side by side with the reference;
40
+ - speed, time to first token, peak memory and file size per version.
41
+
42
+ ## Quick start (about 2 minutes, plus model download)
43
+
44
+ Needs an Apple Silicon Mac (M1 or newer), Python 3.11+ and [uv](https://docs.astral.sh/uv/).
45
+
46
+ ```bash
47
+ pip install "quantcheck[mlx]" # add [llamacpp] for GGUF files
48
+ quantcheck hw # chip, memory, free disk
49
+ ```
50
+
51
+ Sign in once (opens your browser; needs the sign-in settings, see Status below):
52
+
53
+ ```bash
54
+ quantcheck login
55
+ ```
56
+
57
+ Run the example (Qwen3-8B, 3 versions, downloads a few GB the first time):
58
+
59
+ ```bash
60
+ quantcheck run examples/quantcheck.yaml
61
+ ```
62
+
63
+ Or use the local lab, which runs only on your Mac:
64
+
65
+ ```bash
66
+ quantcheck ui
67
+ ```
68
+
69
+ Open `runs/<run-id>/report.html` in a browser. Rebuild it any time:
70
+
71
+ ```bash
72
+ quantcheck report <run-id>
73
+ ```
74
+
75
+ Everything is also saved to `runs/<run-id>/results.json`.
76
+
77
+ ## Your own tests
78
+
79
+ `tests.jsonl` has one test per line. A first line with `"type": "set"` holds what your app sends with every question (instructions, tools). See [`examples/tests.jsonl`](examples/tests.jsonl): English, Hindi and Tamil prompts, a document-grounded answer, a tool call and an "I don't know" case.
80
+
81
+ ```json
82
+ {"id": "hi-001", "prompt": "ऑर्डर कैंसल कैसे करें?", "checks": [{"type": "language", "value": "hi"}], "tags": ["hindi"]}
83
+ ```
84
+
85
+ Checks (hard yes/no): `json`, `json_schema`, `regex`, `contains`, `not_contains`, `language`, `min_length`, `max_length`, `tool_call`, `grounded`, `refusal`.
86
+ Tools are never executed: quantcheck only reads the tool call the model writes and plays back the result you recorded.
87
+
88
+ How the score works: a failed check scores 0, otherwise a judge model scores 0 to 10 against the reference (the expected answer, or the largest version). The judge also runs on your Mac.
89
+
90
+ ## What a report looks like
91
+
92
+ `report.html` is one file that opens offline. It shows the recommendation ("use 6-bit", or "not proven yet"), speed, memory and file size per version, quality by tag, and every answer that changed or failed, side by side with the reference. With fewer than 20 prompts quantcheck refuses to name a safe version; use 100 or more for real decisions.
93
+
94
+ ## Status
95
+
96
+ Working: the local lab (`quantcheck ui`: sign in, start a test, watch progress, read reports), test loader, MLX and llama.cpp runners, checks, local judge, recommendation, terminal and HTML reports.
97
+ Sign-in (`quantcheck login`, `logout`, `whoami`) works with Google through a Supabase project (see `docs/decisions/001-auth-provider.md`). Token refresh and sign-out are tested with mocks only so far.
98
+ Not built yet: `judge: claude`, quantizing models yourself, GPU runners.
99
+
100
+ Known limits:
101
+
102
+ - The `language` check works by script (Devanagari, Tamil, Telugu, Bengali and more) and English. It cannot tell Hindi from Marathi, and does not support other Latin-script languages yet.
103
+ - llama.cpp peak memory is sampled from process memory: compare versions with each other, not with MLX numbers.
104
+ - Tool calls are read for Qwen/Hermes, Mistral and Llama 3 formats.
105
+
106
+ ## Develop
107
+
108
+ ```bash
109
+ uv sync --extra dev --extra mlx --extra llamacpp
110
+ uv run pytest -q # fast tests, no model downloads
111
+ uv run pytest -m slow # real tiny-model tests (downloads ~1 GB)
112
+ uv run ruff check . && uv run ruff format .
113
+ ```
114
+
115
+ License: Apache-2.0.
@@ -0,0 +1,79 @@
1
+ quantcheck/__init__.py,sha256=SKKHb8qqh7NhEsfDms1QVZQvfCFW2yWiC3UXl1ujxto,89
2
+ quantcheck/bench.py,sha256=j7h538o3knlFqleAHL7uJasmdKt8ams-4s-1Anmmlgg,1326
3
+ quantcheck/candidates.py,sha256=nESlPMbuYNfi7mPqIIvwgnLn49J3e-90etiBQ6isQIk,5323
4
+ quantcheck/cli.py,sha256=kr4_No9h78B58IAxhI21iue2TYyPMgsr1OYxjcxb-38,9327
5
+ quantcheck/config.py,sha256=QG14Cjcs0EHEEkC-0twnywC337VmbMrQ8L9fVbZ8axg,2330
6
+ quantcheck/hardware.py,sha256=8IocWaCVRmPbfEjEf56hbrotnRZEHdl2AtWAl1Kr1wk,1621
7
+ quantcheck/limits.py,sha256=6x8OrcH4KQFhqB2MKbJ1QVo40s7I70ExWorCeYKyljM,583
8
+ quantcheck/pipeline.py,sha256=nj0wpWwV8IMQzjTkezYZfF9NAfmQnz9F17fiAKw9f1w,6447
9
+ quantcheck/prompt.py,sha256=4Ix0gZiGCnOH647qx2HS60nLoifXdn6J0zQSUG3NFpA,2248
10
+ quantcheck/recommend.py,sha256=4rzhCZVQXYbJ7amQrzumlzVwOe1iUNdU3BykvXt2WFY,5989
11
+ quantcheck/settings.py,sha256=2eSDuBKGeB1YNgJKv3ajv0PW9MjJczkPmh4pLLMURos,395
12
+ quantcheck/store.py,sha256=EMX11hQeiTKBtd0uPMYQdXoHPLoOpnSiYDmX3hkXc3Q,2707
13
+ quantcheck/tests_io.py,sha256=xwh6-SCTfUUd01jhKyOOpSnFqKkPPKdoqJh-BOz51QI,5770
14
+ quantcheck/auth/__init__.py,sha256=L2NNsbiICBTAJv0Mo62ruY6C4EhOp9Zr2GM1m3abPJ0,339
15
+ quantcheck/auth/base.py,sha256=CJqCL2expM_YOwXx0e9MhEBxbR1iNgT424E-zcKMhH4,2319
16
+ quantcheck/auth/callback.py,sha256=YfcXqoRs0gofbdS_5L7oxA7sHBLRS8t8ubaMLza39MM,2838
17
+ quantcheck/auth/fake.py,sha256=lkwcBC50T5-iDH4N1y_wZXw6DJzuTlAidNK-dW1hpzg,1416
18
+ quantcheck/auth/service.py,sha256=kqKy9Vb1PYvpfx5Zx_3QmmesP1gwJliHYSqyvjW4XMk,1553
19
+ quantcheck/auth/store.py,sha256=Fylw66sFtpd-x69H_puWXkDfVy9hcIXH7UGsD8foljA,1626
20
+ quantcheck/auth/supabase.py,sha256=LoObPjDsGqUUn22SwcnXDyQUz5fGPBpxw62LpcEOeEk,6731
21
+ quantcheck/executors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ quantcheck/report/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ quantcheck/report/html.py,sha256=snfb_yQ-zz5iLk0b5uuZRiHK4rruYbaKINFaCl1gxUc,1192
24
+ quantcheck/report/terminal.py,sha256=2PDD77ijpezv9uQ9wqXBrFC0eZ07Amkp2O0kSf7yFxA,3251
25
+ quantcheck/report/tokens.py,sha256=68GqqOAsE2LsnHTbqq14BOplJPU9R8noF9DB5hnB0YA,2351
26
+ quantcheck/report/view.py,sha256=4EK0LJxR5bCJVkJ-vbjXCVVFfltB8rGq6rVZwEYzyPQ,6667
27
+ quantcheck/report/templates/report.html.j2,sha256=ohYGR0rCmcXWf7VaiDyRDIGgmOusoDx-ot4vXDcXYrQ,14249
28
+ quantcheck/runners/__init__.py,sha256=KruGc6Qyqb5c-DhttbP5QR1IazgJdg5JorJm97jPtqc,159
29
+ quantcheck/runners/base.py,sha256=mRNDbTi9JBHeT4I706Hpajsaj3z-iF-e4dK6--He6Qk,2702
30
+ quantcheck/runners/fake.py,sha256=tK0P0GHKhJqQjxGUK9kyweT-2CISnh1kyfrgxX-LyjE,2487
31
+ quantcheck/runners/llamacpp_runner.py,sha256=U7o25H_eIyCZuwMQAFYVZucuJRHN9QzzkJCChyrSJwk,7093
32
+ quantcheck/runners/mlx_runner.py,sha256=saXriYewZvFKTVxTKnohy4_YJLxpE6CKlZsUpeH3lYA,5740
33
+ quantcheck/runners/toolparse.py,sha256=h6tYY7RW5goo8bdWaHzP5f8cN-53L92cokS-6jtXDgo,4176
34
+ quantcheck/scoring/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
35
+ quantcheck/scoring/checks.py,sha256=7sDY1nJM767RMFGqvVbuWntq8Uxj7-wnJWfutjufqV8,12655
36
+ quantcheck/scoring/fake_judge.py,sha256=dUZBPXi4HPUFt4I8o-MN32wW2WfZ9dOM0QaC5lacgiw,1671
37
+ quantcheck/scoring/judge.py,sha256=xXXHoqJ0HBjK55Fhc5clThNHb_7rsI8w6cOGsksyozk,6410
38
+ quantcheck/scoring/language.py,sha256=6sYEkdjKNydb1ErEwWkFpQ35nS0c9ueTi3VeuxQ2IYA,3558
39
+ quantcheck/scoring/models.py,sha256=xABjCpcb0INwZj1pksg1fP3MGt8jbyBmDRpoJzS3xLw,3082
40
+ quantcheck/scoring/score.py,sha256=6HILbAM53qECGjEZgLr2yvjQ5bXzS3ksBGgv4ITZ6-Y,6496
41
+ quantcheck/scoring/stats.py,sha256=ng5BpB8GexBdtSGxKeo6i1pJbtAxA3eWR7EDmuJ_wD4,2184
42
+ quantcheck/ui/__init__.py,sha256=SGA1qTa2j-26Ivh-x_jlTi3COd0LhYgx-8c9qNxW5SQ,92
43
+ quantcheck/ui/app.py,sha256=1IdJkD7u4PUbmUN7ddJprIanGf3GMub-jXinH_5tdzs,22038
44
+ quantcheck/ui/catalog.py,sha256=g9vSv4uJFTGSJpqS2TtNt2jphSZ1H6ml5nkY6N1f6n4,2818
45
+ quantcheck/ui/chat.py,sha256=B5q62v9kZJXWzIKsicI7_i4yIAxgis-Iq4FuNNLyvz0,9096
46
+ quantcheck/ui/compare.py,sha256=0j_krybV2eXRji1SOzXqls9VpnGXeY8hLynbCtfjcsc,2604
47
+ quantcheck/ui/downloads.py,sha256=-Z1zZZAq6sYL_8zLs4L1znoLy_vOzTGXuA3_nfME9cs,6902
48
+ quantcheck/ui/jobs.py,sha256=KR5VqT2vIdiwQ3Go2B4WuQ9bGAJcgY3n-xT8vO3fGCc,7089
49
+ quantcheck/ui/modeldetail.py,sha256=KjvIjFi9APwfvOQJl_XRFst8_Tyd8ufcFSmFbwScxlo,4030
50
+ quantcheck/ui/reviews.py,sha256=aFmvuxy77PRH92BLlQhuKOzHB5eAuEz6mOvHn3DY_jc,2104
51
+ quantcheck/ui/security.py,sha256=vPxBPbZI3qRnFyJGrrKbZKIEQvpP0ADXmAb6BNAvGjI,1962
52
+ quantcheck/ui/summary.py,sha256=w9Oj627UZNBwuIJYhEFf1XwkzwN_AC-TYmg-8tZ8BdU,3595
53
+ quantcheck/ui/system.py,sha256=l8atw31o-YEhSIBYLShmN1dOr_5aryU0lpk06s5oxmw,3798
54
+ quantcheck/ui/testsets.py,sha256=en_Bfr9rPS6PNjjDy06P6NLhTcnD6eJdeBxph2mpEPE,10451
55
+ quantcheck/ui/static/chat.js,sha256=FUelPuf9ROffobdgzw2P4udt5k2PlHxZHSbSOZ6IwSM,26101
56
+ quantcheck/ui/static/fonts.css,sha256=NmuKXGlICRh9voAdbRi2T6xh_Xe540HWaMhViuO8hfg,9902
57
+ quantcheck/ui/static/index.html,sha256=H9D1wLIOtrhtGu7WyxOHLkURnz7X6yIBbRVVWq3lB1I,919
58
+ quantcheck/ui/static/lab.css,sha256=mBIHsCuzpBlFoSdLXsN6MDH9ro4Gu-PHDsnGpvpCbwY,79872
59
+ quantcheck/ui/static/lab.js,sha256=TFi5zRcAYzkcmieeKrr-wJ70DYPJQiU9L7bg_M-veUc,78084
60
+ quantcheck/ui/static/logo.svg,sha256=AxDj-1hECOgfcJKXr88iX_HUtZf-Pbky6aYJTWKBaUg,400
61
+ quantcheck/ui/static/review.js,sha256=zggLzxNyzuaB3OqA9TT90LY5U0KwrE3GIGzNBc4cBAQ,10932
62
+ quantcheck/ui/static/setup.js,sha256=ImHgBu6cHh7RkZy7MxHnVQweaaFgRKcEG13DtvCdH30,12235
63
+ quantcheck/ui/static/testsets.js,sha256=SrMES1smfIzVIGk6ppsIPm98apuh17ecceVwWjCJjmo,47896
64
+ quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2,sha256=LDK5s-41jBGeIQ9vUZX5vTSJTXinhf8uldYOcY5ACvQ,31340
65
+ quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2,sha256=nDjLLQ0tk8HubiH6eNt28T6n4V4VzGQhTHyom2qqNcQ,11596
66
+ quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2,sha256=Ep4FHyXGnI1uJyVWKzkWxaq-ooBt1rrKOjSeyZzqUUA,120232
67
+ quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2,sha256=S89EXis8Xtj3RN6IHKjWBgqi7Ly75W68WwwKzYvLI6c,13516
68
+ quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2,sha256=XRGBLEn14j0uFoJBzt1sW0LMOpUeQ7GG5Gx9mI70_8U,25016
69
+ quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2,sha256=Eg-QPvMYYVT58w0gJU4S4SAgsas2GcxNlQxIIr7JqaQ,31900
70
+ quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2,sha256=NJaxe5LhqWhz-4maq45dyspU2HkRWEejVrjna_YRyzY,17276
71
+ quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2,sha256=Y4tkFXmr5ddFBrvO7sj5IEi6oqYvChsKGaL8t5hbfBQ,50444
72
+ quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2,sha256=kmhOSs3nnvB3WM0JOAt-AemCTYsGHt3toEb3jBZtexI,32228
73
+ quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2,sha256=njiz8Vddq6NDXvCdM6ICWF7VvSBL0KjHRJVcdQwrkJE,14760
74
+ quantcheck/ui/static/fonts/README.md,sha256=MBNURcv4KfmTRseYGwUTwoYpK8Kn0dh50U-fynkoS6c,628
75
+ quantcheck-0.0.1.dist-info/METADATA,sha256=UO_lc-TamapJSANG0IHfNWLg4vNkiiG4mNrR3LQjFU4,4995
76
+ quantcheck-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
77
+ quantcheck-0.0.1.dist-info/entry_points.txt,sha256=glJ2UJ9Mzqo6gyz4k4UDlhOYSGkaKoR_Tvt26GFKqT0,50
78
+ quantcheck-0.0.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
79
+ quantcheck-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ quantcheck = quantcheck.cli:app