Compare commits

...
1 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5 Release 0.14.0: quality eval
Release / release (push) Successful in 3m17s
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00
33 changed files with 3822 additions and 79 deletions

No files matched your search

+26
View File
@@ -4,6 +4,32 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [0.14.0] - 2026-10-21
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
long-context retrieval, so a launch option that makes a model faster but worse shows up.
No changes to `compose.yaml` or `.env`. The new column is added on start.
### Added
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
with greedy decoding, a fixed seed and thinking turned off:
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
context, sized with the server's own tokenizer.
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
result records its version (`kaname-eval-1`).
- The run page shows the score, each section and every item with the reason it failed. Compare views
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
("Also run the quality eval") and show it as a column.
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
- The tuning skill checks quality after speed and reports both.
## [0.13.0] - 2026-10-21
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
+22 -9
View File
@@ -1,6 +1,6 @@
---
name: kaname-tuning
description: Deploy local LLMs on the user's Kaname server and benchmark them to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
description: Deploy local LLMs on the user's Kaname server, benchmark their speed and check their answer quality to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
required_environment_variables:
- name: KANAME_URL
prompt: Kaname base URL (no trailing slash)
@@ -109,6 +109,17 @@ kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
temperature. `?full=1` only when you need the per-category details.
- If the wait times out, the run is still going: one more call with `?wait=900`, then report.
Then check that the answers are still right (speed alone can hide a broken setup):
```bash
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{"kind": "eval", "deploymentId": "<id>", "label": "Q4_K_M ctx16k q8_0 KV"}'
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
```
`quality.score` (0–100) and per section (`tools`, `coding`, `retrieval`). Add `?full=1` to see which
items failed. A drop of more than a few points against the baseline means the change hurt quality,
however fast it is.
## 5. Change one variable and compare
Stop, change one option, start, wait, benchmark again:
@@ -120,12 +131,13 @@ kaname -X PATCH "$KANAME_URL/api/v1/deployments/<id>" -d '{"options": {"cacheTyp
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/start"
```
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it and
removes it again (stop your own deployment first; it counts as one run):
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it (with
`"quality": true` also runs the quality eval) and removes it again (stop your own deployment first;
it counts as one run):
```bash
kaname -X POST "$KANAME_URL/api/v1/sweeps" -d '{
"baseDeploymentId": "<id>", "quick": true,
"baseDeploymentId": "<id>", "quick": true, "quality": true,
"params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }]
}'
kaname -m 960 "$KANAME_URL/api/v1/sweeps/<sweepId>?wait=900"
@@ -150,12 +162,13 @@ an A/B (two deployments of the same model at once, if the user allows 2 agent de
Report a compact table, one row per setup, the varied option first:
| KV cache | Decode t/s | Prefill t/s | TTFT ms | VRAM peak | Notes |
| --- | --- | --- | --- | --- | --- |
| f16 | 58.1 | 1910 | 88 | 11.2 GB | baseline |
| q8_0 | 57.6 | 1880 | 90 | 9.4 GB | −1 %, 1.8 GB less VRAM |
| KV cache | Decode t/s | Prefill t/s | TTFT ms | Quality | VRAM peak | Notes |
| --- | --- | --- | --- | --- | --- | --- |
| f16 | 58.1 | 1910 | 88 | 86.1 | 11.2 GB | baseline |
| q8_0 | 57.6 | 1880 | 90 | 86.1 | 9.4 GB | −1 % speed, same quality, 1.8 GB less VRAM |
Name the winner and why (and what stayed the same: GPU, engine version, quant, context). Then stop
Name the winner and why: speed and quality together (and what stayed the same: GPU, engine version,
quant, context). Then stop
your deployment (or delete it if the user doesn't need it):
```bash
+24 -3
View File
@@ -247,11 +247,12 @@ command and estimates. `start` goes through the same guardrails as creating one
| Field | |
| --- | --- |
| `kind` | `run` (default) or `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) |
| `kind` | `run` (default, BetterBench speed), `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) or `eval` (the [quality eval](#quality-eval)) |
| `deploymentId`, `deploymentBId` | Own, running deployments |
| `quick` | `true`: 5 passes, a smoke check; default `false`: 20 passes, comparable |
| `passes`, `phases` | Optional: passes per category; phases `decode`, `prefill`, `concurrency` (default all) |
| `label`, `description` | Optional; the description goes into the report and the launch80 preview |
| `sections` | `eval` only: `tools`, `coding`, `retrieval` (default all) |
Answers `201` with `state` `pending_approval` (default) or `queued`, and the run's time limit.
@@ -271,7 +272,10 @@ Answers `201` with `state` `pending_approval` (default) or `queued`, and the run
```
`?full=1` adds BetterBench's complete summary (per category, per prompt depth, per concurrency
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval).
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval). Eval runs
have `quality` instead of `headline`:
`{"evalSet": "kaname-eval-1", "score": 83.3, "sections": {"tools": "11/12", "coding": "6/8", "retrieval": "8/9"}}`,
and with `?full=1` the `failed` items with the reason.
`POST /api/v1/benchmarks/{id}/cancel` cancels an own run.
#### `GET /api/v1/benchmarks/compare?ids=a,b,…`
@@ -282,12 +286,29 @@ level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence
#### `POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}[?wait=S]`, `POST /api/v1/sweeps/{id}/cancel`
`benchmarks:run` / `benchmarks:read`. One or two settings varied from an own base deployment, e.g.
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`.
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`;
`"quality": true` also runs the quality eval on each variant.
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
`flashAttn`, `cacheRamMb`, `gpuLayers`, `dtype`, `maxNumSeqs`, `kvCacheGb`, `gpuMemoryUtilization`,
`cpus` (per engine, as in the UI). Each variant is deployed, benchmarked and removed again. The
answer lists every variant with its headline numbers and setup.
#### Quality eval
BetterBench measures speed only. `kind: "eval"` checks what a deployment answers, deterministically
(greedy decoding, temperature 0, fixed seed, thinking turned off where the chat template supports
it), so a quant, KV cache type or build that changes quality shows up next to the speed numbers:
| Section | Items | Passes when |
| --- | --- | --- |
| `tools` | 12 requests with 3 tools each | exactly one tool call, valid JSON arguments, the right function and the expected arguments |
| `coding` | 8 short Python functions | the answer's code passes its unit tests, run in a throwaway container (no network, read-only, unprivileged) |
| `retrieval` | a six-digit code hidden at 10 %, 50 % and 90 % depth in texts of 25 %, 50 % and 100 % of the context | the answer contains the code |
The score is the mean pass rate of the sections that could run (a server that refuses tool calls,
e.g. vLLM without a tool-call parser, doesn't count as 0). The eval set is versioned (`evalSet`);
only results of the same version compare.
## Waiting instead of polling
Every status call costs an agent a round of its context. The status endpoints (`/jobs/{id}`,
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `benchmark_runs` ADD `quality` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -141,6 +141,13 @@
"when": 1792587768766,
"tag": "0019_agent_tuning",
"breakpoints": true
},
{
"idx": 20,
"version": "6",
"when": 1792588720328,
"tag": "0020_quality_eval",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.13.0",
"version": "0.14.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.13.0",
"version": "0.14.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.13.0",
"version": "0.14.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -38,6 +38,7 @@ import { RequestedByBadge } from "@/components/requested-by-badge";
import { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
import { QualityReport } from "./quality-report";
import { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
@@ -84,6 +85,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
body: JSON.stringify({
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
kind: r.kind,
label: r.label,
description: r.description,
...r.settings,
@@ -174,7 +176,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
)}
</p>
<p className="text-xs text-muted-foreground">
BetterBench ·{" "}
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
{r.kind === "ab"
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
: describeSettings(r.settings)}{" "}
@@ -271,7 +273,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
{r.state === "pending_approval" && (
<AgentApprovalBar
requestedBy={r.requestedBy}
what={`run ${r.kind === "ab" ? "an A/B" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
what={`run ${r.kind === "ab" ? "an A/B" : r.kind === "eval" ? "the quality eval" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
base={`/api/benchmarks/${r.id}`}
/>
)}
@@ -294,7 +296,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
<div className="flex min-w-0 flex-col gap-4">
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
{r.kind === "ab" ? <AbReport run={r} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
<LiveLog
url={`/api/benchmarks/${r.id}/logs`}
title="BetterBench output"
@@ -355,7 +357,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
</CardContent>
</Card>
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
{r.kind === "run" && (
{r.kind !== "ab" && (
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
@@ -0,0 +1,68 @@
import { CheckIcon, XIcon } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { QualityResult } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
/** A quality eval's result: the score, each section's pass rate and every item. */
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
if (!quality) {
return (
<Card>
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Quality</CardTitle>
<CardDescription>
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
{quality.config.thinking ? "on" : "off"}
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
only results of the same eval set compare.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-baseline gap-2">
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Section</TableHead>
<TableHead className="text-right">Passed</TableHead>
<TableHead className="text-right">Score</TableHead>
<TableHead className="text-right">Time</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{quality.sections.map((s) => (
<TableRow key={s.section}>
<TableCell className="whitespace-normal">
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
</TableCell>
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<ul className="flex flex-col gap-1 text-xs">
{quality.items.map((i) => (
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
<span className="font-mono">{i.id}</span>
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
</li>
))}
</ul>
</CardContent>
</Card>
);
}
+5 -1
View File
@@ -220,7 +220,11 @@ export function BenchmarkList({
</div>
</TableCell>
<TableCell className="text-right font-medium tabular-nums">
{fmt(h.decode)}
{r.kind === "eval" ? (
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
) : (
fmt(h.decode)
)}
</TableCell>
<TableCell className="text-right tabular-nums">
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
+21 -2
View File
@@ -5,6 +5,7 @@ import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { getBenchmarks } from "@/lib/benchmarks";
import { metaRows } from "@/lib/benchmark-meta";
import { SECTION_LABEL } from "@/lib/quality-view";
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
@@ -12,7 +13,7 @@ import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Compare benchmarks" };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null) => number | null };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
/** Differences smaller than this are shown without color: below what a single run can resolve. */
const NOISE_PCT = 2;
@@ -87,6 +88,24 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
},
];
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
const quality = runs.map((r) => r.quality);
if (quality.some(Boolean)) {
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
groups.push({
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
rows: [
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
...sections.map((sec) => ({
label: SECTION_LABEL[sec],
unit: "%",
higherIsBetter: true,
digits: 1,
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
})),
],
});
}
const metrics = groups.filter((g) => g.rows.length > 0);
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
@@ -187,7 +206,7 @@ function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[
</TableCell>
</TableRow>
{rows.map((m) => {
const vals = sums.map((s) => m.get(s));
const vals = sums.map((s, i) => m.get(s, i));
const present = vals.filter((v): v is number => v != null);
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
return (
@@ -13,18 +13,28 @@ import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { metaRows } from "@/lib/benchmark-meta";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
type Sweep = typeof benchmarkSweeps.$inferSelect;
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null; meta: RunMeta | null };
type Run = {
id: string;
state: string;
summary: BenchmarkSummary | null;
resources: ResourceStats | null;
phase: string | null;
error: string | null;
meta: RunMeta | null;
quality: QualityResult | null;
};
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
pending: "Waiting",
deploying: "Deploying",
benchmarking: "Benchmarking",
evaluating: "Quality eval",
done: "Done",
failed: "Failed",
skipped: "Skipped",
@@ -42,11 +52,13 @@ type Row = {
vram: number | null;
power: number | null;
temp: number | null;
quality: number | null;
};
function rowsOf(data: SweepData): Row[] {
return data.sweep.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId) ?? null;
const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null;
const h = headline(run?.summary ?? null);
const c = run?.resources?.containers.find((x) => x.side === "a");
const g = run?.resources?.gpus ?? [];
@@ -62,6 +74,7 @@ function rowsOf(data: SweepData): Row[] {
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
quality: ev?.quality?.score ?? null,
};
});
}
@@ -129,7 +142,9 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
vram: best(rows, "vram", false),
power: best(rows, "power", false),
temp: best(rows, "temp", false),
quality: best(rows, "quality", true),
};
const hasQuality = !!sweep.settings.quality;
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
);
@@ -236,6 +251,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
</th>
))}
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
{hasQuality && <th className="px-3 py-2 text-right font-medium">Quality</th>}
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
@@ -269,6 +285,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
</td>
))}
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
{hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
@@ -64,6 +64,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
const [label, setLabel] = useState("");
const [quality, setQuality] = useState(false);
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
@@ -95,6 +96,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
quick: mode === "quick",
passes: mode === "custom" ? Number(passes) || 10 : null,
phases: phases.length === PHASES.length ? [] : phases,
quality,
}),
});
const json = await res.json().catch(() => ({}));
@@ -205,6 +207,13 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
</label>
))}
</div>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<Checkbox checked={quality} onCheckedChange={(v) => setQuality(v === true)} className="mt-0.5" />
<span className="flex flex-col">
<span>Also run the quality eval on each variant</span>
<span className="text-xs text-muted-foreground">Tool calling, coding and long-context retrieval, after the speed run (adds a few minutes per variant).</span>
</span>
</label>
<div className="flex flex-col gap-1.5">
<Label htmlFor="sw-label">Label</Label>
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
@@ -1,6 +1,6 @@
"use client";
import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
@@ -14,6 +14,8 @@ import { NativeSelect } from "@/components/ui/native-select";
import { abHeadline } from "@/lib/ab-report";
import { headline } from "@/lib/benchmark-view";
import type { BenchmarkPhase } from "@/lib/db/schema";
import { QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
import type { ListRow } from "../../benchmarks/benchmark-list";
@@ -23,7 +25,7 @@ const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
];
type Mode = "run" | "ab" | "sweep";
type Mode = "run" | "ab" | "quality" | "sweep";
type Peer = { id: string; name: string; state: string; modelId: string };
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
@@ -41,6 +43,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
const [peerId, setPeerId] = useState("");
const [mde, setMde] = useState("1");
const [maxPairs, setMaxPairs] = useState("200");
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
const active = runs.some((r) => r.state === "queued" || r.state === "running");
useEffect(() => {
@@ -87,6 +90,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
{ id: "run", label: "Run", icon: GaugeIcon },
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
];
@@ -211,6 +215,32 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
</>
)}
{tab === "quality" && (
<>
<p className="text-xs text-muted-foreground">
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality,
next to the speed numbers.
</p>
<div className="flex flex-col gap-1.5">
{QUALITY_SECTIONS.map((s) => (
<label key={s} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{SECTION_LABEL[s]}</span>
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={!running || busy || sections.length === 0}>
<BadgeCheckIcon />
Run quality eval
</Button>
{!running && <p className="text-xs text-muted-foreground">Start the deployment to evaluate it.</p>}
</>
)}
{tab === "sweep" && (
<>
<p className="text-xs text-muted-foreground">
@@ -231,11 +261,15 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
<span className="min-w-0 truncate">
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
{r.kind !== "run" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">{r.kind === "ab" ? "A/B" : "quality"}</span>}
{r.label ?? new Date(r.createdAt).toLocaleString()}
</span>
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
{r.kind === "ab"
? r.ab && abHeadline(r.ab.decode_tps)
: r.kind === "eval"
? r.quality?.score != null && `${r.quality.score}%`
: h.decode != null && `${h.decode.toFixed(1)} t/s`}
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</span>
</Link>
+2 -2
View File
@@ -5,11 +5,11 @@ import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
export const dynamic = "force-dynamic";
/** ?ids=a,b,c (2–16 runs): headline numbers side by side, the setup values that differ, and the shared ones. */
export const GET = withToken("benchmarks:read", async (req, { token }) => {
export const GET = withToken("benchmarks:read", async (req) => {
try {
const ids = (new URL(req.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 16);
if (ids.length < 2) return v1Error(400, "invalid_request", "Pass at least two run ids: ?ids=<id>,<id>");
return v1Json(await compareRuns(ids, token));
return v1Json(await compareRuns(ids));
} catch (err) {
return v1Catch(err);
}
+1 -1
View File
@@ -17,7 +17,7 @@ export const GET = withToken("benchmarks:read", async (req, { token }) => {
}
});
/** Queue a benchmark run (kind "run") or a paired A/B (kind "ab") on the token's own running deployment(s). */
/** Queue a speed run (kind "run"), a paired A/B ("ab") or the quality eval ("eval") on the token's own running deployment(s). */
export const POST = withToken("benchmarks:run", async (req, { token }) => {
try {
const body = AgentRunBody.parse(await req.json());
+89
View File
@@ -0,0 +1,89 @@
{
"instructions": "Write the Python 3 function described below. Use only the standard library. Reply with the complete function definition, starting with def, in a single ```python code block and nothing else.",
"items": [
{
"id": "is-palindrome",
"prompt": "is_palindrome(s: str) -> bool: True if s reads the same forwards and backwards, ignoring case and every character that isn't a letter or a digit.",
"tests": [
"assert is_palindrome('A man, a plan, a canal: Panama') is True",
"assert is_palindrome('race a car') is False",
"assert is_palindrome('') is True",
"assert is_palindrome('No lemon, no melon') is True",
"assert is_palindrome('ab2a') is False"
]
},
{
"id": "fizzbuzz",
"prompt": "fizzbuzz(n: int) -> list[str]: for 1..n, 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, 'FizzBuzz' for multiples of both, else the number as a string.",
"tests": [
"assert fizzbuzz(5) == ['1', '2', 'Fizz', '4', 'Buzz']",
"assert fizzbuzz(15)[-1] == 'FizzBuzz'",
"assert fizzbuzz(0) == []",
"assert len(fizzbuzz(100)) == 100"
]
},
{
"id": "merge-intervals",
"prompt": "merge_intervals(intervals: list[list[int]]) -> list[list[int]]: merge overlapping or touching [start, end] intervals and return them sorted by start.",
"tests": [
"assert merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]",
"assert merge_intervals([[1, 4], [4, 5]]) == [[1, 5]]",
"assert merge_intervals([]) == []",
"assert merge_intervals([[5, 7], [1, 2]]) == [[1, 2], [5, 7]]",
"assert merge_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]"
]
},
{
"id": "word-count",
"prompt": "word_count(text: str) -> dict[str, int]: count words, lowercased, where a word is a run of letters (anything else separates words).",
"tests": [
"assert word_count('Hello, hello world!') == {'hello': 2, 'world': 1}",
"assert word_count('') == {}",
"assert word_count('one-two three') == {'one': 1, 'two': 1, 'three': 1}",
"assert word_count('A a A b') == {'a': 3, 'b': 1}"
]
},
{
"id": "roman-to-int",
"prompt": "roman_to_int(s: str) -> int: convert a Roman numeral (I, V, X, L, C, D, M, with subtractive forms like IV and CM) to an integer.",
"tests": [
"assert roman_to_int('III') == 3",
"assert roman_to_int('LVIII') == 58",
"assert roman_to_int('MCMXCIV') == 1994",
"assert roman_to_int('XLIX') == 49",
"assert roman_to_int('MMXXVI') == 2026"
]
},
{
"id": "flatten",
"prompt": "flatten(nested: list) -> list: return all non-list items of an arbitrarily nested list, in order.",
"tests": [
"assert flatten([1, [2, [3, [4]], 5]]) == [1, 2, 3, 4, 5]",
"assert flatten([]) == []",
"assert flatten([[], [[]], [1]]) == [1]",
"assert flatten(['a', ['b', ['c']]]) == ['a', 'b', 'c']"
]
},
{
"id": "second-largest",
"prompt": "second_largest(nums: list[int]) -> int | None: the second largest distinct value, or None if there isn't one.",
"tests": [
"assert second_largest([3, 1, 4, 1, 5, 9, 2, 6]) == 6",
"assert second_largest([7, 7, 7]) is None",
"assert second_largest([]) is None",
"assert second_largest([-2, -5, -1]) == -2",
"assert second_largest([10, 9]) == 9"
]
},
{
"id": "rle-encode",
"prompt": "rle_encode(s: str) -> str: run-length encode a string as each character followed by its run length, e.g. 'aaabcc' -> 'a3b1c2'.",
"tests": [
"assert rle_encode('aaabcc') == 'a3b1c2'",
"assert rle_encode('') == ''",
"assert rle_encode('abc') == 'a1b1c1'",
"assert rle_encode('zzzzzzzzzzzz') == 'z12'"
]
}
]
}
+41
View File
@@ -0,0 +1,41 @@
{
"lengths": [0.25, 0.5, 1.0],
"positions": [0.1, 0.5, 0.9],
"reserveTokens": 384,
"seed": 20261021,
"needle": "Note for later: the access code for the {color} vault is {code}.",
"question": "In the text above there is one note with an access code for the {color} vault. What is that access code? Answer with the six-digit number only.",
"colors": ["amber", "cobalt", "crimson", "jade", "silver", "violet", "ochre", "teal", "scarlet"],
"filler": [
"The river bends twice before it reaches the old mill at the edge of the valley.",
"Most of the orchard was planted after the long winter, when the soil had recovered.",
"A narrow path leads from the station to the market square, lined with plane trees.",
"In spring the meadows fill with clover and the bees return to the wooden hives.",
"The library keeps its oldest maps in a cool room behind the reading hall.",
"Fishing boats leave the harbour before dawn and come back around midday.",
"The bakery on the corner opens at six and is usually sold out by ten.",
"Snow rarely stays on the lower slopes for more than a few days at a time.",
"An old stone bridge crosses the stream where the two footpaths meet.",
"The town hall clock was repaired last year and now runs a minute fast.",
"Every autumn the vineyards hire extra hands for the harvest weeks.",
"The lighthouse has been automated, but a keeper still checks it each week.",
"A small museum by the church shows tools that farmers used a century ago.",
"The tram line was extended to the university campus in the north.",
"Wild garlic grows along the shaded banks of the brook in early May.",
"The guesthouse serves breakfast in a garden room that faces the hills.",
"Cyclists often stop at the fountain to refill their bottles before the climb.",
"The weekly market sells cheese from three farms in the neighbouring villages.",
"On clear nights the observatory opens its dome to visitors after nine.",
"The ferry runs every hour in summer and twice a day in the colder months.",
"A row of chestnut trees marks the old boundary of the monastery grounds.",
"The pottery workshop fires its kiln on Thursdays and sells seconds on Fridays.",
"Fog settles in the valley on most mornings and lifts by late morning.",
"The cooperative store stocks seeds, rope, lamp oil and tinned food.",
"Herons nest in the reeds at the far end of the lake each year.",
"The school bus takes the long way round when the pass is closed.",
"A painter rents the attic above the bookshop for the summer months.",
"The old railway embankment is now a walking trail through the woods.",
"Shepherds move the flocks to the high pastures in the first week of June.",
"The smithy still repairs gates and hinges for the farms nearby."
]
}
+160
View File
@@ -0,0 +1,160 @@
{
"tools": {
"get_weather": {
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City name, e.g. Berlin" },
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
},
"required": ["city", "unit"]
}
},
"convert_currency": {
"description": "Convert an amount of money between currencies.",
"parameters": {
"type": "object",
"properties": {
"amount": { "type": "number" },
"from": { "type": "string", "description": "ISO 4217 code, e.g. USD" },
"to": { "type": "string", "description": "ISO 4217 code, e.g. EUR" }
},
"required": ["amount", "from", "to"]
}
},
"create_calendar_event": {
"description": "Add an event to the user's calendar.",
"parameters": {
"type": "object",
"properties": {
"title": { "type": "string" },
"date": { "type": "string", "description": "YYYY-MM-DD" },
"time": { "type": "string", "description": "HH:MM, 24-hour" },
"duration_minutes": { "type": "integer" }
},
"required": ["title", "date", "time", "duration_minutes"]
}
},
"set_timer": {
"description": "Start a countdown timer.",
"parameters": {
"type": "object",
"properties": { "minutes": { "type": "integer" } },
"required": ["minutes"]
}
},
"get_stock_price": {
"description": "Latest price of a stock by its ticker symbol.",
"parameters": {
"type": "object",
"properties": { "ticker": { "type": "string", "description": "e.g. AAPL" } },
"required": ["ticker"]
}
},
"search_files": {
"description": "Search the user's files.",
"parameters": {
"type": "object",
"properties": {
"query": { "type": "string" },
"extension": { "type": "string", "description": "File extension without the dot, e.g. pdf" }
},
"required": ["query"]
}
},
"send_message": {
"description": "Send a chat message to a contact.",
"parameters": {
"type": "object",
"properties": {
"recipient": { "type": "string" },
"text": { "type": "string" }
},
"required": ["recipient", "text"]
}
},
"calculate": {
"description": "Evaluate an arithmetic expression.",
"parameters": {
"type": "object",
"properties": { "expression": { "type": "string", "description": "e.g. 3 * (4 + 5)" } },
"required": ["expression"]
}
}
},
"items": [
{
"id": "weather-berlin",
"tools": ["get_weather", "get_stock_price", "set_timer"],
"prompt": "What's the weather in Berlin right now? Use Celsius.",
"expect": { "name": "get_weather", "args": { "city": "Berlin", "unit": "celsius" } }
},
{
"id": "currency-usd-eur",
"tools": ["convert_currency", "calculate", "get_stock_price"],
"prompt": "How much is 250 US dollars in euros?",
"expect": { "name": "convert_currency", "args": { "amount": 250, "from": "USD", "to": "EUR" } }
},
{
"id": "calendar-budget",
"tools": ["create_calendar_event", "set_timer", "send_message"],
"prompt": "Put a meeting called Budget review on 2026-11-03 at 14:30 for 45 minutes in my calendar.",
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "budget review" }, "date": "2026-11-03", "time": "14:30", "duration_minutes": 45 } }
},
{
"id": "timer-12",
"tools": ["set_timer", "create_calendar_event", "get_weather"],
"prompt": "Set a timer for 12 minutes.",
"expect": { "name": "set_timer", "args": { "minutes": 12 } }
},
{
"id": "stock-aapl",
"tools": ["get_stock_price", "convert_currency", "search_files"],
"prompt": "What's Apple's stock price at the moment? The ticker is AAPL.",
"expect": { "name": "get_stock_price", "args": { "ticker": "AAPL" } }
},
{
"id": "files-invoices",
"tools": ["search_files", "send_message", "calculate"],
"prompt": "Find my PDF files about invoices.",
"expect": { "name": "search_files", "args": { "query": { "contains": "invoice" }, "extension": { "oneOf": ["pdf", ".pdf"] } } }
},
{
"id": "message-maria",
"tools": ["send_message", "create_calendar_event", "set_timer"],
"prompt": "Tell Maria that I'll be ten minutes late.",
"expect": { "name": "send_message", "args": { "recipient": "Maria", "text": { "contains": "late" } } }
},
{
"id": "weather-tokyo-f",
"tools": ["get_weather", "convert_currency", "search_files"],
"prompt": "Weather in Tokyo, in Fahrenheit please.",
"expect": { "name": "get_weather", "args": { "city": "Tokyo", "unit": "fahrenheit" } }
},
{
"id": "currency-jpy-chf",
"tools": ["calculate", "convert_currency", "get_weather"],
"prompt": "Convert 1200 Japanese yen to Swiss francs.",
"expect": { "name": "convert_currency", "args": { "amount": 1200, "from": "JPY", "to": "CHF" } }
},
{
"id": "timer-90",
"tools": ["create_calendar_event", "set_timer", "send_message"],
"prompt": "I need a 90 minute timer.",
"expect": { "name": "set_timer", "args": { "minutes": 90 } }
},
{
"id": "calendar-dentist",
"tools": ["send_message", "get_weather", "create_calendar_event"],
"prompt": "Schedule 'Dentist' for 2026-12-01 at 09:00, it takes 30 minutes.",
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "dentist" }, "date": "2026-12-01", "time": "09:00", "duration_minutes": 30 } }
},
{
"id": "calc-17x23",
"tools": ["calculate", "get_stock_price", "set_timer"],
"prompt": "What is 17 times 23? Use the calculator.",
"expect": { "name": "calculate", "args": { "expression": { "matches": "^\\s*17\\s*[*x×]\\s*23\\s*$" } } }
}
]
}
+37 -10
View File
@@ -6,7 +6,7 @@ import { gpuLoad } from "@/lib/agent-deployments";
import type { TokenIdentity } from "@/lib/api-tokens";
import { metaRows } from "@/lib/benchmark-meta";
import { headline } from "@/lib/benchmark-view";
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, type RunMeta } from "@/lib/db/schema";
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
import { db } from "@/lib/db/client";
import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
@@ -19,7 +19,8 @@ import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
export const AgentRunBody = z
.object({
kind: z.enum(["run", "ab"]).default("run"),
/** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
kind: z.enum(["run", "ab", "eval"]).default("run"),
deploymentId: z.string().min(1),
/** A/B: the second deployment (same model). */
deploymentBId: z.string().min(1).optional(),
@@ -31,6 +32,8 @@ export const AgentRunBody = z
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
mdePct: z.number().min(0.1).max(50).optional(),
maxPairs: z.number().int().min(12).max(2000).optional(),
/** eval: which sections (default all). */
sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
})
.strict();
@@ -46,6 +49,8 @@ export const AgentSweepBody = z
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant. */
quality: z.boolean().default(false),
})
.strict();
@@ -81,6 +86,8 @@ export async function requestRun(token: TokenIdentity, body: z.infer<typeof Agen
phases: body.phases,
mdePct: body.mdePct ?? null,
maxPairs: body.maxPairs ?? null,
kind: body.kind,
evalSections: body.sections,
}),
{ requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
);
@@ -103,7 +110,7 @@ export async function requestSweep(token: TokenIdentity, body: z.infer<typeof Ag
}
const pending = guard.approvalMode === "approve";
const row = await createSweep(
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases },
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
{
requestedBy: requested(token),
pendingApproval: pending,
@@ -132,10 +139,21 @@ export async function ownSweep(token: TokenIdentity, id: string) {
const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
/** The quality eval in short: overall score and per section. */
export function qualityView(q: QualityResult | null | undefined) {
if (!q) return null;
return {
evalSet: q.evalSet,
score: q.score,
sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
};
}
/** Headline numbers + the setup (section 1 metadata) as key/value. */
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null) {
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
const h = headline(summary);
return {
...(quality ? { quality: qualityView(quality) } : {}),
headline: {
decodeTps: r1(h.decode),
prefillTps: r1(h.prefill?.tps),
@@ -179,7 +197,8 @@ export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
...compact(r.summary, r.meta),
...compact(r.summary, r.meta, r.quality),
...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
...(r.kind === "ab" && r.ab
? {
ab: {
@@ -219,7 +238,16 @@ export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>
timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
variants: s.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId);
return { label: v.label, overrides: v.overrides, state: v.state, runId: v.runId ?? null, error: v.error ?? null, ...compact(run?.summary ?? null, run?.meta ?? null) };
const ev = data.runs.find((r) => r.id === v.evalRunId);
return {
label: v.label,
overrides: v.overrides,
state: v.state,
runId: v.runId ?? null,
evalRunId: v.evalRunId ?? null,
error: v.error ?? null,
...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
};
}),
startedAt: s.startedAt?.toISOString() ?? null,
finishedAt: s.finishedAt?.toISOString() ?? null,
@@ -228,16 +256,15 @@ export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>
}
/** Runs side by side: headline numbers and the setup keys whose values differ. */
export async function compareRuns(ids: string[], token: TokenIdentity) {
export async function compareRuns(ids: string[]) {
const runs = await getBenchmarks(ids);
const rows = runs.map((r) => ({ id: r.id, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta) }));
const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
return {
runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms. Differences under ~2 % between separate runs are noise; use an A/B for small effects.",
tokenName: token.name,
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
};
}
+46
View File
@@ -533,3 +533,49 @@ describe("the index", () => {
assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
});
});
describe("quality eval through the API", () => {
it("requests an eval run on the token's own deployment and reads its score", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
assert.equal(row?.kind, "eval");
assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
await M.db
.db()
.update(M.schema.benchmarkRuns)
.set({
state: "completed",
quality: {
evalSet: "kaname-eval-1",
score: 75,
sections: [
{ section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
],
items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
},
})
.where(eq(M.schema.benchmarkRuns.id, r.body.id));
const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
assert.equal(full.body.failed[0].id, "timer-12");
});
it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
assert.equal(bad.status, 400);
await setState(d.body.id, "stopped");
const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(s.status, 201);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
assert.equal(row?.settings.quality, true);
});
});
+2
View File
@@ -70,6 +70,8 @@ export function configChips(s: BenchmarkSnapshot): string[] {
}
export function describeSettings(st: BenchmarkSettings): string {
// A quality eval's settings carry its sections (empty: all).
if (st.evalSections) return `quality eval · ${st.evalSections.length ? st.evalSections.join(", ") : "all sections"}`;
const passes = st.passes ?? (st.quick ? 5 : 20);
const phases = st.phases.length ? st.phases.join(", ") : "all phases";
return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
+20 -10
View File
@@ -5,7 +5,7 @@ import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns } from "@/lib/db/schema";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
@@ -35,6 +35,10 @@ export const BenchmarkBody = z.object({
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
/** Set by sweeps. */
sweepId: z.string().nullable().optional(),
/** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
kind: z.enum(["run", "ab", "eval"]).optional(),
/** eval: which sections (empty: all). */
evalSections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
});
export type BenchmarkInput = z.infer<typeof BenchmarkBody>;
@@ -54,7 +58,9 @@ async function snapshotOf(deploymentId: string, role: string) {
export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
const ab = !!input.deploymentBId;
const kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
const ab = kind === "ab";
if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
if (b) {
@@ -66,19 +72,22 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind: ab ? "ab" : "run",
kind,
deploymentId: a.id,
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
settings:
kind === "eval"
? { quick: false, passes: null, warmup: null, phases: [], evalSections: input.evalSections ?? [] }
: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
snapshot: a.snapshot,
snapshotB: b?.snapshot ?? null,
sweepId: input.sweepId ?? null,
@@ -116,6 +125,7 @@ const listColumns = {
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
quality: benchmarkRuns.quality,
sweepId: benchmarkRuns.sweepId,
requestedBy: benchmarkRuns.requestedBy,
requestedByTokenId: benchmarkRuns.requestedByTokenId,
+31 -2
View File
@@ -703,9 +703,34 @@ export type BenchmarkSettings = {
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
mdePct?: number | null;
maxPairs?: number | null;
/** eval: which sections (empty: all). Sweeps: also run the quality eval for each variant. */
evalSections?: QualitySection[];
quality?: boolean;
};
export const BENCHMARK_KINDS = ["run", "ab"] as const;
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
export type QualityResult = {
/** The eval set's version; only results of the same version are comparable. */
evalSet: string;
score: number | null;
sections: {
section: QualitySection;
passed: number;
total: number;
score: number | null;
/** Why the section couldn't run (e.g. the server doesn't do tool calls); then it doesn't count. */
unsupported?: string | null;
seconds: number;
}[];
items: { section: QualitySection; id: string; pass: boolean; detail?: string | null }[];
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
};
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
@@ -945,6 +970,8 @@ export const benchmarkRuns = sqliteTable(
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** kind "eval": the quality eval's result. */
quality: text("quality", { mode: "json" }).$type<QualityResult>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Requested through the API: the token and its name at the time. */
@@ -1026,9 +1053,11 @@ export type SweepVariant = {
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
overrides: Record<string, unknown>;
label: string;
state: "pending" | "deploying" | "benchmarking" | "done" | "failed" | "skipped";
state: "pending" | "deploying" | "benchmarking" | "evaluating" | "done" | "failed" | "skipped";
deploymentId?: string | null;
runId?: string | null;
/** The quality eval run of this variant (sweeps with quality: true). */
evalRunId?: string | null;
error?: string | null;
};
+12
View File
@@ -0,0 +1,12 @@
// Labels for the quality eval's sections. Pure and small: safe for client components (the eval set
// itself stays in src/lib/quality.ts).
import type { QualitySection } from "@/lib/db/schema";
export const SECTION_LABEL: Record<QualitySection, string> = { tools: "Tool calling", coding: "Coding", retrieval: "Long-context retrieval" };
export const SECTION_HINT: Record<QualitySection, string> = {
tools: "12 requests: valid JSON, the right function and arguments",
coding: "8 short Python functions, checked by unit tests in a sandbox",
retrieval: "a code hidden at 3 depths in 3 text lengths up to the context size",
};
+135
View File
@@ -0,0 +1,135 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { describe, it } from "node:test";
import { argMatches, buildHaystack, EVAL_SET, extractCode, prng, retrievalCases, scoreNeedle, scoreToolCall, summarize, testProgram, toolDefs } from "./quality";
describe("eval set", () => {
it("tool items only use defined tools and expect one of their own", () => {
for (const item of EVAL_SET.tools.items) {
for (const t of item.tools) assert.ok(EVAL_SET.tools.tools[t], `${item.id}: unknown tool ${t}`);
assert.ok(item.tools.includes(item.expect.name), `${item.id}: expects ${item.expect.name}, not offered`);
const params = EVAL_SET.tools.tools[item.expect.name].parameters as { properties: Record<string, unknown> };
for (const k of Object.keys(item.expect.args)) assert.ok(params.properties[k], `${item.id}: ${k} isn't a parameter`);
}
assert.equal(EVAL_SET.tools.items.length, 12);
assert.equal(toolDefs(EVAL_SET.tools.items[0])[0].type, "function");
});
it("has unique ids", () => {
const ids = [...EVAL_SET.tools.items, ...EVAL_SET.coding.items].map((i) => i.id);
assert.equal(new Set(ids).size, ids.length);
});
// Reference solutions: the eval's own tests must accept a correct answer.
const python = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).status === 0);
const REFERENCE: Record<string, string> = {
"is-palindrome": "def is_palindrome(s):\n t = [c.lower() for c in s if c.isalnum()]\n return t == t[::-1]",
fizzbuzz:
"def fizzbuzz(n):\n return ['FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, n + 1)]",
"merge-intervals":
"def merge_intervals(intervals):\n out = []\n for s, e in sorted(intervals):\n if out and s <= out[-1][1]:\n out[-1][1] = max(out[-1][1], e)\n else:\n out.append([s, e])\n return out",
"word-count":
"import re\ndef word_count(text):\n d = {}\n for w in re.findall('[A-Za-z]+', text):\n d[w.lower()] = d.get(w.lower(), 0) + 1\n return d",
"roman-to-int":
"def roman_to_int(s):\n v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n n = 0\n for i, c in enumerate(s):\n n += -v[c] if i + 1 < len(s) and v[s[i + 1]] > v[c] else v[c]\n return n",
flatten: "def flatten(nested):\n out = []\n for x in nested:\n out.extend(flatten(x) if isinstance(x, list) else [x])\n return out",
"second-largest": "def second_largest(nums):\n u = sorted(set(nums))\n return u[-2] if len(u) > 1 else None",
"rle-encode":
"from itertools import groupby\ndef rle_encode(s):\n return ''.join(f'{k}{len(list(g))}' for k, g in groupby(s))",
};
it("coding tests pass for a correct solution and fail for a wrong one", { skip: !python && "no python here" }, () => {
for (const item of EVAL_SET.coding.items) {
const ok = spawnSync(python!, ["-I", "-c", testProgram(REFERENCE[item.id], item.tests)], { encoding: "utf8" });
assert.equal(ok.status, 0, `${item.id}: ${ok.stderr}`);
assert.match(ok.stdout, /KANAME-OK/);
const fname = item.prompt.split("(")[0];
const bad = spawnSync(python!, ["-I", "-c", testProgram(`def ${fname}(*a, **k):\n return None`, item.tests)], { encoding: "utf8" });
assert.notEqual(bad.status, 0, `${item.id}: a wrong answer passed`);
}
});
});
describe("tool call scoring", () => {
const expect = EVAL_SET.tools.items.find((i) => i.id === "calendar-budget")!.expect;
const call = (args: unknown, name = "create_calendar_event") => [{ name, arguments: typeof args === "string" ? args : JSON.stringify(args) }];
it("accepts the right function with matching arguments (case-insensitive, extra ones fine)", () => {
const r = scoreToolCall(call({ title: "Budget Review", date: "2026-11-03", time: "14:30", duration_minutes: 45, location: "x" }), expect);
assert.equal(r.pass, true);
assert.equal(scoreToolCall(call({ title: "budget review meeting", date: "2026-11-03", time: "14:30", duration_minutes: "45" }), expect).pass, true);
});
it("refuses invalid JSON, the wrong function, wrong or missing arguments, several calls, none", () => {
assert.match(scoreToolCall(call("{title: 'x'"), expect).detail, /invalid JSON/);
assert.match(scoreToolCall(call("[1]"), expect).detail, /JSON object/);
assert.match(scoreToolCall(call({}, "set_timer"), expect).detail, /called set_timer/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-04", time: "14:30", duration_minutes: 45 }), expect).detail, /wrong date/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-03", time: "14:30" }), expect).detail, /wrong duration_minutes=undefined/);
assert.match(scoreToolCall([...call({}), ...call({})], expect).detail, /2 tool calls/);
assert.equal(scoreToolCall([], expect).pass, false);
assert.equal(scoreToolCall(null, expect).pass, false);
});
it("matches the argument rules", () => {
assert.ok(argMatches("PDF", { oneOf: ["pdf", ".pdf"] }));
assert.ok(argMatches(" 17 * 23 ", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(!argMatches("17+23", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(argMatches(250.0, 250));
assert.ok(!argMatches(null, "x"));
});
});
describe("code extraction", () => {
it("takes the last python block, or bare code", () => {
assert.equal(extractCode("Here:\n```python\ndef a(): pass\n```\nand\n```py\ndef b(): pass\n```"), "def b(): pass");
assert.equal(extractCode("```\ndef c(): pass\n```"), "def c(): pass");
assert.equal(extractCode("def d():\n return 1"), "def d():\n return 1");
assert.equal(extractCode("I can't do that."), null);
});
});
describe("long-context retrieval", () => {
it("plans lengths × positions within the context, deterministic codes", () => {
const c = retrievalCases(32768);
assert.equal(c.length, 9);
assert.ok(c.every((x) => x.targetTokens <= 32768 - EVAL_SET.retrieval.reserveTokens));
assert.deepEqual(retrievalCases(32768), c);
assert.ok(c.every((x) => /^\d{6}$/.test(x.code)));
assert.equal(retrievalCases(600).length, 0, "too short for any haystack");
assert.equal(retrievalCases(1200).length, 6, "the 25 % length is under 256 tokens");
});
it("puts the needle at its depth and the question at the end", () => {
const [first, , last] = retrievalCases(16384);
for (const c of [first, last]) {
const text = buildHaystack(c, 4);
const at = text.indexOf(c.code) / text.length;
assert.ok(Math.abs(at - c.position) < 0.05, `needle at ${at}, wanted ${c.position}`);
assert.ok(text.trimEnd().endsWith("only."));
assert.ok(Math.abs(text.length / 4 - c.targetTokens) / c.targetTokens < 0.06);
}
assert.equal(buildHaystack(first, 4), buildHaystack(first, 4));
});
it("scores the answer by the six digits", () => {
const c = retrievalCases(8192)[0];
assert.equal(scoreNeedle(`The code is ${c.code}.`, c).pass, true);
assert.equal(scoreNeedle("123456", { ...c, code: "654321" }).pass, false);
const r = prng(1);
assert.equal(prng(1)(), r());
});
});
describe("score", () => {
it("averages the sections that ran", () => {
const s = summarize([
{ section: "tools", passed: 9, total: 12, score: null, seconds: 10 },
{ section: "coding", passed: 4, total: 8, score: null, seconds: 30 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "context unknown", seconds: 0 },
]);
assert.equal(s.score, 62.5);
assert.deepEqual(s.sections.map((x) => x.score), [75, 50, null]);
assert.equal(summarize([]).score, null);
});
});
+175
View File
@@ -0,0 +1,175 @@
// The quality eval: a small, deterministic check of what a deployment produces (not how fast), so
// launch options that change the output (quant, KV cache type, context, sampling bugs in a build)
// show up next to the speed numbers. Pure: the eval set, prompt building and scoring; the worker
// (src/worker/quality.ts) talks to the server and the code sandbox.
import type { QualityResult } from "@/lib/db/schema";
import coding from "@/evals/v1/coding.json";
import retrieval from "@/evals/v1/retrieval.json";
import tools from "@/evals/v1/tools.json";
/** Bump with any change to the eval set or the scoring: results are only comparable within a version. */
export const EVAL_SET_VERSION = "kaname-eval-1";
export const EVAL_SEED = 1;
export type ArgRule = string | number | boolean | { contains: string } | { oneOf: (string | number)[] } | { matches: string };
export type ToolItem = { id: string; tools: string[]; prompt: string; expect: { name: string; args: Record<string, ArgRule> } };
export type CodingItem = { id: string; prompt: string; tests: string[] };
export const EVAL_SET = {
version: EVAL_SET_VERSION,
tools: tools as unknown as { tools: Record<string, { description: string; parameters: Record<string, unknown> }>; items: ToolItem[] },
coding: coding as { instructions: string; items: CodingItem[] },
retrieval: retrieval as {
lengths: number[];
positions: number[];
reserveTokens: number;
seed: number;
needle: string;
question: string;
colors: string[];
filler: string[];
},
};
// --- tool calling ---------------------------------------------------------------------------
/** The OpenAI `tools` array for an item. */
export function toolDefs(item: ToolItem) {
return item.tools.map((name) => ({ type: "function" as const, function: { name, ...EVAL_SET.tools.tools[name] } }));
}
const norm = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : v);
/** One argument against its rule: strings case-insensitively, numbers by value. */
export function argMatches(value: unknown, rule: ArgRule): boolean {
if (value === undefined || value === null) return false;
if (typeof rule === "object") {
if ("contains" in rule) return typeof value === "string" && value.toLowerCase().includes(rule.contains.toLowerCase());
if ("oneOf" in rule) return rule.oneOf.some((r) => argMatches(value, r));
if ("matches" in rule) return typeof value === "string" && new RegExp(rule.matches, "i").test(value);
}
if (typeof rule === "number") return Number(value) === rule;
return norm(value) === norm(rule);
}
export type ToolCall = { name: string; arguments: string };
/**
* A tool call is right when there is exactly one, its arguments are valid JSON, the function is the
* expected one and every expected argument matches (extra arguments are fine).
*/
export function scoreToolCall(calls: ToolCall[] | null | undefined, expect: ToolItem["expect"]): { pass: boolean; detail: string } {
if (!calls || calls.length === 0) return { pass: false, detail: "no tool call" };
if (calls.length > 1) return { pass: false, detail: `${calls.length} tool calls, expected one` };
const [c] = calls;
let args: Record<string, unknown>;
try {
const parsed = JSON.parse(c.arguments || "{}");
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { pass: false, detail: "arguments aren't a JSON object" };
args = parsed as Record<string, unknown>;
} catch {
return { pass: false, detail: `invalid JSON arguments: ${c.arguments.slice(0, 120)}` };
}
if (c.name !== expect.name) return { pass: false, detail: `called ${c.name}, expected ${expect.name}` };
const wrong = Object.entries(expect.args).filter(([k, rule]) => !argMatches(args[k], rule));
if (wrong.length) return { pass: false, detail: `wrong ${wrong.map(([k]) => `${k}=${JSON.stringify(args[k])}`).join(", ")}` };
return { pass: true, detail: `${c.name}(${JSON.stringify(args)})` };
}
// --- coding -------------------------------------------------------------------------------
/** The last ```python block of a reply (or the only fenced block); null without one. */
export function extractCode(reply: string): string | null {
const blocks = [...reply.matchAll(/```(?:python|py)?[ \t]*\r?\n([\s\S]*?)```/gi)].map((m) => m[1]);
if (blocks.length) return blocks[blocks.length - 1].trim() || null;
// Some models answer with bare code.
return /^\s*(def|import|from)\s/m.test(reply) ? reply.trim() : null;
}
/** The program the sandbox runs: the model's code, then the tests; prints OK when all pass. */
export function testProgram(code: string, tests: string[]): string {
return `${code}\n\n# --- tests ---\n${tests.join("\n")}\nprint("KANAME-OK")\n`;
}
// --- long-context retrieval ---------------------------------------------------------------
/** A small, seeded PRNG (mulberry32): the haystacks are the same every run. */
export function prng(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export type NeedleCase = { id: string; targetTokens: number; position: number; color: string; code: string };
/** The cases for a context of `contextTokens`: each length × each needle position, deduplicated. */
export function retrievalCases(contextTokens: number): NeedleCase[] {
const r = EVAL_SET.retrieval;
const usable = Math.max(0, contextTokens - r.reserveTokens);
const rand = prng(r.seed);
const out: NeedleCase[] = [];
const seen = new Set<number>();
let i = 0;
for (const len of r.lengths) {
const target = Math.floor(usable * len);
if (target < 256 || seen.has(target)) continue;
seen.add(target);
for (const position of r.positions) {
out.push({
id: `${Math.round(target / 100) / 10}k@${Math.round(position * 100)}%`,
targetTokens: target,
position,
color: r.colors[i++ % r.colors.length],
code: String(100000 + Math.floor(rand() * 900000)),
});
}
}
return out;
}
/**
* The haystack for a case: filler sentences in a seeded order up to about `targetTokens` (measured
* with the server's own tokenizer as characters per token), the needle at `position`, then the
* question.
*/
export function buildHaystack(c: NeedleCase, charsPerToken: number): string {
const r = EVAL_SET.retrieval;
const rand = prng(r.seed + c.targetTokens);
const targetChars = Math.floor(c.targetTokens * charsPerToken * 0.97);
const parts: string[] = [];
let len = 0;
while (len < targetChars) {
const s = r.filler[Math.floor(rand() * r.filler.length)];
parts.push(s);
len += s.length + 1;
}
const needle = r.needle.replace("{color}", c.color).replace("{code}", c.code);
parts.splice(Math.round(parts.length * c.position), 0, needle);
return `${parts.join(" ")}\n\n${r.question.replace("{color}", c.color)}`;
}
/** Did the answer give the code (the six digits, anywhere)? */
export function scoreNeedle(answer: string, c: NeedleCase): { pass: boolean; detail: string } {
const found: string[] = answer.match(/\d{6}/g) ?? [];
return found.includes(c.code) ? { pass: true, detail: c.code } : { pass: false, detail: `expected ${c.code}, got ${JSON.stringify(answer.trim().slice(0, 80))}` };
}
// --- score --------------------------------------------------------------------------------
/** Section pass rates and the overall score (mean of the sections that could run), 0–100. */
export function summarize(
sections: QualityResult["sections"],
): Pick<QualityResult, "score" | "sections"> {
const counted = sections.filter((s) => !s.unsupported && s.total > 0);
const withScore = sections.map((s) => ({ ...s, score: !s.unsupported && s.total > 0 ? Math.round((s.passed / s.total) * 1000) / 10 : null }));
const score = counted.length ? Math.round((counted.reduce((n, s) => n + s.passed / s.total, 0) / counted.length) * 1000) / 10 : null;
return { score, sections: withScore };
}
export { SECTION_LABEL } from "@/lib/quality-view";
+15 -4
View File
@@ -28,6 +28,8 @@ export const SweepBody = z.object({
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).nullable().optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant (after its speed run). */
quality: z.boolean().default(false),
});
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
@@ -76,7 +78,7 @@ export async function createSweep(input: z.infer<typeof SweepBody>, agent?: Agen
// The variants' deployments must not publish ports or require a second copy of the base's port.
base: { name: base.name, runtimeId: base.runtimeId, modelId: base.modelId, options: base.options, cpus: base.cpus, memoryMb: base.memoryMb },
params: input.params,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases, quality: input.quality },
variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })),
...(agent
? {
@@ -101,10 +103,19 @@ export async function listSweeps(): Promise<SweepRow[]> {
export async function getSweep(id: string) {
const sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!sweep) return null;
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = sweep.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error, meta: benchmarkRuns.meta })
.select({
id: benchmarkRuns.id,
state: benchmarkRuns.state,
summary: benchmarkRuns.summary,
resources: benchmarkRuns.resources,
phase: benchmarkRuns.phase,
error: benchmarkRuns.error,
meta: benchmarkRuns.meta,
quality: benchmarkRuns.quality,
})
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
@@ -136,7 +147,7 @@ export async function deleteSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "running" || s.state === "queued") throw new SweepRequestError("busy", "Cancel the sweep first.", 409);
const runIds = s.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = s.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
if (runIds.length) {
await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds));
await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds));
+105 -15
View File
@@ -11,7 +11,22 @@ import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchma
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema";
import {
apiKeys,
type BenchmarkKind,
benchmarkLogs,
benchmarkRuns,
type BenchmarkSummary,
deployments,
type LogStream,
QUALITY_SECTIONS,
type QualityResult,
type QualitySection,
type RunMeta,
runtimes,
type SystemSummary,
} from "@/lib/db/schema";
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { abSummary } from "./ab-summary";
@@ -21,13 +36,16 @@ import { log } from "./log";
import { normalizePciAddress } from "./hardware";
import { errorCauses } from "./log-causes";
import { type GpuTargets, ResourceSampler } from "./resources";
import { runQualityEval } from "./quality";
import { docker, workerImage } from "./runtimes";
type Current = {
runId: string;
kind: "run" | "ab";
kind: BenchmarkKind;
deploymentIds: string[];
child: ChildProcess;
/** BetterBench (runs, A/B); null for a quality eval, which runs in-process and stops via `abort`. */
child: ChildProcess | null;
abort: AbortController | null;
sampler: ResourceSampler | null;
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
meta: RunMeta | null;
@@ -204,6 +222,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
const setup = await runSetup([a.id, b?.id ?? null]);
const [meta, metaB] = setup.metas;
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
if (run.kind === "eval") return startEval(run, a, keys, meta, setup.system);
const args =
run.kind === "ab" && b
? abArgs({
@@ -278,6 +297,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
kind: run.kind,
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
abort: null,
sampler,
meta,
metaB,
@@ -296,13 +316,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
const id = cur.runId;
for (const stream of ["stdout", "stderr"] as const) {
const rest = partial.get(`${id}:${stream}`);
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
/** Stop the resource sampler; record the PCIe links seen under load in the run's meta. */
async function stopSampling(cur: Current) {
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
if (resources?.links) {
@@ -310,9 +325,82 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
await db()
.update(benchmarkRuns)
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
.where(eq(benchmarkRuns.id, id))
.catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`));
.where(eq(benchmarkRuns.id, cur.runId))
.catch((err) => log.warn(`benchmark ${cur.runId}: link update failed: ${message(err)}`));
}
return resources;
}
/** Kaname's quality eval: in-process against the deployment, coding answers in the sandbox. */
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys: string[], meta: RunMeta | null, system: SystemSummary) {
const s = run.snapshot;
const sections = run.settings.evalSections?.length ? run.settings.evalSections : [...QUALITY_SECTIONS];
const dep = await db().query.deployments.findFirst({ columns: { engineInfo: true, options: true }, where: eq(deployments.id, a.id) });
const contextTokens = dep?.engineInfo?.contextSize ?? dep?.options.contextSize ?? s.options.contextSize ?? null;
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${s.deploymentName} (${s.repoId} on ${s.runtimeName}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, system }).where(eq(benchmarkRuns.id, run.id));
const c = docker();
const sampler = c ? new ResourceSampler(c, [{ side: "a" as const, containerId: a.containerId }], await gpuTargets([meta, null])) : null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const cur: Current = {
runId: run.id,
kind: "eval",
deploymentIds: [a.id],
child: null,
abort: new AbortController(),
sampler,
meta,
metaB: null,
maxPairs: null,
cancelled: false,
lost: null,
secrets: keys,
};
current = cur;
log.info(`benchmark ${run.id}: quality eval started for ${s.deploymentName}`);
const onLine = (line: string) => {
addLog(run.id, "stdout", line, keys);
const m = line.match(/^(tools|coding|retrieval): starting$/);
if (m) void db().update(benchmarkRuns).set({ phase: `Quality: ${SECTION_LABEL[m[1] as QualitySection]}` }).where(eq(benchmarkRuns.id, run.id)).then(() => {}, () => {});
};
runQualityEval(
{ base: `http://${a.containerName}:${ENGINE_PORT[a.engine]}`, model: s.repoId, engine: a.engine, apiKey: keys[0] ?? null, contextTokens },
{ sections, signal: cur.abort!.signal, log: onLine, docker: c, sandboxImage: workerImage() },
).then(
(q) => doneEval(cur, q, null),
(err) => doneEval(cur, null, err),
);
}
async function doneEval(cur: Current, quality: QualityResult | null, err: unknown) {
const id = cur.runId;
const resources = await stopSampling(cur);
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", quality, resources });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, quality, resources });
} else if (err || !quality) {
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}`, resources });
} else {
addLog(id, "system", `Done: score ${quality.score ?? "–"} (${quality.sections.map((x) => `${x.section} ${x.unsupported ? "n/a" : `${x.passed}/${x.total}`}`).join(", ")}).`);
await finish(id, { state: "completed", quality, resources });
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: quality eval ${cur.cancelled ? "cancelled" : cur.lost || err ? "failed" : `done, score ${quality?.score}`}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
const id = cur.runId;
for (const stream of ["stdout", "stderr"] as const) {
const rest = partial.get(`${id}:${stream}`);
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
const resources = await stopSampling(cur);
const dir = runDir(id);
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
@@ -357,9 +445,11 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
}
function stop(cur: Current) {
if (cur.child.exitCode !== null) return;
cur.child.kill("SIGTERM");
setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref();
const child = cur.child;
if (!child) return void cur.abort?.abort();
if (child.exitCode !== null) return;
child.kill("SIGTERM");
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 10_000).unref();
}
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
+101
View File
@@ -0,0 +1,101 @@
// The quality eval against a fake OpenAI-compatible server: requests, scoring, unsupported sections,
// cancelling. (The code sandbox needs Docker; here coding counts as unsupported.)
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, before, describe, it } from "node:test";
import { EVAL_SET } from "@/lib/quality";
import { runQualityEval } from "./quality";
type Body = { messages: { content: string }[]; tools?: unknown[]; temperature?: number; seed?: number; chat_template_kwargs?: { enable_thinking?: boolean } };
let server: Server;
let base = "";
let refuseTools = false;
const seen: Body[] = [];
before(async () => {
server = createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
const body = JSON.parse(raw || "{}") as Body & { content?: string };
const json = (status: number, v: unknown) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(v));
};
if (req.url === "/tokenize") return json(200, { tokens: new Array(Math.ceil((body.content ?? "").length / 4)).fill(1) });
if (req.url !== "/v1/chat/completions") return json(404, {});
seen.push(body);
const prompt = body.messages[0].content;
if (body.tools) {
if (refuseTools) return json(400, { error: { message: "tools param requires --jinja flag" } });
const item = EVAL_SET.tools.items.find((i) => i.prompt === prompt)!;
// Half right: every other item calls the wrong function.
const idx = EVAL_SET.tools.items.indexOf(item);
const args = Object.fromEntries(Object.entries(item.expect.args).map(([k, v]) => [k, typeof v === "object" ? ("contains" in v ? v.contains : "oneOf" in v ? v.oneOf[0] : "17 * 23") : v]));
const wrong = item.expect.name === "set_timer" ? "get_weather" : "set_timer";
const name = idx % 2 === 0 ? item.expect.name : wrong;
return json(200, { choices: [{ message: { content: null, tool_calls: [{ function: { name, arguments: JSON.stringify(args) } }] } }] });
}
const code = prompt.match(/vault is (\d{6})/)?.[1];
// Finds the needle in the first two thirds of the text only.
const found = code && prompt.indexOf(code) / prompt.length < 0.66;
return json(200, { choices: [{ message: { content: found ? `The code is ${code}.` : "I couldn't find it." } }] });
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => server.close());
const target = () => ({ base, model: "test/model", engine: "llama.cpp" as const, apiKey: null, contextTokens: 4096 });
const opts = (o: Partial<Parameters<typeof runQualityEval>[1]> = {}) => ({
sections: ["tools", "coding", "retrieval"] as const as ("tools" | "coding" | "retrieval")[],
signal: new AbortController().signal,
log: () => {},
docker: null,
sandboxImage: null,
...o,
});
describe("quality eval run", () => {
it("scores tool calls and retrieval, greedy with a fixed seed and thinking off", async () => {
seen.length = 0;
const q = await runQualityEval(target(), opts());
const by = Object.fromEntries(q.sections.map((s) => [s.section, s]));
assert.equal(by.tools.passed, 6);
assert.equal(by.tools.total, 12);
assert.match(by.coding.unsupported!, /sandbox/);
assert.equal(by.retrieval.total, 9);
assert.equal(by.retrieval.passed, 6, "positions 10 % and 50 % found, 90 % not");
assert.equal(q.score, 58.3, "mean of 50 % and 66.7 %; coding doesn't count");
assert.equal(q.evalSet, "kaname-eval-1");
assert.ok(seen.every((b) => b.temperature === 0 && b.seed === 1 && b.chat_template_kwargs?.enable_thinking === false));
assert.equal(q.items.filter((i) => i.section === "tools" && !i.pass)[0].detail, "called set_timer, expected convert_currency");
});
it("marks tool calling unsupported when the server refuses tools", async () => {
refuseTools = true;
try {
const q = await runQualityEval(target(), opts({ sections: ["tools"] }));
assert.match(q.sections[0].unsupported!, /refused tool calls: .*--jinja/);
assert.equal(q.score, null);
} finally {
refuseTools = false;
}
});
it("can't plan retrieval without a context length", async () => {
const q = await runQualityEval({ ...target(), contextTokens: null }, opts({ sections: ["retrieval"] }));
assert.match(q.sections[0].unsupported!, /context length is unknown/);
});
it("stops early when cancelled", async () => {
const ac = new AbortController();
ac.abort();
const q = await runQualityEval(target(), opts({ signal: ac.signal }));
assert.equal(q.sections.length, 0);
});
});
+242
View File
@@ -0,0 +1,242 @@
// Runs the quality eval (src/lib/quality.ts) against a running deployment: greedy decoding with a
// fixed seed, thinking turned off where the chat template supports it, scoring that doesn't depend
// on judgement. Coding answers run with their unit tests in a throwaway container from Kaname's own
// image: no network, read-only, unprivileged user, all capabilities dropped, small limits.
import type { QualityResult, QualitySection, RuntimeEngine } from "@/lib/db/schema";
import {
buildHaystack,
EVAL_SEED,
EVAL_SET,
EVAL_SET_VERSION,
extractCode,
retrievalCases,
scoreNeedle,
scoreToolCall,
summarize,
testProgram,
type ToolCall,
toolDefs,
} from "@/lib/quality";
import type { DockerClient } from "./docker/client";
export type EvalTarget = {
/** http://<container>:<port> */
base: string;
model: string;
engine: RuntimeEngine;
apiKey: string | null;
/** Context per request (llama.cpp: per slot), for the retrieval lengths. */
contextTokens: number | null;
};
export type EvalOptions = {
sections: QualitySection[];
signal: AbortSignal;
log: (line: string) => void;
docker: DockerClient | null;
/** Image for the coding sandbox (Kaname's own, it has Python); null: coding can't run. */
sandboxImage: string | null;
};
const TEMPERATURE = 0;
const THINKING = false;
class HttpError extends Error {
constructor(
public status: number,
message: string,
) {
super(message);
}
}
async function post<T>(t: EvalTarget, path: string, body: unknown, signal: AbortSignal, timeoutMs: number): Promise<T> {
const res = await fetch(`${t.base}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json", ...(t.apiKey ? { Authorization: `Bearer ${t.apiKey}` } : {}) },
body: JSON.stringify(body),
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
});
const text = await res.text();
if (!res.ok) throw new HttpError(res.status, text.slice(0, 300));
return JSON.parse(text) as T;
}
type ChatMessage = { content?: string | null; tool_calls?: { function?: { name?: string; arguments?: string } }[] };
/** One greedy chat completion; thinking off (Qwen3-style templates read enable_thinking, others ignore it). */
async function chat(t: EvalTarget, messages: { role: string; content: string }[], extra: Record<string, unknown>, signal: AbortSignal, timeoutMs = 300_000) {
const r = await post<{ choices?: { message?: ChatMessage }[] }>(
t,
"/v1/chat/completions",
{ model: t.model, messages, temperature: TEMPERATURE, seed: EVAL_SEED, chat_template_kwargs: { enable_thinking: THINKING }, ...extra },
signal,
timeoutMs,
);
return r.choices?.[0]?.message ?? {};
}
type Section = QualityResult["sections"][number];
type Item = QualityResult["items"][number];
async function toolsSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
let passed = 0;
const all = EVAL_SET.tools.items;
for (const item of all) {
if (o.signal.aborted) break;
try {
const m = await chat(t, [{ role: "user", content: item.prompt }], { tools: toolDefs(item), tool_choice: "auto", max_tokens: 512 }, o.signal);
const calls: ToolCall[] = (m.tool_calls ?? []).map((c) => ({ name: c.function?.name ?? "", arguments: c.function?.arguments ?? "" }));
const r = scoreToolCall(calls, item.expect);
if (r.pass) passed++;
items.push({ section: "tools", id: item.id, pass: r.pass, detail: r.detail });
o.log(`tools ${item.id}: ${r.pass ? "pass" : `fail (${r.detail})`}`);
} catch (err) {
// The server can't do tool calls at all (e.g. no tool-call parser configured): the section
// doesn't count instead of scoring 0.
if (err instanceof HttpError && err.status >= 400 && err.status < 500 && items.every((x) => x.section !== "tools")) {
o.log(`tools: the server refused tool calls (${err.status}): ${err.message}`);
return { section: "tools", passed: 0, total: 0, unsupported: `the server refused tool calls: ${err.message.slice(0, 200)}` };
}
if (o.signal.aborted) break;
items.push({ section: "tools", id: item.id, pass: false, detail: err instanceof Error ? err.message.slice(0, 200) : String(err) });
o.log(`tools ${item.id}: error ${err instanceof Error ? err.message : err}`);
}
}
return { section: "tools", passed, total: all.length };
}
/** Run a program in the sandbox; ok when it exits 0 and printed the marker. */
async function runPython(c: DockerClient, image: string, program: string, signal: AbortSignal): Promise<{ ok: boolean; output: string }> {
const runner = "import base64,os;exec(compile(base64.b64decode(os.environ['KANAME_CODE']).decode(),'solution','exec'),{'__name__':'__main__'})";
const created = await c.createContainer(`kaname-eval-sandbox-${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`, {
Image: image,
User: "65534:65534",
Entrypoint: ["python3", "-I", "-c", runner],
Cmd: [],
Env: [`KANAME_CODE=${Buffer.from(program).toString("base64")}`, "PYTHONDONTWRITEBYTECODE=1"],
NetworkDisabled: true,
Labels: { "kaname.managed": "true", "kaname.probe": "eval-sandbox" },
HostConfig: {
NetworkMode: "none",
ReadonlyRootfs: true,
Tmpfs: { "/tmp": "rw,noexec,nosuid,size=16m" },
CapDrop: ["ALL"],
SecurityOpt: ["no-new-privileges"],
Memory: 256 * 2 ** 20,
MemorySwap: 256 * 2 ** 20,
NanoCpus: 1e9,
PidsLimit: 64,
Privileged: false,
AutoRemove: false,
},
});
const lines: string[] = [];
try {
await c.startContainer(created.Id);
await c
.followLogs(created.Id, (_s, line) => lines.length < 200 && lines.push(line), { tail: "all", signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]) })
.catch(() => {});
const st = await c.containerState(created.Id);
if (st?.Running) {
await c.stopContainer(created.Id, 0).catch(() => {});
return { ok: false, output: "timed out (15 s)" };
}
return { ok: st?.ExitCode === 0 && lines.some((l) => l.includes("KANAME-OK")), output: lines.slice(-6).join("\n") };
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
}
async function codingSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
if (!o.docker || !o.sandboxImage) return { section: "coding", passed: 0, total: 0, unsupported: "no Docker access for the code sandbox" };
let passed = 0;
const all = EVAL_SET.coding.items;
for (const item of all) {
if (o.signal.aborted) break;
let pass = false;
let detail: string;
try {
const m = await chat(t, [{ role: "user", content: `${EVAL_SET.coding.instructions}\n\n${item.prompt}` }], { max_tokens: 1024 }, o.signal);
const code = extractCode(m.content ?? "");
if (!code) detail = "no code block in the answer";
else {
const r = await runPython(o.docker, o.sandboxImage, testProgram(code, item.tests), o.signal);
pass = r.ok;
detail = r.ok ? "tests pass" : `tests fail: ${r.output.split("\n").slice(-2).join(" ").slice(0, 200)}`;
}
} catch (err) {
if (o.signal.aborted) break;
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
}
if (pass) passed++;
items.push({ section: "coding", id: item.id, pass, detail });
o.log(`coding ${item.id}: ${pass ? "pass" : `fail (${detail})`}`);
}
return { section: "coding", passed, total: all.length };
}
/** Characters per token of the filler text, by the server's own tokenizer (4 if it can't tell). */
async function charsPerToken(t: EvalTarget, signal: AbortSignal): Promise<number> {
const sample = EVAL_SET.retrieval.filler.join(" ");
try {
const r =
t.engine === "llama.cpp"
? await post<{ tokens?: unknown[] }>(t, "/tokenize", { content: sample }, signal, 30_000)
: await post<{ count?: number; tokens?: unknown[] }>(t, "/tokenize", { model: t.model, prompt: sample }, signal, 30_000);
const n = (r as { count?: number }).count ?? r.tokens?.length ?? 0;
return n > 0 ? sample.length / n : 4;
} catch {
return 4;
}
}
async function retrievalSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
if (!t.contextTokens) return { section: "retrieval", passed: 0, total: 0, unsupported: "the context length is unknown" };
const cases = retrievalCases(t.contextTokens);
if (cases.length === 0) return { section: "retrieval", passed: 0, total: 0, unsupported: `context of ${t.contextTokens} tokens is too short` };
const cpt = await charsPerToken(t, o.signal);
let passed = 0;
for (const c of cases) {
if (o.signal.aborted) break;
let pass = false;
let detail: string;
try {
const m = await chat(t, [{ role: "user", content: buildHaystack(c, cpt) }], { max_tokens: 32 }, o.signal, 900_000);
({ pass, detail } = scoreNeedle(m.content ?? "", c));
} catch (err) {
if (o.signal.aborted) break;
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
}
if (pass) passed++;
items.push({ section: "retrieval", id: c.id, pass, detail });
o.log(`retrieval ${c.id}: ${pass ? "pass" : `fail (${detail})`}`);
}
return { section: "retrieval", passed, total: cases.length };
}
const RUNNERS: Record<QualitySection, (t: EvalTarget, o: EvalOptions, items: Item[]) => Promise<Omit<Section, "score" | "seconds">>> = {
tools: toolsSection,
coding: codingSection,
retrieval: retrievalSection,
};
/** The whole eval (or the chosen sections), in order; stops early when the signal aborts. */
export async function runQualityEval(t: EvalTarget, o: EvalOptions): Promise<QualityResult> {
const items: Item[] = [];
const sections: Section[] = [];
for (const s of o.sections) {
if (o.signal.aborted) break;
const t0 = Date.now();
o.log(`${s}: starting`);
const r = await RUNNERS[s](t, o, items);
sections.push({ ...r, score: null, seconds: Math.round((Date.now() - t0) / 1000) });
}
return {
evalSet: EVAL_SET_VERSION,
...summarize(sections),
items,
config: { temperature: TEMPERATURE, seed: EVAL_SEED, thinking: THINKING, contextTokens: t.contextTokens },
};
}
+32 -7
View File
@@ -51,20 +51,21 @@ async function advance(sweep: Sweep): Promise<void> {
const timedOut = overTime(sweep.startedAt, sweep.timeLimitS);
if (sweep.cancelRequestedAt || timedOut) {
for (const v of variants) {
if (v.state === "benchmarking" && v.runId) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, v.runId));
if (v.state === "deploying" || v.state === "benchmarking") await removeDeployment(v.deploymentId);
const open = v.state === "evaluating" ? v.evalRunId : v.state === "benchmarking" ? v.runId : null;
if (open) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, open));
if (v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating") await removeDeployment(v.deploymentId);
}
await save(sweep.id, {
state: timedOut ? "failed" : "cancelled",
...(timedOut ? { error: `Stopped: the sweep exceeded the time limit for agent sweeps (${Math.round((sweep.timeLimitS ?? 0) / 60)} min).` } : {}),
finishedAt: new Date(),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating" ? { ...v, state: "skipped" as const } : v)),
});
log.info(`sweep ${sweep.id}: ${timedOut ? "stopped at its time limit" : "cancelled"}`);
return;
}
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking");
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating");
if (i < 0) {
const ok = variants.filter((v) => v.state === "done").length;
await save(sweep.id, { state: ok > 0 ? "completed" : "failed", finishedAt: new Date(), error: ok > 0 ? null : "No variant could be benchmarked." });
@@ -127,14 +128,38 @@ async function advance(sweep: Sweep): Promise<void> {
return;
}
// benchmarking
const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.runId) }) : null;
// benchmarking, then (sweeps with quality) evaluating
const runId = v.state === "evaluating" ? v.evalRunId : v.runId;
const run = runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, runId) }) : null;
if (!run) {
await put(i, { state: "failed", error: "The variant's run disappeared." });
return removeDeployment(v.deploymentId);
}
if (run.state === "queued" || run.state === "running") return;
await put(i, run.state === "completed" ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
if (run.state === "completed" && v.state === "benchmarking" && sweep.settings.quality) {
const snap = await deploymentSnapshot(v.deploymentId!);
if (snap) {
const [ev] = await db()
.insert(benchmarkRuns)
.values({
kind: "eval",
deploymentId: snap.id,
modelId: snap.modelId,
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label} · quality`.slice(0, 120),
settings: { quick: false, passes: null, warmup: null, phases: [], evalSections: [] },
snapshot: snap.snapshot,
sweepId: sweep.id,
requestedByTokenId: sweep.requestedByTokenId,
requestedBy: sweep.requestedBy,
timeLimitS: sweep.runTimeLimitS,
})
.returning({ id: benchmarkRuns.id });
return void (await put(i, { state: "evaluating", evalRunId: ev.id }));
}
}
const ok = run.state === "completed" || (v.state === "evaluating" && !!v.runId);
// A failed eval doesn't undo the speed result; it shows on the eval run.
await put(i, ok ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
await removeDeployment(v.deploymentId);
}