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.
- quantcheck/__init__.py +3 -0
- quantcheck/auth/__init__.py +6 -0
- quantcheck/auth/base.py +74 -0
- quantcheck/auth/callback.py +73 -0
- quantcheck/auth/fake.py +40 -0
- quantcheck/auth/service.py +49 -0
- quantcheck/auth/store.py +63 -0
- quantcheck/auth/supabase.py +168 -0
- quantcheck/bench.py +38 -0
- quantcheck/candidates.py +138 -0
- quantcheck/cli.py +251 -0
- quantcheck/config.py +63 -0
- quantcheck/executors/__init__.py +0 -0
- quantcheck/hardware.py +52 -0
- quantcheck/limits.py +19 -0
- quantcheck/pipeline.py +172 -0
- quantcheck/prompt.py +67 -0
- quantcheck/recommend.py +131 -0
- quantcheck/report/__init__.py +0 -0
- quantcheck/report/html.py +38 -0
- quantcheck/report/templates/report.html.j2 +272 -0
- quantcheck/report/terminal.py +90 -0
- quantcheck/report/tokens.py +41 -0
- quantcheck/report/view.py +161 -0
- quantcheck/runners/__init__.py +3 -0
- quantcheck/runners/base.py +87 -0
- quantcheck/runners/fake.py +68 -0
- quantcheck/runners/llamacpp_runner.py +185 -0
- quantcheck/runners/mlx_runner.py +153 -0
- quantcheck/runners/toolparse.py +107 -0
- quantcheck/scoring/__init__.py +0 -0
- quantcheck/scoring/checks.py +342 -0
- quantcheck/scoring/fake_judge.py +50 -0
- quantcheck/scoring/judge.py +171 -0
- quantcheck/scoring/language.py +99 -0
- quantcheck/scoring/models.py +92 -0
- quantcheck/scoring/score.py +167 -0
- quantcheck/scoring/stats.py +60 -0
- quantcheck/settings.py +14 -0
- quantcheck/store.py +88 -0
- quantcheck/tests_io.py +169 -0
- quantcheck/ui/__init__.py +1 -0
- quantcheck/ui/app.py +534 -0
- quantcheck/ui/catalog.py +47 -0
- quantcheck/ui/chat.py +211 -0
- quantcheck/ui/compare.py +63 -0
- quantcheck/ui/downloads.py +172 -0
- quantcheck/ui/jobs.py +173 -0
- quantcheck/ui/modeldetail.py +97 -0
- quantcheck/ui/reviews.py +59 -0
- quantcheck/ui/security.py +45 -0
- quantcheck/ui/static/chat.js +312 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
- quantcheck/ui/static/fonts/README.md +14 -0
- quantcheck/ui/static/fonts.css +228 -0
- quantcheck/ui/static/index.html +24 -0
- quantcheck/ui/static/lab.css +768 -0
- quantcheck/ui/static/lab.js +896 -0
- quantcheck/ui/static/logo.svg +5 -0
- quantcheck/ui/static/review.js +127 -0
- quantcheck/ui/static/setup.js +132 -0
- quantcheck/ui/static/testsets.js +527 -0
- quantcheck/ui/summary.py +104 -0
- quantcheck/ui/system.py +101 -0
- quantcheck/ui/testsets.py +243 -0
- quantcheck-0.0.1.dist-info/METADATA +115 -0
- quantcheck-0.0.1.dist-info/RECORD +79 -0
- quantcheck-0.0.1.dist-info/WHEEL +4 -0
- quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
- quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""What a report shows, built once from a saved run and used by both terminal and HTML."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
from quantcheck.bench import BenchSummary, summarize
|
|
8
|
+
from quantcheck.recommend import CHANGE
|
|
9
|
+
from quantcheck.scoring.models import AnswerScore, Recommendation
|
|
10
|
+
from quantcheck.store import RunResult
|
|
11
|
+
from quantcheck.tests_io import TestCase
|
|
12
|
+
|
|
13
|
+
MAX_CHANGES_PER_VERSION = 200
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Row(BaseModel):
|
|
17
|
+
"""One line of the version table."""
|
|
18
|
+
|
|
19
|
+
label: str
|
|
20
|
+
status: str # ok | skipped
|
|
21
|
+
reason: str | None = None
|
|
22
|
+
is_reference: bool = False
|
|
23
|
+
quality: float | None = None
|
|
24
|
+
relative: float | None = None
|
|
25
|
+
ci_low: float | None = None
|
|
26
|
+
ci_high: float | None = None
|
|
27
|
+
verdict: str = "-" # reference | safe | unsafe | uncertain | -
|
|
28
|
+
n_worse: int = 0
|
|
29
|
+
size_saving: float | None = None
|
|
30
|
+
bench: BenchSummary
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Change(BaseModel):
|
|
34
|
+
"""One answer that failed, or got clearly worse than the reference's."""
|
|
35
|
+
|
|
36
|
+
case_id: str
|
|
37
|
+
prompt: str
|
|
38
|
+
documents: list[str] = Field(default_factory=list)
|
|
39
|
+
tags: list[str] = Field(default_factory=list)
|
|
40
|
+
kind: str # check_failed | error | worse
|
|
41
|
+
why: str
|
|
42
|
+
reference_name: str # "Expected answer" or "<label> (reference)"
|
|
43
|
+
reference_text: str
|
|
44
|
+
answer_text: str
|
|
45
|
+
quality: float | None = None
|
|
46
|
+
reference_quality: float | None = None
|
|
47
|
+
judge_reason: str = ""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ReportView(BaseModel):
|
|
51
|
+
"""Everything a report needs."""
|
|
52
|
+
|
|
53
|
+
run_id: str
|
|
54
|
+
created_at: str
|
|
55
|
+
model: str
|
|
56
|
+
runtime: str
|
|
57
|
+
judge: str | None = None
|
|
58
|
+
judge_model: str | None = None
|
|
59
|
+
quality_limit: float
|
|
60
|
+
n_prompts: int
|
|
61
|
+
hardware: str
|
|
62
|
+
reference_label: str | None = None
|
|
63
|
+
scored: bool = False
|
|
64
|
+
recommendation: Recommendation | None = None
|
|
65
|
+
rows: list[Row]
|
|
66
|
+
tags: list[str] = Field(default_factory=list)
|
|
67
|
+
tag_quality: dict[str, dict[str, float]] = Field(default_factory=dict) # label -> tag -> q
|
|
68
|
+
changes: dict[str, list[Change]] = Field(default_factory=dict) # label -> changes
|
|
69
|
+
changes_total: dict[str, int] = Field(default_factory=dict) # before the display cap
|
|
70
|
+
reference_failures: list[Change] = Field(default_factory=list)
|
|
71
|
+
unscored: dict[str, int] = Field(default_factory=dict)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _hardware(env: dict) -> str:
|
|
75
|
+
hw = env.get("hardware", {})
|
|
76
|
+
return f"{hw.get('chip', '?')}, {hw.get('ram_gb', '?')} GB RAM"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _change(case: TestCase, ans: AnswerScore, text: str, ref_name: str, ref_text: str,
|
|
80
|
+
ref_q: float | None, kind: str) -> Change: # fmt: skip
|
|
81
|
+
failed = [c for c in ans.checks if c.passed is False]
|
|
82
|
+
why = ans.why or (failed[0].detail if failed else "")
|
|
83
|
+
if kind == "worse":
|
|
84
|
+
why = f"judge {ans.quality * 10:.0f}/10" if ans.quality is not None else why
|
|
85
|
+
return Change(
|
|
86
|
+
case_id=case.id, prompt=case.prompt, documents=case.context, tags=case.tags, kind=kind,
|
|
87
|
+
why=why, reference_name=ref_name, reference_text=ref_text, answer_text=text,
|
|
88
|
+
quality=ans.quality, reference_quality=ref_q,
|
|
89
|
+
judge_reason=(ans.judge.reason if ans.judge else ""),
|
|
90
|
+
) # fmt: skip
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def build_view(result: RunResult) -> ReportView:
|
|
94
|
+
"""Turn a saved run (scored or not) into the facts a report shows."""
|
|
95
|
+
sc, rec = result.scoring, result.recommendation
|
|
96
|
+
cases = {c.id: c for c in result.testset.cases}
|
|
97
|
+
score_by = {c.label: c for c in sc.candidates} if sc else {}
|
|
98
|
+
verdict_by = {v.label: v for v in rec.verdicts} if rec else {}
|
|
99
|
+
ref_label = sc.reference_label if sc else None
|
|
100
|
+
runs = {c.label: c for c in result.candidates}
|
|
101
|
+
|
|
102
|
+
rows: list[Row] = []
|
|
103
|
+
for cr in result.candidates:
|
|
104
|
+
s, v = score_by.get(cr.label), verdict_by.get(cr.label)
|
|
105
|
+
rows.append(Row(
|
|
106
|
+
label=cr.label, status=cr.status, reason=cr.reason, is_reference=cr.label == ref_label,
|
|
107
|
+
quality=s.quality if s else None, relative=v.relative if v else None,
|
|
108
|
+
ci_low=v.ci_low if v else None, ci_high=v.ci_high if v else None,
|
|
109
|
+
verdict=v.verdict if v else "-", n_worse=v.n_worse if v else 0,
|
|
110
|
+
size_saving=v.size_saving if v else None, bench=summarize(cr),
|
|
111
|
+
)) # fmt: skip
|
|
112
|
+
rows.sort(key=lambda r: (r.status != "ok", -(r.bench.file_size_mb or 0)))
|
|
113
|
+
|
|
114
|
+
tags = sorted({t for c in result.testset.cases for t in c.tags})
|
|
115
|
+
tag_quality = {s.label: s.per_tag for s in score_by.values()}
|
|
116
|
+
|
|
117
|
+
changes: dict[str, list[Change]] = {}
|
|
118
|
+
totals: dict[str, int] = {}
|
|
119
|
+
unscored: dict[str, int] = {}
|
|
120
|
+
ref_failures: list[Change] = []
|
|
121
|
+
ref_score = score_by.get(ref_label) if ref_label else None
|
|
122
|
+
ref_answers = {a.case_id: a for a in ref_score.answers} if ref_score else {}
|
|
123
|
+
ref_run_text = {a.case_id: a.final_text for a in runs[ref_label].answers} if ref_label else {}
|
|
124
|
+
|
|
125
|
+
for label, s in score_by.items():
|
|
126
|
+
raw = {a.case_id: a for a in runs[label].answers}
|
|
127
|
+
found: list[Change] = []
|
|
128
|
+
unscored[label] = sum(a.status == "unscored" for a in s.answers)
|
|
129
|
+
for ans in s.answers:
|
|
130
|
+
case = cases[ans.case_id]
|
|
131
|
+
ref_q = ref_answers[ans.case_id].quality if ans.case_id in ref_answers else None
|
|
132
|
+
if case.expected is not None:
|
|
133
|
+
ref_name, ref_text = "Expected answer", case.expected
|
|
134
|
+
else:
|
|
135
|
+
ref_name, ref_text = f"{ref_label} (reference)", ref_run_text.get(ans.case_id, "")
|
|
136
|
+
text = raw[ans.case_id].final_text
|
|
137
|
+
if ans.status in ("check_failed", "error"):
|
|
138
|
+
kind = ans.status
|
|
139
|
+
elif ans.quality is not None and ref_q is not None and ref_q - ans.quality > CHANGE:
|
|
140
|
+
kind = "worse"
|
|
141
|
+
else:
|
|
142
|
+
continue
|
|
143
|
+
if label == ref_label and kind == "worse":
|
|
144
|
+
continue
|
|
145
|
+
found.append(_change(case, ans, text, ref_name, ref_text, ref_q, kind))
|
|
146
|
+
if label == ref_label:
|
|
147
|
+
ref_failures = found
|
|
148
|
+
else:
|
|
149
|
+
totals[label] = len(found)
|
|
150
|
+
changes[label] = found[:MAX_CHANGES_PER_VERSION]
|
|
151
|
+
|
|
152
|
+
return ReportView(
|
|
153
|
+
run_id=result.run_id, created_at=result.created_at, model=str(result.config.get("model")),
|
|
154
|
+
runtime=str(result.config.get("runtime")), judge=sc.judge if sc else None,
|
|
155
|
+
judge_model=sc.judge_model if sc else None,
|
|
156
|
+
quality_limit=float(result.config.get("quality_limit", 0.97)),
|
|
157
|
+
n_prompts=len(result.testset.cases), hardware=_hardware(result.environment),
|
|
158
|
+
reference_label=ref_label, scored=sc is not None, recommendation=rec, rows=rows,
|
|
159
|
+
tags=tags, tag_quality=tag_quality, changes=changes, changes_total=totals,
|
|
160
|
+
reference_failures=ref_failures, unscored=unscored,
|
|
161
|
+
) # fmt: skip
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Runner interface and registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
from quantcheck.candidates import Candidate
|
|
11
|
+
from quantcheck.prompt import Prompt
|
|
12
|
+
from quantcheck.tests_io import ToolCall
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GenSettings(BaseModel):
|
|
16
|
+
"""Identical for every candidate in a run."""
|
|
17
|
+
|
|
18
|
+
temperature: float = 0.0
|
|
19
|
+
seed: int = 42
|
|
20
|
+
max_tokens: int = 512
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Generation(BaseModel):
|
|
24
|
+
"""One model answer plus measurements."""
|
|
25
|
+
|
|
26
|
+
text: str
|
|
27
|
+
tool_calls: list[ToolCall] = Field(default_factory=list) # parsed from the model's output
|
|
28
|
+
prompt_tokens: int = 0
|
|
29
|
+
output_tokens: int = 0
|
|
30
|
+
ttft_s: float | None = None # time to first token
|
|
31
|
+
prompt_tps: float | None = None # prompt tokens processed per second
|
|
32
|
+
gen_tps: float | None = None # answer tokens generated per second
|
|
33
|
+
total_s: float | None = None
|
|
34
|
+
peak_memory_mb: float | None = None
|
|
35
|
+
error: str | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Runner(ABC):
|
|
39
|
+
"""Loads one candidate at a time and generates answers."""
|
|
40
|
+
|
|
41
|
+
name: str
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def load(self, candidate: Candidate) -> None:
|
|
45
|
+
"""Load the model. Raise on failure; the pipeline skips this candidate."""
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def generate(self, prompt: Prompt, settings: GenSettings) -> Generation:
|
|
49
|
+
"""Answer one prompt using the model's own chat template and tool format."""
|
|
50
|
+
|
|
51
|
+
def stream(
|
|
52
|
+
self, prompt: Prompt, settings: GenSettings, on_text: Callable[[str], None]
|
|
53
|
+
) -> Generation:
|
|
54
|
+
"""Like ``generate`` but reports the answer so far through ``on_text``.
|
|
55
|
+
|
|
56
|
+
The default answers in one piece. Runners that can stream override it (Chat uses it).
|
|
57
|
+
"""
|
|
58
|
+
gen = self.generate(prompt, settings)
|
|
59
|
+
on_text(gen.text)
|
|
60
|
+
return gen
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def unload(self) -> None:
|
|
64
|
+
"""Free memory before the next candidate loads."""
|
|
65
|
+
|
|
66
|
+
def model_info(self) -> dict:
|
|
67
|
+
"""Facts about the loaded model, e.g. ``{"file_size_mb": 412.3}``. Called after load."""
|
|
68
|
+
return {}
|
|
69
|
+
|
|
70
|
+
def capabilities(self) -> dict:
|
|
71
|
+
"""What this runner supports (tools, formats...). Override as needed."""
|
|
72
|
+
return {}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_REGISTRY: dict[str, Callable[[], Runner]] = {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def register_runner(name: str, factory: Callable[[], Runner]) -> None:
|
|
79
|
+
"""Register a runner factory under a name (mlx, llamacpp, ...)."""
|
|
80
|
+
_REGISTRY[name] = factory
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_runner(name: str) -> Runner:
|
|
84
|
+
"""Create a runner by name; fail clearly if unknown."""
|
|
85
|
+
if name not in _REGISTRY:
|
|
86
|
+
raise KeyError(f"Unknown runner '{name}'. Known: {sorted(_REGISTRY)}")
|
|
87
|
+
return _REGISTRY[name]()
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""FakeRunner: canned answers for unit tests. Never loads a model."""
|
|
2
|
+
|
|
3
|
+
from quantcheck.candidates import Candidate
|
|
4
|
+
from quantcheck.prompt import Prompt
|
|
5
|
+
from quantcheck.runners.base import Generation, GenSettings, Runner, register_runner
|
|
6
|
+
from quantcheck.tests_io import ToolCall
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FakeRunner(Runner):
|
|
10
|
+
"""Canned answers. A key matches when it appears in the last user message."""
|
|
11
|
+
|
|
12
|
+
name = "fake"
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
answers: dict[str, str] | None = None,
|
|
17
|
+
default: str = "ok",
|
|
18
|
+
tool_calls: dict[str, ToolCall] | None = None,
|
|
19
|
+
after_tool: str = "done",
|
|
20
|
+
fail_load: set[str] | None = None,
|
|
21
|
+
by_quant: dict[str, dict[str, str]] | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.answers = answers or {}
|
|
24
|
+
self.default = default
|
|
25
|
+
self.tool_calls = tool_calls or {}
|
|
26
|
+
self.after_tool = after_tool
|
|
27
|
+
self.fail_load = fail_load or set() # quantization labels that fail to load
|
|
28
|
+
self.by_quant = by_quant or {} # label -> own answers, to simulate a worse version
|
|
29
|
+
self.loaded: Candidate | None = None
|
|
30
|
+
self.load_log: list[str] = []
|
|
31
|
+
|
|
32
|
+
def load(self, candidate: Candidate) -> None:
|
|
33
|
+
if candidate.quantization in self.fail_load:
|
|
34
|
+
raise RuntimeError(f"cannot load {candidate.quantization}")
|
|
35
|
+
self.loaded = candidate
|
|
36
|
+
self.load_log.append(candidate.quantization)
|
|
37
|
+
|
|
38
|
+
def generate(self, prompt: Prompt, settings: GenSettings) -> Generation:
|
|
39
|
+
if self.loaded is None:
|
|
40
|
+
return Generation(text="", error="no candidate loaded")
|
|
41
|
+
text, calls = self._answer(prompt)
|
|
42
|
+
return Generation(
|
|
43
|
+
text=text,
|
|
44
|
+
tool_calls=calls,
|
|
45
|
+
prompt_tokens=len(prompt.user_text.split()),
|
|
46
|
+
output_tokens=len(text.split()),
|
|
47
|
+
ttft_s=0.0,
|
|
48
|
+
total_s=0.0,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def _answer(self, prompt: Prompt) -> tuple[str, list[ToolCall]]:
|
|
52
|
+
if prompt.messages[-1]["role"] == "tool":
|
|
53
|
+
return self.after_tool, []
|
|
54
|
+
user = prompt.user_text
|
|
55
|
+
for key, call in self.tool_calls.items():
|
|
56
|
+
if key in user:
|
|
57
|
+
return "", [call]
|
|
58
|
+
own = self.by_quant.get(self.loaded.quantization if self.loaded else "", {})
|
|
59
|
+
for key, text in {**self.answers, **own}.items():
|
|
60
|
+
if key in user:
|
|
61
|
+
return text, []
|
|
62
|
+
return self.default, []
|
|
63
|
+
|
|
64
|
+
def unload(self) -> None:
|
|
65
|
+
self.loaded = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
register_runner("fake", FakeRunner)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""llama.cpp runner: GGUF models, Metal on Apple Silicon. Needs ``quantcheck[llamacpp]``.
|
|
2
|
+
|
|
3
|
+
The prompt is rendered here with the model's own chat template (read from the GGUF file),
|
|
4
|
+
because ``create_chat_completion`` cannot turn thinking off and does not read tool calls.
|
|
5
|
+
Tool calls are read by ``toolparse`` and never run.
|
|
6
|
+
|
|
7
|
+
Memory: llama.cpp has no peak-memory counter, so ``peak_memory_mb`` is the highest resident
|
|
8
|
+
memory of this process sampled during generation. It is an approximation; compare versions
|
|
9
|
+
with it, not against MLX numbers.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import psutil
|
|
19
|
+
|
|
20
|
+
from quantcheck.candidates import Candidate
|
|
21
|
+
from quantcheck.prompt import Prompt
|
|
22
|
+
from quantcheck.runners.base import Generation, GenSettings, Runner, register_runner
|
|
23
|
+
from quantcheck.runners.toolparse import clean_answer, detect_style, parse_tool_calls
|
|
24
|
+
|
|
25
|
+
DEFAULT_N_CTX = 8192
|
|
26
|
+
SAMPLE_EVERY_S = 0.02
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _PeakRSS:
|
|
30
|
+
"""Samples this process's resident memory in a thread and keeps the highest value."""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._proc = psutil.Process()
|
|
34
|
+
self._stop = threading.Event()
|
|
35
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
36
|
+
self.peak_mb = 0.0
|
|
37
|
+
|
|
38
|
+
def _sample(self) -> None:
|
|
39
|
+
self.peak_mb = max(self.peak_mb, self._proc.memory_info().rss / 1e6)
|
|
40
|
+
|
|
41
|
+
def _run(self) -> None:
|
|
42
|
+
while not self._stop.is_set():
|
|
43
|
+
self._sample()
|
|
44
|
+
self._stop.wait(SAMPLE_EVERY_S)
|
|
45
|
+
|
|
46
|
+
def __enter__(self) -> _PeakRSS:
|
|
47
|
+
self._sample()
|
|
48
|
+
self._thread.start()
|
|
49
|
+
return self
|
|
50
|
+
|
|
51
|
+
def __exit__(self, *exc: object) -> None:
|
|
52
|
+
self._stop.set()
|
|
53
|
+
self._thread.join()
|
|
54
|
+
self._sample()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def fit_problem(n_prompt: int, max_tokens: int, n_ctx: int) -> str | None:
|
|
58
|
+
"""Why the prompt cannot run in this context window, or None. Never truncates silently."""
|
|
59
|
+
if n_prompt + max_tokens > n_ctx:
|
|
60
|
+
return (
|
|
61
|
+
f"prompt is {n_prompt} tokens and the answer may use {max_tokens} more, but the "
|
|
62
|
+
f"context window is {n_ctx}. Shorten the documents or instructions, or raise n_ctx."
|
|
63
|
+
)
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class LlamaCppRunner(Runner):
|
|
68
|
+
"""Runs GGUF models with llama-cpp-python."""
|
|
69
|
+
|
|
70
|
+
name = "llamacpp"
|
|
71
|
+
|
|
72
|
+
def __init__(self) -> None:
|
|
73
|
+
self._llm = None
|
|
74
|
+
self._candidate: Candidate | None = None
|
|
75
|
+
self._formatter = None
|
|
76
|
+
self._eos_text = ""
|
|
77
|
+
self._style: str | None = None
|
|
78
|
+
self._n_ctx = DEFAULT_N_CTX
|
|
79
|
+
|
|
80
|
+
def load(self, candidate: Candidate) -> None:
|
|
81
|
+
try:
|
|
82
|
+
from llama_cpp import Llama, llama_chat_format
|
|
83
|
+
except ImportError as e:
|
|
84
|
+
raise RuntimeError(
|
|
85
|
+
"llama-cpp-python is not installed. Run: pip install 'quantcheck[llamacpp]'"
|
|
86
|
+
) from e
|
|
87
|
+
self._n_ctx = int(candidate.extra.get("n_ctx", DEFAULT_N_CTX))
|
|
88
|
+
common = dict(n_gpu_layers=-1, n_ctx=self._n_ctx, seed=0, verbose=False)
|
|
89
|
+
path = Path(candidate.model).expanduser()
|
|
90
|
+
if path.is_file():
|
|
91
|
+
llm = Llama(model_path=str(path), **common)
|
|
92
|
+
else:
|
|
93
|
+
pattern = candidate.extra.get("file_pattern")
|
|
94
|
+
if not pattern:
|
|
95
|
+
raise RuntimeError(
|
|
96
|
+
f"'{candidate.model}' is not a .gguf file and has no file_pattern"
|
|
97
|
+
)
|
|
98
|
+
llm = Llama.from_pretrained(candidate.model, filename=pattern, **common)
|
|
99
|
+
template = llm.metadata.get("tokenizer.chat_template")
|
|
100
|
+
if not template:
|
|
101
|
+
raise RuntimeError("this GGUF file has no chat template, so prompts cannot be built")
|
|
102
|
+
self._llm, self._candidate = llm, candidate
|
|
103
|
+
self._style = detect_style(template)
|
|
104
|
+
self._eos_text = self._token_text(llm.token_eos())
|
|
105
|
+
self._formatter = llama_chat_format.Jinja2ChatFormatter(
|
|
106
|
+
template=template,
|
|
107
|
+
eos_token=self._eos_text,
|
|
108
|
+
bos_token=self._token_text(llm.token_bos()),
|
|
109
|
+
add_generation_prompt=True,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def _token_text(self, token_id: int) -> str:
|
|
113
|
+
if token_id is None or token_id < 0:
|
|
114
|
+
return ""
|
|
115
|
+
return self._llm.detokenize([token_id], special=True).decode("utf-8", errors="ignore")
|
|
116
|
+
|
|
117
|
+
def model_info(self) -> dict:
|
|
118
|
+
if not self._llm:
|
|
119
|
+
return {}
|
|
120
|
+
p = Path(getattr(self._llm, "model_path", "") or "")
|
|
121
|
+
return {"file_size_mb": round(p.stat().st_size / 1e6, 1)} if p.is_file() else {}
|
|
122
|
+
|
|
123
|
+
def capabilities(self) -> dict:
|
|
124
|
+
return {"tools": self._style is not None, "tool_format": self._style}
|
|
125
|
+
|
|
126
|
+
def _render(self, prompt: Prompt) -> str:
|
|
127
|
+
# enable_thinking=False: scoring runs must be short and repeatable. Templates with no
|
|
128
|
+
# such switch ignore it.
|
|
129
|
+
return self._formatter(
|
|
130
|
+
messages=prompt.messages, tools=prompt.tools or None, enable_thinking=False
|
|
131
|
+
).prompt
|
|
132
|
+
|
|
133
|
+
def generate(self, prompt: Prompt, settings: GenSettings) -> Generation:
|
|
134
|
+
if self._llm is None:
|
|
135
|
+
return Generation(text="", error="no model loaded")
|
|
136
|
+
tokens = self._llm.tokenize(
|
|
137
|
+
self._render(prompt).encode("utf-8"), add_bos=False, special=True
|
|
138
|
+
)
|
|
139
|
+
if problem := fit_problem(len(tokens), settings.max_tokens, self._n_ctx):
|
|
140
|
+
return Generation(text="", prompt_tokens=len(tokens), error=problem)
|
|
141
|
+
|
|
142
|
+
self._llm.reset() # no prefix reuse between prompts: every timing is a cold start
|
|
143
|
+
parts: list[str] = []
|
|
144
|
+
n_out = 0
|
|
145
|
+
ttft = None
|
|
146
|
+
t0 = time.perf_counter()
|
|
147
|
+
with _PeakRSS() as mem:
|
|
148
|
+
stream = self._llm.create_completion(
|
|
149
|
+
tokens, max_tokens=settings.max_tokens, temperature=settings.temperature,
|
|
150
|
+
seed=settings.seed, stop=[self._eos_text] if self._eos_text else None, stream=True,
|
|
151
|
+
) # fmt: skip
|
|
152
|
+
for chunk in stream:
|
|
153
|
+
if ttft is None:
|
|
154
|
+
ttft = time.perf_counter() - t0
|
|
155
|
+
parts.append(chunk["choices"][0]["text"])
|
|
156
|
+
n_out += 1
|
|
157
|
+
total = time.perf_counter() - t0
|
|
158
|
+
return self._to_generation("".join(parts), len(tokens), n_out, ttft, total, mem.peak_mb)
|
|
159
|
+
|
|
160
|
+
def _to_generation(
|
|
161
|
+
self, raw: str, n_prompt: int, n_out: int, ttft: float | None, total: float, mem_mb: float
|
|
162
|
+
) -> Generation:
|
|
163
|
+
text, calls, error = parse_tool_calls(raw, self._style)
|
|
164
|
+
gen_s = (total - ttft) if ttft is not None else 0.0
|
|
165
|
+
return Generation(
|
|
166
|
+
text=clean_answer(text),
|
|
167
|
+
tool_calls=calls,
|
|
168
|
+
prompt_tokens=n_prompt,
|
|
169
|
+
output_tokens=n_out,
|
|
170
|
+
ttft_s=ttft,
|
|
171
|
+
total_s=total,
|
|
172
|
+
prompt_tps=round(n_prompt / ttft, 1) if ttft else None,
|
|
173
|
+
gen_tps=round((n_out - 1) / gen_s, 1) if n_out > 1 and gen_s > 0 else None,
|
|
174
|
+
peak_memory_mb=round(mem_mb, 1),
|
|
175
|
+
error=error,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def unload(self) -> None:
|
|
179
|
+
self._llm = self._formatter = self._candidate = None
|
|
180
|
+
import gc
|
|
181
|
+
|
|
182
|
+
gc.collect()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
register_runner("llamacpp", LlamaCppRunner)
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""MLX runner (Apple Silicon). Needs ``pip install quantcheck[mlx]``.
|
|
2
|
+
|
|
3
|
+
Uses mlx-lm: the model's own chat template (with its native tool format) builds the
|
|
4
|
+
prompt, and the model's own tool parser reads any tool call it writes. Tools are never run.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from quantcheck.candidates import Candidate
|
|
13
|
+
from quantcheck.prompt import Prompt
|
|
14
|
+
from quantcheck.runners.base import Generation, GenSettings, Runner, register_runner
|
|
15
|
+
from quantcheck.runners.toolparse import clean_answer, split_tool_calls # noqa: F401
|
|
16
|
+
from quantcheck.tests_io import ToolCall
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _dir_size_mb(path: Path) -> float:
|
|
20
|
+
files = [f for f in path.rglob("*") if f.is_file() and f.suffix in {".safetensors", ".gguf"}]
|
|
21
|
+
return round(sum(f.stat().st_size for f in files) / 1e6, 1)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _model_dir(model: str) -> Path | None:
|
|
25
|
+
"""Local folder of a loaded model: the path itself, or its Hugging Face cache snapshot.
|
|
26
|
+
|
|
27
|
+
Reads the cache folder directly: mlx-lm downloads only the files it needs, so
|
|
28
|
+
``snapshot_download(local_files_only=True)`` reports the snapshot as incomplete.
|
|
29
|
+
"""
|
|
30
|
+
p = Path(model).expanduser()
|
|
31
|
+
if p.is_dir():
|
|
32
|
+
return p
|
|
33
|
+
try:
|
|
34
|
+
from huggingface_hub import constants
|
|
35
|
+
|
|
36
|
+
repo = Path(constants.HF_HUB_CACHE) / f"models--{model.replace('/', '--')}"
|
|
37
|
+
ref = repo / "refs" / "main"
|
|
38
|
+
snap = repo / "snapshots" / ref.read_text().strip() if ref.is_file() else None
|
|
39
|
+
if snap is None or not snap.is_dir():
|
|
40
|
+
snaps = sorted((repo / "snapshots").iterdir(), key=lambda d: d.stat().st_mtime)
|
|
41
|
+
snap = snaps[-1] if snaps else None
|
|
42
|
+
return snap
|
|
43
|
+
except (OSError, ImportError):
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class MLXRunner(Runner):
|
|
48
|
+
"""Runs MLX-format models with mlx-lm."""
|
|
49
|
+
|
|
50
|
+
name = "mlx"
|
|
51
|
+
|
|
52
|
+
def __init__(self) -> None:
|
|
53
|
+
self._model = None
|
|
54
|
+
self._tok = None
|
|
55
|
+
self._candidate: Candidate | None = None
|
|
56
|
+
|
|
57
|
+
def load(self, candidate: Candidate) -> None:
|
|
58
|
+
try:
|
|
59
|
+
from mlx_lm import load
|
|
60
|
+
except ImportError as e:
|
|
61
|
+
raise RuntimeError("mlx-lm is not installed. Run: pip install 'quantcheck[mlx]'") from e
|
|
62
|
+
self._model, self._tok = load(candidate.model)
|
|
63
|
+
self._candidate = candidate
|
|
64
|
+
|
|
65
|
+
def model_info(self) -> dict:
|
|
66
|
+
d = _model_dir(self._candidate.model) if self._candidate else None
|
|
67
|
+
return {"file_size_mb": _dir_size_mb(d)} if d else {}
|
|
68
|
+
|
|
69
|
+
def capabilities(self) -> dict:
|
|
70
|
+
return {"tools": bool(self._tok and self._tok.has_tool_calling)}
|
|
71
|
+
|
|
72
|
+
def _render(self, prompt: Prompt) -> str:
|
|
73
|
+
# enable_thinking=False: scoring runs must be short and repeatable. Templates that
|
|
74
|
+
# have no such switch ignore it.
|
|
75
|
+
return self._tok.apply_chat_template(
|
|
76
|
+
prompt.messages,
|
|
77
|
+
tools=prompt.tools or None,
|
|
78
|
+
add_generation_prompt=True,
|
|
79
|
+
tokenize=False,
|
|
80
|
+
enable_thinking=False,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def generate(self, prompt: Prompt, settings: GenSettings) -> Generation:
|
|
84
|
+
return self._generate(prompt, settings, None)
|
|
85
|
+
|
|
86
|
+
def stream(self, prompt: Prompt, settings: GenSettings, on_text) -> Generation:
|
|
87
|
+
return self._generate(prompt, settings, on_text)
|
|
88
|
+
|
|
89
|
+
def _generate(self, prompt: Prompt, settings: GenSettings, on_text) -> Generation:
|
|
90
|
+
if self._model is None:
|
|
91
|
+
return Generation(text="", error="no model loaded")
|
|
92
|
+
import mlx.core as mx
|
|
93
|
+
from mlx_lm import stream_generate
|
|
94
|
+
from mlx_lm.sample_utils import make_sampler
|
|
95
|
+
|
|
96
|
+
mx.random.seed(settings.seed)
|
|
97
|
+
mx.reset_peak_memory()
|
|
98
|
+
rendered = self._render(prompt)
|
|
99
|
+
t0 = time.perf_counter()
|
|
100
|
+
ttft = None
|
|
101
|
+
parts: list[str] = []
|
|
102
|
+
last = None
|
|
103
|
+
for resp in stream_generate(
|
|
104
|
+
self._model,
|
|
105
|
+
self._tok,
|
|
106
|
+
rendered,
|
|
107
|
+
max_tokens=settings.max_tokens,
|
|
108
|
+
sampler=make_sampler(temp=settings.temperature),
|
|
109
|
+
):
|
|
110
|
+
if ttft is None:
|
|
111
|
+
ttft = time.perf_counter() - t0
|
|
112
|
+
parts.append(resp.text)
|
|
113
|
+
last = resp
|
|
114
|
+
if on_text:
|
|
115
|
+
on_text("".join(parts))
|
|
116
|
+
total = time.perf_counter() - t0
|
|
117
|
+
return self._to_generation("".join(parts), last, ttft, total, bool(prompt.tools))
|
|
118
|
+
|
|
119
|
+
def _to_generation(self, raw: str, last, ttft: float | None, total: float, tools: bool):
|
|
120
|
+
text, segments = split_tool_calls(raw, self._tok.tool_call_start, self._tok.tool_call_end)
|
|
121
|
+
calls: list[ToolCall] = []
|
|
122
|
+
error = None
|
|
123
|
+
for seg in segments:
|
|
124
|
+
try:
|
|
125
|
+
parsed = self._tok.tool_parser(seg, None)
|
|
126
|
+
for tc in parsed if isinstance(parsed, list) else [parsed]:
|
|
127
|
+
calls.append(ToolCall(name=tc["name"], arguments=tc.get("arguments") or {}))
|
|
128
|
+
except Exception as e: # a malformed call is a quality failure, shown as such
|
|
129
|
+
error = f"unreadable tool call: {e}"
|
|
130
|
+
return Generation(
|
|
131
|
+
text=clean_answer(text),
|
|
132
|
+
tool_calls=calls,
|
|
133
|
+
prompt_tokens=last.prompt_tokens if last else 0,
|
|
134
|
+
output_tokens=last.generation_tokens if last else 0,
|
|
135
|
+
ttft_s=ttft,
|
|
136
|
+
total_s=total,
|
|
137
|
+
prompt_tps=last.prompt_tps if last else None,
|
|
138
|
+
gen_tps=last.generation_tps if last else None,
|
|
139
|
+
peak_memory_mb=round(last.peak_memory * 1024, 1) if last else None,
|
|
140
|
+
error=error,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def unload(self) -> None:
|
|
144
|
+
self._model = self._tok = self._candidate = None
|
|
145
|
+
try:
|
|
146
|
+
import mlx.core as mx
|
|
147
|
+
|
|
148
|
+
mx.clear_cache()
|
|
149
|
+
except ImportError:
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
register_runner("mlx", MLXRunner)
|