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,99 @@
|
|
|
1
|
+
"""Script-based language detection for the ``language`` check.
|
|
2
|
+
|
|
3
|
+
Deterministic and dependency-free. It tells languages apart when they use different
|
|
4
|
+
scripts (Tamil, Telugu, Bengali, Devanagari, Arabic, Cyrillic, CJK...). It cannot separate
|
|
5
|
+
languages that share a script: Hindi vs Marathi (both Devanagari), Hindi vs Hinglish
|
|
6
|
+
(Latin script), English vs French. Those codes are rejected up front instead of guessed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
Ranges = tuple[tuple[int, int], ...]
|
|
14
|
+
|
|
15
|
+
DEVANAGARI: Ranges = ((0x0900, 0x097F),)
|
|
16
|
+
BENGALI: Ranges = ((0x0980, 0x09FF),)
|
|
17
|
+
GURMUKHI: Ranges = ((0x0A00, 0x0A7F),)
|
|
18
|
+
GUJARATI: Ranges = ((0x0A80, 0x0AFF),)
|
|
19
|
+
ODIA: Ranges = ((0x0B00, 0x0B7F),)
|
|
20
|
+
TAMIL: Ranges = ((0x0B80, 0x0BFF),)
|
|
21
|
+
TELUGU: Ranges = ((0x0C00, 0x0C7F),)
|
|
22
|
+
KANNADA: Ranges = ((0x0C80, 0x0CFF),)
|
|
23
|
+
MALAYALAM: Ranges = ((0x0D00, 0x0D7F),)
|
|
24
|
+
THAI: Ranges = ((0x0E00, 0x0E7F),)
|
|
25
|
+
HEBREW: Ranges = ((0x0590, 0x05FF),)
|
|
26
|
+
ARABIC: Ranges = ((0x0600, 0x06FF), (0x0750, 0x077F))
|
|
27
|
+
GREEK: Ranges = ((0x0370, 0x03FF),)
|
|
28
|
+
CYRILLIC: Ranges = ((0x0400, 0x04FF),)
|
|
29
|
+
HANGUL: Ranges = ((0xAC00, 0xD7AF), (0x1100, 0x11FF))
|
|
30
|
+
KANA: Ranges = ((0x3040, 0x30FF),)
|
|
31
|
+
HAN: Ranges = ((0x4E00, 0x9FFF),)
|
|
32
|
+
|
|
33
|
+
# language code -> script. Languages sharing a script share an entry (hi/mr/ne = Devanagari).
|
|
34
|
+
SCRIPT_OF: dict[str, Ranges] = {
|
|
35
|
+
**dict.fromkeys(["hi", "mr", "ne"], DEVANAGARI),
|
|
36
|
+
"bn": BENGALI,
|
|
37
|
+
"pa": GURMUKHI,
|
|
38
|
+
"gu": GUJARATI,
|
|
39
|
+
"or": ODIA,
|
|
40
|
+
"ta": TAMIL,
|
|
41
|
+
"te": TELUGU,
|
|
42
|
+
"kn": KANNADA,
|
|
43
|
+
"ml": MALAYALAM,
|
|
44
|
+
"th": THAI,
|
|
45
|
+
"he": HEBREW,
|
|
46
|
+
**dict.fromkeys(["ar", "ur", "fa"], ARABIC),
|
|
47
|
+
"el": GREEK,
|
|
48
|
+
**dict.fromkeys(["ru", "uk", "bg"], CYRILLIC),
|
|
49
|
+
"ko": HANGUL,
|
|
50
|
+
"ja": KANA + HAN,
|
|
51
|
+
"zh": HAN,
|
|
52
|
+
}
|
|
53
|
+
SUPPORTED = sorted([*SCRIPT_OF, "en"])
|
|
54
|
+
THRESHOLD = 0.6 # share of letters that must be in the target script
|
|
55
|
+
|
|
56
|
+
_ENGLISH_WORDS = {
|
|
57
|
+
"the", "and", "is", "are", "to", "of", "in", "you", "your", "it", "for", "with", "on",
|
|
58
|
+
"will", "can", "this", "that", "we", "our", "not", "be", "have", "order", "please",
|
|
59
|
+
} # fmt: skip
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _in(ch: str, ranges: Ranges) -> bool:
|
|
63
|
+
cp = ord(ch)
|
|
64
|
+
return any(lo <= cp <= hi for lo, hi in ranges)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _share(text: str, ranges: Ranges) -> float:
|
|
68
|
+
letters = [c for c in text if c.isalpha()]
|
|
69
|
+
return sum(_in(c, ranges) for c in letters) / len(letters) if letters else 0.0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _is_english(text: str) -> tuple[bool, str]:
|
|
73
|
+
letters = [c for c in text if c.isalpha()]
|
|
74
|
+
if not letters:
|
|
75
|
+
return False, "no letters in the answer"
|
|
76
|
+
latin = sum(c.isascii() or 0x00C0 <= ord(c) <= 0x024F for c in letters) / len(letters)
|
|
77
|
+
if latin < 0.9:
|
|
78
|
+
return False, f"only {latin:.0%} of letters are Latin"
|
|
79
|
+
words = re.findall(r"[a-z']+", text.lower())
|
|
80
|
+
hits = sum(w in _ENGLISH_WORDS for w in words)
|
|
81
|
+
need = 2 if len(words) >= 6 else 1
|
|
82
|
+
if hits < need:
|
|
83
|
+
return False, "Latin script but no common English words (another language?)"
|
|
84
|
+
return True, "looks English"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def check_language(text: str, code: str) -> tuple[bool, str]:
|
|
88
|
+
"""Is ``text`` written in language ``code``? Returns (ok, short reason)."""
|
|
89
|
+
code = code.lower()
|
|
90
|
+
if code == "en":
|
|
91
|
+
return _is_english(text)
|
|
92
|
+
ranges = SCRIPT_OF[code]
|
|
93
|
+
share = _share(text, ranges)
|
|
94
|
+
if code == "ja":
|
|
95
|
+
kana = _share(text, KANA)
|
|
96
|
+
return (share >= THRESHOLD and kana >= 0.05), f"{share:.0%} Japanese script"
|
|
97
|
+
if code == "zh" and _share(text, KANA) >= 0.05:
|
|
98
|
+
return False, "contains kana (Japanese, not Chinese)"
|
|
99
|
+
return share >= THRESHOLD, f"{share:.0%} of letters in the {code} script"
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Result records for checks, judging and quality scores (saved inside results.json)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CheckResult(BaseModel):
|
|
11
|
+
"""Outcome of one check. ``passed`` is None when the judge must decide."""
|
|
12
|
+
|
|
13
|
+
type: str
|
|
14
|
+
passed: bool | None
|
|
15
|
+
detail: str = ""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class JudgeResult(BaseModel):
|
|
19
|
+
"""A judge's 0-10 score for one answer, with its reason. ``score`` None means it failed."""
|
|
20
|
+
|
|
21
|
+
score: float | None = None
|
|
22
|
+
reason: str = ""
|
|
23
|
+
error: str | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class GroundedResult(BaseModel):
|
|
27
|
+
"""Did the answer stay inside the provided documents? ``passed`` None means the judge failed."""
|
|
28
|
+
|
|
29
|
+
passed: bool | None = None
|
|
30
|
+
unsupported: str = "" # the claim the documents do not support
|
|
31
|
+
error: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AnswerScore(BaseModel):
|
|
35
|
+
"""Score of one answer. ``quality`` is 0..1, or None when it could not be scored."""
|
|
36
|
+
|
|
37
|
+
case_id: str
|
|
38
|
+
status: Literal["scored", "check_failed", "error", "unscored"]
|
|
39
|
+
quality: float | None = None
|
|
40
|
+
checks: list[CheckResult] = Field(default_factory=list)
|
|
41
|
+
judge: JudgeResult | None = None
|
|
42
|
+
reference_kind: Literal["expected", "reference_version"] | None = None
|
|
43
|
+
why: str = ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CandidateScore(BaseModel):
|
|
47
|
+
"""Quality of one version: overall, per tag, and relative to the reference version."""
|
|
48
|
+
|
|
49
|
+
label: str
|
|
50
|
+
quality: float | None = None
|
|
51
|
+
relative: float | None = None # quality / reference version's quality
|
|
52
|
+
per_tag: dict[str, float] = Field(default_factory=dict)
|
|
53
|
+
n_scored: int = 0
|
|
54
|
+
n_total: int = 0
|
|
55
|
+
answers: list[AnswerScore] = Field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ScoringResult(BaseModel):
|
|
59
|
+
"""Everything about how a run was scored, so it can be reproduced."""
|
|
60
|
+
|
|
61
|
+
judge: str
|
|
62
|
+
judge_model: str | None = None
|
|
63
|
+
rubric: str
|
|
64
|
+
reference_label: str | None = None
|
|
65
|
+
candidates: list[CandidateScore] = Field(default_factory=list)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class CandidateVerdict(BaseModel):
|
|
69
|
+
"""Is this version safe to use, compared with the reference, given the sample size?"""
|
|
70
|
+
|
|
71
|
+
label: str
|
|
72
|
+
verdict: Literal["reference", "safe", "unsafe", "uncertain"]
|
|
73
|
+
relative: float | None = None # quality / reference quality
|
|
74
|
+
ci_low: float | None = None # 95% interval on ``relative``
|
|
75
|
+
ci_high: float | None = None
|
|
76
|
+
n: int = 0 # prompts scored for both this version and the reference
|
|
77
|
+
n_worse: int = 0 # prompts where this version scored clearly lower than the reference
|
|
78
|
+
n_better: int = 0
|
|
79
|
+
size_saving: float | None = None # 0.25 = 25% smaller file than the reference
|
|
80
|
+
note: str = ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Recommendation(BaseModel):
|
|
84
|
+
"""The plain answer: which version to use, and how sure we are."""
|
|
85
|
+
|
|
86
|
+
status: Literal["recommended", "keep_reference", "inconclusive", "no_data"]
|
|
87
|
+
limit: float
|
|
88
|
+
reference_label: str | None = None
|
|
89
|
+
recommended: str | None = None
|
|
90
|
+
message: str = ""
|
|
91
|
+
needed_prompts: int | None = None # rough number of prompts needed to settle "uncertain"
|
|
92
|
+
verdicts: list[CandidateVerdict] = Field(default_factory=list)
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Quality scoring (F4, F6): reference choice, checks + judge per answer, aggregation.
|
|
2
|
+
|
|
3
|
+
Quality of an answer = 0 if any check fails, else judge score / 10. A version's quality is
|
|
4
|
+
the mean over its scored answers, also per tag, and relative to the reference version.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from statistics import mean
|
|
11
|
+
|
|
12
|
+
from quantcheck.prompt import build_prompt
|
|
13
|
+
from quantcheck.scoring.checks import run_checks
|
|
14
|
+
from quantcheck.scoring.judge import Judge
|
|
15
|
+
from quantcheck.scoring.models import (
|
|
16
|
+
AnswerScore,
|
|
17
|
+
CandidateScore,
|
|
18
|
+
CheckResult,
|
|
19
|
+
JudgeResult,
|
|
20
|
+
ScoringResult,
|
|
21
|
+
)
|
|
22
|
+
from quantcheck.store import AnswerRecord, CandidateRun, RunResult
|
|
23
|
+
from quantcheck.tests_io import SetHeader, TestCase
|
|
24
|
+
|
|
25
|
+
Progress = Callable[[str, int, int], None] # (version label, answers scored, total)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def pick_reference(result: RunResult) -> CandidateRun | None:
|
|
29
|
+
"""F4: the largest version (most bits) that ran. Ties go to the first listed."""
|
|
30
|
+
ok = [c for c in result.candidates if c.status == "ok" and c.candidate and c.candidate.bits]
|
|
31
|
+
return max(ok, key=lambda c: c.candidate.bits, default=None) # type: ignore[union-attr]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _gen_error(record: AnswerRecord) -> str | None:
|
|
35
|
+
for gen in (record.generation, record.followup):
|
|
36
|
+
if gen and gen.error:
|
|
37
|
+
return gen.error
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _resolve_grounded(
|
|
42
|
+
checks: list[CheckResult], case: TestCase, text: str, judge: Judge, question: str
|
|
43
|
+
) -> list[CheckResult]:
|
|
44
|
+
out: list[CheckResult] = []
|
|
45
|
+
for chk in checks:
|
|
46
|
+
if chk.passed is None and chk.type == "grounded":
|
|
47
|
+
g = judge.grounded(case.context, text, question)
|
|
48
|
+
if g.error:
|
|
49
|
+
chk = CheckResult(type="grounded", passed=None, detail=g.error)
|
|
50
|
+
else:
|
|
51
|
+
detail = (
|
|
52
|
+
"stays inside the documents" if g.passed else f"unsupported: {g.unsupported}"
|
|
53
|
+
)
|
|
54
|
+
chk = CheckResult(type="grounded", passed=g.passed, detail=detail)
|
|
55
|
+
out.append(chk)
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def score_answer(
|
|
60
|
+
case: TestCase,
|
|
61
|
+
header: SetHeader,
|
|
62
|
+
record: AnswerRecord,
|
|
63
|
+
ref_text: str | None,
|
|
64
|
+
is_reference: bool,
|
|
65
|
+
judge: Judge,
|
|
66
|
+
rubric: str,
|
|
67
|
+
cache: dict[tuple[str, str, str], JudgeResult],
|
|
68
|
+
) -> AnswerScore:
|
|
69
|
+
"""Score one answer. Failed checks score 0 without calling the judge."""
|
|
70
|
+
if err := _gen_error(record):
|
|
71
|
+
return AnswerScore(case_id=case.id, status="error", quality=0.0, why=f"generation: {err}")
|
|
72
|
+
text = record.final_text
|
|
73
|
+
question = build_prompt(header, case).user_text
|
|
74
|
+
checks = _resolve_grounded(run_checks(case, header, record), case, text, judge, question)
|
|
75
|
+
failed = [c for c in checks if c.passed is False]
|
|
76
|
+
if failed:
|
|
77
|
+
return AnswerScore(
|
|
78
|
+
case_id=case.id, status="check_failed", quality=0.0, checks=checks, why=failed[0].detail
|
|
79
|
+
)
|
|
80
|
+
if any(c.passed is None for c in checks):
|
|
81
|
+
return AnswerScore(case_id=case.id, status="unscored", checks=checks, why="judge failed")
|
|
82
|
+
|
|
83
|
+
kind = "expected" if case.expected is not None else "reference_version"
|
|
84
|
+
reference = case.expected if case.expected is not None else ref_text
|
|
85
|
+
if reference is None:
|
|
86
|
+
return AnswerScore(
|
|
87
|
+
case_id=case.id, status="unscored", checks=checks, why="no expected answer or reference"
|
|
88
|
+
)
|
|
89
|
+
if text.strip() == reference.strip() or (kind == "reference_version" and is_reference):
|
|
90
|
+
judged = JudgeResult(score=10.0, reason="identical to the reference")
|
|
91
|
+
else:
|
|
92
|
+
key = (question, text, reference)
|
|
93
|
+
if key not in cache:
|
|
94
|
+
cache[key] = judge.score(question, text, reference, rubric)
|
|
95
|
+
judged = cache[key]
|
|
96
|
+
if judged.score is None:
|
|
97
|
+
return AnswerScore(
|
|
98
|
+
case_id=case.id, status="unscored", checks=checks, judge=judged, reference_kind=kind,
|
|
99
|
+
why=judged.error or "judge failed",
|
|
100
|
+
) # fmt: skip
|
|
101
|
+
return AnswerScore(
|
|
102
|
+
case_id=case.id, status="scored", quality=judged.score / 10, checks=checks,
|
|
103
|
+
judge=judged, reference_kind=kind,
|
|
104
|
+
) # fmt: skip
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _aggregate(label: str, answers: list[AnswerScore], cases: list[TestCase]) -> CandidateScore:
|
|
108
|
+
tags = {c.id: c.tags for c in cases}
|
|
109
|
+
scored = [a for a in answers if a.quality is not None]
|
|
110
|
+
per_tag: dict[str, list[float]] = {}
|
|
111
|
+
for a in scored:
|
|
112
|
+
for tag in tags.get(a.case_id, []):
|
|
113
|
+
per_tag.setdefault(tag, []).append(a.quality)
|
|
114
|
+
return CandidateScore(
|
|
115
|
+
label=label,
|
|
116
|
+
quality=round(mean(a.quality for a in scored), 4) if scored else None,
|
|
117
|
+
per_tag={t: round(mean(v), 4) for t, v in per_tag.items()},
|
|
118
|
+
n_scored=len(scored),
|
|
119
|
+
n_total=len(answers),
|
|
120
|
+
answers=answers,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def score_run(
|
|
125
|
+
result: RunResult,
|
|
126
|
+
judge: Judge,
|
|
127
|
+
rubric: str,
|
|
128
|
+
on_progress: Progress | None = None,
|
|
129
|
+
judge_name: str | None = None,
|
|
130
|
+
) -> ScoringResult:
|
|
131
|
+
"""Score every version of a finished run. Loads the judge once and always unloads it."""
|
|
132
|
+
ref_run = pick_reference(result)
|
|
133
|
+
cases = {c.id: c for c in result.testset.cases}
|
|
134
|
+
ref_answers = {a.case_id: a.final_text for a in ref_run.answers} if ref_run else {}
|
|
135
|
+
cache: dict[tuple[str, str, str], JudgeResult] = {}
|
|
136
|
+
scores: list[CandidateScore] = []
|
|
137
|
+
judge.load()
|
|
138
|
+
try:
|
|
139
|
+
for cr in result.candidates:
|
|
140
|
+
if cr.status != "ok":
|
|
141
|
+
continue
|
|
142
|
+
answers: list[AnswerScore] = []
|
|
143
|
+
for i, rec in enumerate(cr.answers, start=1):
|
|
144
|
+
answers.append(
|
|
145
|
+
score_answer(
|
|
146
|
+
cases[rec.case_id], result.testset.header, rec,
|
|
147
|
+
ref_answers.get(rec.case_id), ref_run is not None and cr is ref_run,
|
|
148
|
+
judge, rubric, cache,
|
|
149
|
+
)
|
|
150
|
+
) # fmt: skip
|
|
151
|
+
if on_progress:
|
|
152
|
+
on_progress(cr.label, i, len(cr.answers))
|
|
153
|
+
scores.append(_aggregate(cr.label, answers, result.testset.cases))
|
|
154
|
+
finally:
|
|
155
|
+
judge.unload()
|
|
156
|
+
|
|
157
|
+
ref_quality = next((s.quality for s in scores if ref_run and s.label == ref_run.label), None)
|
|
158
|
+
for s in scores:
|
|
159
|
+
if ref_quality and s.quality is not None:
|
|
160
|
+
s.relative = round(s.quality / ref_quality, 4)
|
|
161
|
+
return ScoringResult(
|
|
162
|
+
judge=judge_name or judge.name,
|
|
163
|
+
judge_model=judge.model,
|
|
164
|
+
rubric=rubric,
|
|
165
|
+
reference_label=ref_run.label if ref_run else None,
|
|
166
|
+
candidates=scores,
|
|
167
|
+
)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Honest statistics (simple, Phase 1): a paired bootstrap on per-prompt quality.
|
|
2
|
+
|
|
3
|
+
Every prompt is scored for the reference and for the version under test, so we compare them
|
|
4
|
+
prompt by prompt (paired) and ask how much the ratio of their mean quality could move if we
|
|
5
|
+
had drawn different prompts. The random seed is fixed, so a run gives the same answer twice.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import random
|
|
12
|
+
from statistics import mean, stdev
|
|
13
|
+
|
|
14
|
+
from quantcheck import limits
|
|
15
|
+
|
|
16
|
+
Z95 = 1.96
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def paired_ratio_ci(
|
|
20
|
+
cand: list[float],
|
|
21
|
+
ref: list[float],
|
|
22
|
+
confidence: float = limits.CONFIDENCE,
|
|
23
|
+
resamples: int = limits.BOOTSTRAP_RESAMPLES,
|
|
24
|
+
seed: int = 0,
|
|
25
|
+
) -> tuple[float, float, float] | None:
|
|
26
|
+
"""(ratio, low, high) of mean(cand)/mean(ref), or None if the reference mean is 0."""
|
|
27
|
+
if len(cand) != len(ref) or not cand or sum(ref) == 0:
|
|
28
|
+
return None
|
|
29
|
+
ratio = sum(cand) / sum(ref)
|
|
30
|
+
rng = random.Random(seed)
|
|
31
|
+
n = len(cand)
|
|
32
|
+
ratios: list[float] = []
|
|
33
|
+
for _ in range(resamples):
|
|
34
|
+
idx = [rng.randrange(n) for _ in range(n)]
|
|
35
|
+
denom = sum(ref[i] for i in idx)
|
|
36
|
+
if denom > 0:
|
|
37
|
+
ratios.append(sum(cand[i] for i in idx) / denom)
|
|
38
|
+
if not ratios:
|
|
39
|
+
return None
|
|
40
|
+
ratios.sort()
|
|
41
|
+
tail = (1 - confidence) / 2
|
|
42
|
+
lo = ratios[int(tail * len(ratios))]
|
|
43
|
+
hi = ratios[min(len(ratios) - 1, int((1 - tail) * len(ratios)))]
|
|
44
|
+
return ratio, lo, hi
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def needed_prompts(cand: list[float], ref: list[float], limit: float) -> int | None:
|
|
48
|
+
"""Rough prompts needed to separate this version from the limit (None: cannot tell).
|
|
49
|
+
|
|
50
|
+
Uses the spread of per-prompt differences and how far the observed ratio sits from the
|
|
51
|
+
limit. Capped at the per-set maximum, so a very close call answers "the maximum".
|
|
52
|
+
"""
|
|
53
|
+
if len(cand) < 2 or sum(ref) == 0:
|
|
54
|
+
return None
|
|
55
|
+
ref_mean = mean(ref)
|
|
56
|
+
diffs = [c - r for c, r in zip(cand, ref, strict=True)]
|
|
57
|
+
sd = stdev(diffs)
|
|
58
|
+
gap = abs(mean(cand) / ref_mean - limit) * ref_mean
|
|
59
|
+
gap = max(gap, 0.005) # a dead heat would otherwise ask for infinite prompts
|
|
60
|
+
return min(limits.MAX_PROMPTS, max(len(cand), math.ceil((Z95 * sd / gap) ** 2)))
|
quantcheck/settings.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""App-wide settings in one place (host, port, data folder)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
9
|
+
DEFAULT_PORT = 8765
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def data_dir() -> Path:
|
|
13
|
+
"""Where the lab keeps runs, test sets and cache: ``~/quantcheck`` (QUANTCHECK_HOME)."""
|
|
14
|
+
return Path(os.environ.get("QUANTCHECK_HOME", Path.home() / "quantcheck")).expanduser()
|
quantcheck/store.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Results: the run record and where it is saved (JSON files now, a database later)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
from quantcheck.candidates import Candidate
|
|
11
|
+
from quantcheck.runners.base import Generation
|
|
12
|
+
from quantcheck.scoring.models import Recommendation, ScoringResult
|
|
13
|
+
from quantcheck.tests_io import TestSet
|
|
14
|
+
|
|
15
|
+
SCHEMA_VERSION = 1 # bump when the results.json shape changes; add a migration
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AnswerRecord(BaseModel):
|
|
19
|
+
"""One prompt answered by one candidate; ``followup`` follows a recorded tool result."""
|
|
20
|
+
|
|
21
|
+
case_id: str
|
|
22
|
+
generation: Generation
|
|
23
|
+
followup: Generation | None = None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def final_text(self) -> str:
|
|
27
|
+
"""The answer a customer would read."""
|
|
28
|
+
return (self.followup or self.generation).text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CandidateRun(BaseModel):
|
|
32
|
+
"""All answers from one version, or why it was skipped."""
|
|
33
|
+
|
|
34
|
+
label: str
|
|
35
|
+
candidate: Candidate | None = None
|
|
36
|
+
status: str = "ok" # ok | skipped
|
|
37
|
+
reason: str | None = None
|
|
38
|
+
file_size_mb: float | None = None
|
|
39
|
+
answers: list[AnswerRecord] = Field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class RunResult(BaseModel):
|
|
43
|
+
"""Everything about one run: config, machine, tests, answers."""
|
|
44
|
+
|
|
45
|
+
schema_version: int = SCHEMA_VERSION
|
|
46
|
+
run_id: str
|
|
47
|
+
created_at: str
|
|
48
|
+
config: dict
|
|
49
|
+
environment: dict
|
|
50
|
+
testset: TestSet
|
|
51
|
+
candidates: list[CandidateRun]
|
|
52
|
+
scoring: ScoringResult | None = None # filled by the scoring pass
|
|
53
|
+
recommendation: Recommendation | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ResultsStore(ABC):
|
|
57
|
+
"""Where runs are saved."""
|
|
58
|
+
|
|
59
|
+
@abstractmethod
|
|
60
|
+
def save(self, result: RunResult) -> Path: ...
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def load(self, ref: str | Path) -> RunResult: ...
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class JsonResultsStore(ResultsStore):
|
|
67
|
+
"""``<output_dir>/<run_id>/results.json``."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, output_dir: str | Path) -> None:
|
|
70
|
+
self.output_dir = Path(output_dir)
|
|
71
|
+
|
|
72
|
+
def save(self, result: RunResult) -> Path:
|
|
73
|
+
run_dir = self.output_dir / result.run_id
|
|
74
|
+
run_dir.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
path = run_dir / "results.json"
|
|
76
|
+
path.write_text(result.model_dump_json(indent=2), encoding="utf-8")
|
|
77
|
+
return path
|
|
78
|
+
|
|
79
|
+
def load(self, ref: str | Path) -> RunResult:
|
|
80
|
+
"""``ref`` is a run id, a run folder, or a results.json path."""
|
|
81
|
+
p = Path(ref)
|
|
82
|
+
if not p.exists():
|
|
83
|
+
p = self.output_dir / str(ref)
|
|
84
|
+
if p.is_dir():
|
|
85
|
+
p = p / "results.json"
|
|
86
|
+
if not p.is_file():
|
|
87
|
+
raise FileNotFoundError(f"no results found for '{ref}'")
|
|
88
|
+
return RunResult.model_validate_json(p.read_text(encoding="utf-8"))
|
quantcheck/tests_io.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Load and validate a tests.jsonl file.
|
|
2
|
+
|
|
3
|
+
A file has at most one ``{"type": "set", ...}`` header line (shared system
|
|
4
|
+
instructions and tools) and any number of test-case lines. Errors name the
|
|
5
|
+
line number so a user can fix their file quickly.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
14
|
+
|
|
15
|
+
from quantcheck import limits
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TestFileError(ValueError):
|
|
19
|
+
"""The tests file is invalid. The message says which line and why."""
|
|
20
|
+
|
|
21
|
+
__test__ = False # not a pytest class
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Strict(BaseModel):
|
|
25
|
+
model_config = ConfigDict(extra="forbid")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ToolSpec(_Strict):
|
|
29
|
+
"""A tool the app offers the model. Never executed, only described."""
|
|
30
|
+
|
|
31
|
+
name: str
|
|
32
|
+
description: str = ""
|
|
33
|
+
parameters: dict = Field(default_factory=lambda: {"type": "object", "properties": {}})
|
|
34
|
+
changes_data: bool = False # cancel / refund / delete: flagged in the UI
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SetHeader(_Strict):
|
|
38
|
+
"""Set-level context sent with every prompt."""
|
|
39
|
+
|
|
40
|
+
type: str = "set"
|
|
41
|
+
system: str = ""
|
|
42
|
+
tools: list[ToolSpec] = Field(default_factory=list)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CheckSpec(_Strict):
|
|
46
|
+
"""One hard yes/no rule, e.g. ``{"type": "language", "value": "hi"}``."""
|
|
47
|
+
|
|
48
|
+
type: str
|
|
49
|
+
value: object = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ToolCall(_Strict):
|
|
53
|
+
"""A tool call: name plus arguments."""
|
|
54
|
+
|
|
55
|
+
name: str
|
|
56
|
+
arguments: dict = Field(default_factory=dict)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class TestCase(_Strict):
|
|
60
|
+
"""One prompt plus everything the app sends with it."""
|
|
61
|
+
|
|
62
|
+
__test__ = False
|
|
63
|
+
|
|
64
|
+
id: str = Field(min_length=1)
|
|
65
|
+
prompt: str = Field(min_length=1)
|
|
66
|
+
context: list[str] = Field(default_factory=list) # retrieved documents (RAG)
|
|
67
|
+
expected: str | None = None
|
|
68
|
+
expected_tool_call: ToolCall | None = None
|
|
69
|
+
tool_results: dict[str, object] = Field(default_factory=dict) # recorded, played back
|
|
70
|
+
checks: list[CheckSpec] = Field(default_factory=list)
|
|
71
|
+
tags: list[str] = Field(default_factory=list)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class TestSet(BaseModel):
|
|
75
|
+
"""A validated test file."""
|
|
76
|
+
|
|
77
|
+
__test__ = False
|
|
78
|
+
|
|
79
|
+
header: SetHeader = Field(default_factory=SetHeader)
|
|
80
|
+
cases: list[TestCase]
|
|
81
|
+
warnings: list[str] = Field(default_factory=list)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _fail(line_no: int, msg: str) -> TestFileError:
|
|
85
|
+
return TestFileError(f"line {line_no}: {msg}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _short(err: ValidationError) -> str:
|
|
89
|
+
first = err.errors()[0]
|
|
90
|
+
loc = ".".join(str(p) for p in first["loc"])
|
|
91
|
+
return f"{loc}: {first['msg']}" if loc else first["msg"]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _validate_case(case: TestCase, tools: dict[str, ToolSpec], line_no: int) -> None:
|
|
95
|
+
for chk in case.checks:
|
|
96
|
+
if chk.type == "tool_call" and case.expected_tool_call is None:
|
|
97
|
+
raise _fail(line_no, f"{case.id}: check 'tool_call' needs expected_tool_call")
|
|
98
|
+
call = case.expected_tool_call
|
|
99
|
+
if call is not None and call.name not in tools:
|
|
100
|
+
raise _fail(line_no, f"{case.id}: expected_tool_call '{call.name}' is not in the set tools")
|
|
101
|
+
for name in case.tool_results:
|
|
102
|
+
if name not in tools:
|
|
103
|
+
raise _fail(line_no, f"{case.id}: tool_results has unknown tool '{name}'")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def loads_tests(text: str) -> TestSet:
|
|
107
|
+
"""Parse tests.jsonl text. Blank lines and ``#`` comment lines are skipped."""
|
|
108
|
+
header: SetHeader | None = None
|
|
109
|
+
cases: list[TestCase] = []
|
|
110
|
+
case_lines: list[int] = []
|
|
111
|
+
seen: set[str] = set()
|
|
112
|
+
|
|
113
|
+
for line_no, raw in enumerate(text.splitlines(), start=1):
|
|
114
|
+
line = raw.strip()
|
|
115
|
+
if not line or line.startswith("#"):
|
|
116
|
+
continue
|
|
117
|
+
try:
|
|
118
|
+
obj = json.loads(line)
|
|
119
|
+
except json.JSONDecodeError as e:
|
|
120
|
+
raise _fail(line_no, f"not valid JSON ({e.msg})") from e
|
|
121
|
+
if not isinstance(obj, dict):
|
|
122
|
+
raise _fail(line_no, "each line must be a JSON object")
|
|
123
|
+
try:
|
|
124
|
+
if obj.get("type") == "set":
|
|
125
|
+
if header is not None:
|
|
126
|
+
raise _fail(line_no, "more than one 'set' header line")
|
|
127
|
+
header = SetHeader.model_validate(obj)
|
|
128
|
+
else:
|
|
129
|
+
case = TestCase.model_validate(obj)
|
|
130
|
+
if case.id in seen:
|
|
131
|
+
raise _fail(line_no, f"duplicate id '{case.id}'")
|
|
132
|
+
seen.add(case.id)
|
|
133
|
+
cases.append(case)
|
|
134
|
+
case_lines.append(line_no)
|
|
135
|
+
except ValidationError as e:
|
|
136
|
+
raise _fail(line_no, _short(e)) from e
|
|
137
|
+
|
|
138
|
+
header = header or SetHeader()
|
|
139
|
+
tools = {t.name: t for t in header.tools}
|
|
140
|
+
if len(tools) != len(header.tools):
|
|
141
|
+
raise TestFileError("set header: duplicate tool names")
|
|
142
|
+
for case, line_no in zip(cases, case_lines, strict=True):
|
|
143
|
+
_validate_case(case, tools, line_no)
|
|
144
|
+
|
|
145
|
+
warnings = _limit_warnings(header, cases)
|
|
146
|
+
return TestSet(header=header, cases=cases, warnings=warnings)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _limit_warnings(header: SetHeader, cases: list[TestCase]) -> list[str]:
|
|
150
|
+
if not cases:
|
|
151
|
+
raise TestFileError("no test prompts found")
|
|
152
|
+
if len(cases) > limits.MAX_PROMPTS:
|
|
153
|
+
raise TestFileError(f"{len(cases)} prompts; the limit is {limits.MAX_PROMPTS} per set")
|
|
154
|
+
if len(header.tools) > limits.MAX_TOOLS:
|
|
155
|
+
raise TestFileError(f"{len(header.tools)} tools; the limit is {limits.MAX_TOOLS} per set")
|
|
156
|
+
warnings: list[str] = []
|
|
157
|
+
if len(cases) > limits.WARN_PROMPTS:
|
|
158
|
+
warnings.append(f"{len(cases)} prompts is a long run; expect a long wait per version.")
|
|
159
|
+
if len(header.tools) > limits.WARN_TOOLS:
|
|
160
|
+
warnings.append(f"{len(header.tools)} tools: small models often pick the wrong one.")
|
|
161
|
+
return warnings
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def load_tests(path: str | Path) -> TestSet:
|
|
165
|
+
"""Read and validate a tests.jsonl file."""
|
|
166
|
+
p = Path(path)
|
|
167
|
+
if not p.is_file():
|
|
168
|
+
raise TestFileError(f"tests file not found: {p}")
|
|
169
|
+
return loads_tests(p.read_text(encoding="utf-8"))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The local lab (F9b): a web app on localhost that drives the same pipeline as the CLI."""
|