From 6b67c653b53b808456e0dbf1875e9a7e1afc2787 Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Wed, 21 Oct 2026 15:24:36 +0200 Subject: [PATCH] Release 0.14.0: quality eval 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 --- CHANGELOG.md | 26 + docs/agent/SKILL-tuning.md | 31 +- docs/api.md | 27 +- drizzle/0020_quality_eval.sql | 1 + drizzle/meta/0020_snapshot.json | 2327 +++++++++++++++++ drizzle/meta/_journal.json | 7 + package-lock.json | 4 +- package.json | 2 +- .../benchmarks/[id]/benchmark-detail.tsx | 10 +- .../(app)/benchmarks/[id]/quality-report.tsx | 68 + src/app/(app)/benchmarks/benchmark-list.tsx | 6 +- src/app/(app)/benchmarks/compare/page.tsx | 23 +- .../benchmarks/sweeps/[id]/sweep-detail.tsx | 21 +- .../benchmarks/sweeps/new/sweep-form.tsx | 9 + .../(app)/deployments/[id]/benchmark-card.tsx | 42 +- src/app/api/v1/benchmarks/compare/route.ts | 4 +- src/app/api/v1/benchmarks/route.ts | 2 +- src/evals/v1/coding.json | 89 + src/evals/v1/retrieval.json | 41 + src/evals/v1/tools.json | 160 ++ src/lib/agent-runs.ts | 47 +- src/lib/api-v1-agent.test.ts | 46 + src/lib/benchmark-view.ts | 2 + src/lib/benchmarks.ts | 30 +- src/lib/db/schema.ts | 33 +- src/lib/quality-view.ts | 12 + src/lib/quality.test.ts | 135 + src/lib/quality.ts | 175 ++ src/lib/sweeps.ts | 19 +- src/worker/benchmarks.ts | 120 +- src/worker/quality.test.ts | 101 + src/worker/quality.ts | 242 ++ src/worker/sweeps.ts | 39 +- 33 files changed, 3822 insertions(+), 79 deletions(-) create mode 100644 drizzle/0020_quality_eval.sql create mode 100644 drizzle/meta/0020_snapshot.json create mode 100644 src/app/(app)/benchmarks/[id]/quality-report.tsx create mode 100644 src/evals/v1/coding.json create mode 100644 src/evals/v1/retrieval.json create mode 100644 src/evals/v1/tools.json create mode 100644 src/lib/quality-view.ts create mode 100644 src/lib/quality.test.ts create mode 100644 src/lib/quality.ts create mode 100644 src/worker/quality.test.ts create mode 100644 src/worker/quality.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b3708ee..f029a82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/agent/SKILL-tuning.md b/docs/agent/SKILL-tuning.md index 62ada44..3a266fe 100644 --- a/docs/agent/SKILL-tuning.md +++ b/docs/agent/SKILL-tuning.md @@ -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/?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": "", "label": "Q4_K_M ctx16k q8_0 KV"}' +kaname -m 960 "$KANAME_URL/api/v1/benchmarks/?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/" -d '{"options": {"cacheTyp kaname -X POST "$KANAME_URL/api/v1/deployments//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": "", "quick": true, + "baseDeploymentId": "", "quick": true, "quality": true, "params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }] }' kaname -m 960 "$KANAME_URL/api/v1/sweeps/?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 diff --git a/docs/api.md b/docs/api.md index b799b09..8c83466 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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}`, diff --git a/drizzle/0020_quality_eval.sql b/drizzle/0020_quality_eval.sql new file mode 100644 index 0000000..5c6197d --- /dev/null +++ b/drizzle/0020_quality_eval.sql @@ -0,0 +1 @@ +ALTER TABLE `benchmark_runs` ADD `quality` text; \ No newline at end of file diff --git a/drizzle/meta/0020_snapshot.json b/drizzle/meta/0020_snapshot.json new file mode 100644 index 0000000..9f24964 --- /dev/null +++ b/drizzle/meta/0020_snapshot.json @@ -0,0 +1,2327 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "6178621d-8b10-484d-aa7e-e85eaf0ecfdd", + "prevId": "b20bb7ae-f705-4f7a-a6c4-27f2ba35918c", + "tables": { + "agent_activity": { + "name": "agent_activity", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_id": { + "name": "token_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_name": { + "name": "token_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "agent_activity_token_idx": { + "name": "agent_activity_token_idx", + "columns": [ + "token_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "api_keys": { + "name": "api_keys", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "api_keys_key_unique": { + "name": "api_keys_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "api_tokens": { + "name": "api_tokens", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "api_tokens_hash_unique": { + "name": "api_tokens_hash_unique", + "columns": [ + "hash" + ], + "isUnique": true + }, + "api_tokens_name_uq": { + "name": "api_tokens_name_uq", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_logs": { + "name": "benchmark_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_logs_idx": { + "name": "benchmark_logs_idx", + "columns": [ + "run_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_publications": { + "name": "benchmark_publications", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'preview'" + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'bench.betterbench.v1'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_bytes": { + "name": "payload_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "previewed_at": { + "name": "previewed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_by": { + "name": "confirmed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_at": { + "name": "confirmed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "guid": { + "name": "guid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_publications_run_idx": { + "name": "benchmark_publications_run_idx", + "columns": [ + "run_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_runs": { + "name": "benchmark_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "deployment_id": { + "name": "deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'betterbench'" + }, + "settings": { + "name": "settings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snapshot": { + "name": "snapshot", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "has_report": { + "name": "has_report", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'run'" + }, + "deployment_b_id": { + "name": "deployment_b_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "snapshot_b": { + "name": "snapshot_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ab": { + "name": "ab", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resources": { + "name": "resources", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quality": { + "name": "quality", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sweep_id": { + "name": "sweep_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "time_limit_s": { + "name": "time_limit_s", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta": { + "name": "meta", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta_b": { + "name": "meta_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "system": { + "name": "system", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_runs_created_idx": { + "name": "benchmark_runs_created_idx", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_sweeps": { + "name": "benchmark_sweeps", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_deployment_id": { + "name": "base_deployment_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base": { + "name": "base", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "variants": { + "name": "variants", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "time_limit_s": { + "name": "time_limit_s", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_time_limit_s": { + "name": "run_time_limit_s", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "deployment_logs": { + "name": "deployment_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "deployment_id": { + "name": "deployment_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "deployment_logs_idx": { + "name": "deployment_logs_idx", + "columns": [ + "deployment_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "deployment_logs_deployment_id_deployments_id_fk": { + "name": "deployment_logs_deployment_id_deployments_id_fk", + "tableFrom": "deployment_logs", + "tableTo": "deployments", + "columnsFrom": [ + "deployment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "deployments": { + "name": "deployments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "runtime_id": { + "name": "runtime_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "cpus": { + "name": "cpus", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "memory_mb": { + "name": "memory_mb", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_port": { + "name": "host_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "desired_state": { + "name": "desired_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'stopped'" + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'stopped'" + }, + "delete_requested_at": { + "name": "delete_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container_id": { + "name": "container_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_id": { + "name": "image_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ready_at": { + "name": "ready_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stopped_at": { + "name": "stopped_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stats": { + "name": "stats", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "engine_info": { + "name": "engine_info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sweep_id": { + "name": "sweep_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "protected": { + "name": "protected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "start_requested_at": { + "name": "start_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "deployments_runtime_id_runtimes_id_fk": { + "name": "deployments_runtime_id_runtimes_id_fk", + "tableFrom": "deployments", + "tableTo": "runtimes", + "columnsFrom": [ + "runtime_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "deployments_model_id_models_id_fk": { + "name": "deployments_model_id_models_id_fk", + "tableFrom": "deployments", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_files": { + "name": "job_files", + "columns": { + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model_file_id": { + "name": "model_file_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_bytes": { + "name": "expected_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + } + }, + "indexes": {}, + "foreignKeys": { + "job_files_job_id_jobs_id_fk": { + "name": "job_files_job_id_jobs_id_fk", + "tableFrom": "job_files", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "job_files_model_file_id_model_files_id_fk": { + "name": "job_files_model_file_id_model_files_id_fk", + "tableFrom": "job_files", + "tableTo": "model_files", + "columnsFrom": [ + "model_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_files_job_id_model_file_id_pk": { + "columns": [ + "job_id", + "model_file_id" + ], + "name": "job_files_job_id_model_file_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_logs": { + "name": "job_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "job_logs_job_idx": { + "name": "job_logs_job_idx", + "columns": [ + "job_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "job_logs_job_id_jobs_id_fk": { + "name": "job_logs_job_id_jobs_id_fk", + "tableFrom": "job_logs", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "jobs": { + "name": "jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_sha": { + "name": "target_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "speed_bps": { + "name": "speed_bps", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eta_seconds": { + "name": "eta_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "jobs_state_idx": { + "name": "jobs_state_idx", + "columns": [ + "state" + ], + "isUnique": false + }, + "jobs_model_idx": { + "name": "jobs_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "jobs_model_id_models_id_fk": { + "name": "jobs_model_id_models_id_fk", + "tableFrom": "jobs", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "local_folders": { + "name": "local_folders", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_count": { + "name": "file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit": { + "name": "commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scanned_at": { + "name": "scanned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_files": { + "name": "model_files", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blob_oid": { + "name": "blob_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lfs_sha256": { + "name": "lfs_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "selected": { + "name": "selected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_files_model_path_uq": { + "name": "model_files_model_path_uq", + "columns": [ + "model_id", + "path" + ], + "isUnique": true + } + }, + "foreignKeys": { + "model_files_model_id_models_id_fk": { + "name": "model_files_model_id_models_id_fk", + "tableFrom": "model_files", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_revisions": { + "name": "model_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pinned_at": { + "name": "pinned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "model_revisions_model_idx": { + "name": "model_revisions_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_revisions_model_id_models_id_fk": { + "name": "model_revisions_model_id_models_id_fk", + "tableFrom": "model_revisions", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_tags": { + "name": "model_tags", + "columns": { + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_tags_tag_idx": { + "name": "model_tags_tag_idx", + "columns": [ + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_tags_model_id_models_id_fk": { + "name": "model_tags_model_id_models_id_fk", + "tableFrom": "model_tags", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "model_tags_tag_id_tags_id_fk": { + "name": "model_tags_tag_id_tags_id_fk", + "tableFrom": "model_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "model_tags_model_id_tag_id_pk": { + "columns": [ + "model_id", + "tag_id" + ], + "name": "model_tags_model_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "models": { + "name": "models", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_type": { + "name": "repo_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'model'" + }, + "repo_id": { + "name": "repo_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tracked_revision": { + "name": "tracked_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "pinned_sha": { + "name": "pinned_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "local_path": { + "name": "local_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "include_patterns": { + "name": "include_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "exclude_patterns": { + "name": "exclude_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "remote_sha": { + "name": "remote_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_state": { + "name": "hub_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_missing_since": { + "name": "hub_missing_since", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "update_diff": { + "name": "update_diff", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "downloaded_at": { + "name": "downloaded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_models": { + "name": "base_models", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_relation": { + "name": "base_relation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_avatar_url": { + "name": "author_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "architecture": { + "name": "architecture", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pipeline_tag": { + "name": "pipeline_tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "license": { + "name": "license", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_tags": { + "name": "hub_tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_fetched_at": { + "name": "metadata_fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "models_repo_uq": { + "name": "models_repo_uq", + "columns": [ + "repo_type", + "repo_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runtimes": { + "name": "runtimes", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "engine": { + "name": "engine", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accelerator": { + "name": "accelerator", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'cpu'" + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "extra_args": { + "name": "extra_args", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "devices": { + "name": "devices", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "shm_size_mb": { + "name": "shm_size_mb", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "numa_tuning": { + "name": "numa_tuning", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "preset": { + "name": "preset", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_state": { + "name": "image_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "image_id": { + "name": "image_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_size": { + "name": "image_size", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_created": { + "name": "image_created", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pull_requested_at": { + "name": "pull_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pull_started_at": { + "name": "pull_started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pull_progress": { + "name": "pull_progress", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pull_error": { + "name": "pull_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_checked_at": { + "name": "image_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_digest": { + "name": "image_digest", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "engine_name": { + "name": "engine_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_slug_uq": { + "name": "tags_slug_uq", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "worker_state": { + "name": "worker_state", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pid": { + "name": "pid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hf_version": { + "name": "hf_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_free_bytes": { + "name": "models_dir_free_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_total_bytes": { + "name": "models_dir_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scan_requested_at": { + "name": "scan_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "docker": { + "name": "docker", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index a7cfad2..67cebaf 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -141,6 +141,13 @@ "when": 1792587768766, "tag": "0019_agent_tuning", "breakpoints": true + }, + { + "idx": 20, + "version": "6", + "when": 1792588720328, + "tag": "0020_quality_eval", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 08c6a94..e52b96b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index e7ff743..57531ac 100644 --- a/package.json +++ b/package.json @@ -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\"", diff --git a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx index 34d29f4..d144407 100644 --- a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx +++ b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx @@ -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 }) { )}

- 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" && ( )} @@ -294,7 +296,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {

- {r.kind === "ab" ? : } + {r.kind === "ab" ? : r.kind === "eval" ? : } - {r.kind === "run" && ( + {r.kind !== "ab" && ( Settings measured diff --git a/src/app/(app)/benchmarks/[id]/quality-report.tsx b/src/app/(app)/benchmarks/[id]/quality-report.tsx new file mode 100644 index 0000000..a57b348 --- /dev/null +++ b/src/app/(app)/benchmarks/[id]/quality-report.tsx @@ -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 ( + + {running ? "The quality eval is running; results appear when it's done." : "No result."} + + ); + } + return ( + + + Quality + + 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. + + + +
+ {quality.score != null ? `${quality.score}%` : "—"} + overall (mean of the sections) +
+ + + + Section + Passed + Score + Time + + + + {quality.sections.map((s) => ( + + +
{SECTION_LABEL[s.section]}
+
{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}
+
+ {s.unsupported ? "—" : `${s.passed} / ${s.total}`} + {s.score != null ? `${s.score}%` : "—"} + {s.seconds} s +
+ ))} +
+
+
    + {quality.items.map((i) => ( +
  • + {i.pass ? : } + {i.id} + {i.detail} +
  • + ))} +
+
+
+ ); +} diff --git a/src/app/(app)/benchmarks/benchmark-list.tsx b/src/app/(app)/benchmarks/benchmark-list.tsx index e7c3b1a..43a6f00 100644 --- a/src/app/(app)/benchmarks/benchmark-list.tsx +++ b/src/app/(app)/benchmarks/benchmark-list.tsx @@ -220,7 +220,11 @@ export function BenchmarkList({
- {fmt(h.decode)} + {r.kind === "eval" ? ( + {r.quality?.score != null ? `${r.quality.score}% quality` : "–"} + ) : ( + fmt(h.decode) + )} {h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"} diff --git a/src/app/(app)/benchmarks/compare/page.tsx b/src/app/(app)/benchmarks/compare/page.tsx index 6d0500a..0e23e4c 100644 --- a/src/app/(app)/benchmarks/compare/page.tsx +++ b/src/app/(app)/benchmarks/compare/page.tsx @@ -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[ {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 ( diff --git a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx index 5f95d14..6c28e95 100644 --- a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx +++ b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx @@ -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 = { 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) => ( {v != null ? fmt(v) : "—"} ); @@ -236,6 +251,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) { ))} Decode t/s + {hasQuality && Quality} TTFT ms Prefill t/s Peak t/s @@ -269,6 +285,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) { ))} {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))} diff --git a/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx b/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx index 04f7db5..877635f 100644 --- a/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx +++ b/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx @@ -64,6 +64,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia const keys = base ? sweepKeysFor(base.engine, base.accelerator) : []; const [params, setParams] = useState([{ 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(["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 ))}
+
setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" /> diff --git a/src/app/(app)/deployments/[id]/benchmark-card.tsx b/src/app/(app)/deployments/[id]/benchmark-card.tsx index ba3df8a..a28afaf 100644 --- a/src/app/(app)/deployments/[id]/benchmark-card.tsx +++ b/src/app/(app)/deployments/[id]/benchmark-card.tsx @@ -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([...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" && ( + <> +

+ 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. +

+
+ {QUALITY_SECTIONS.map((s) => ( + + ))} +
+ setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" /> + + {!running &&

Start the deployment to evaluate it.

} + + )} + {tab === "sweep" && ( <>

@@ -231,11 +261,15 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep return ( - {r.kind === "ab" && A/B} + {r.kind !== "run" && {r.kind === "ab" ? "A/B" : "quality"}} {r.label ?? new Date(r.createdAt).toLocaleString()} - {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`} diff --git a/src/app/api/v1/benchmarks/compare/route.ts b/src/app/api/v1/benchmarks/compare/route.ts index 6c8498a..c1bcc65 100644 --- a/src/app/api/v1/benchmarks/compare/route.ts +++ b/src/app/api/v1/benchmarks/compare/route.ts @@ -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=,"); - return v1Json(await compareRuns(ids, token)); + return v1Json(await compareRuns(ids)); } catch (err) { return v1Catch(err); } diff --git a/src/app/api/v1/benchmarks/route.ts b/src/app/api/v1/benchmarks/route.ts index 00df12e..baf5557 100644 --- a/src/app/api/v1/benchmarks/route.ts +++ b/src/app/api/v1/benchmarks/route.ts @@ -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()); diff --git a/src/evals/v1/coding.json b/src/evals/v1/coding.json new file mode 100644 index 0000000..a009913 --- /dev/null +++ b/src/evals/v1/coding.json @@ -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'" + ] + } + ] +} diff --git a/src/evals/v1/retrieval.json b/src/evals/v1/retrieval.json new file mode 100644 index 0000000..0546c05 --- /dev/null +++ b/src/evals/v1/retrieval.json @@ -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." + ] +} diff --git a/src/evals/v1/tools.json b/src/evals/v1/tools.json new file mode 100644 index 0000000..dc9ef57 --- /dev/null +++ b/src/evals/v1/tools.json @@ -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*$" } } } + } + ] +} diff --git a/src/lib/agent-runs.ts b/src/lib/agent-runs.ts index 037c040..ef7f357 100644 --- a/src/lib/agent-runs.ts +++ b/src/lib/agent-runs.ts @@ -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 (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> 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> } /** 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.", }; } diff --git a/src/lib/api-v1-agent.test.ts b/src/lib/api-v1-agent.test.ts index 76a60f6..d17a93f 100644 --- a/src/lib/api-v1-agent.test.ts +++ b/src/lib/api-v1-agent.test.ts @@ -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); + }); +}); diff --git a/src/lib/benchmark-view.ts b/src/lib/benchmark-view.ts index 320c02b..0b0d799 100644 --- a/src/lib/benchmark-view.ts +++ b/src/lib/benchmark-view.ts @@ -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}`; diff --git a/src/lib/benchmarks.ts b/src/lib/benchmarks.ts index 5f355f0..7bef4c7 100644 --- a/src/lib/benchmarks.ts +++ b/src/lib/benchmarks.ts @@ -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; @@ -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, diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 99a6899..3eeca40 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -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(), ab: text("ab", { mode: "json" }).$type(), resources: text("resources", { mode: "json" }).$type(), + /** kind "eval": the quality eval's result. */ + quality: text("quality", { mode: "json" }).$type(), /** 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; 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; }; diff --git a/src/lib/quality-view.ts b/src/lib/quality-view.ts new file mode 100644 index 0000000..51060c5 --- /dev/null +++ b/src/lib/quality-view.ts @@ -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 = { tools: "Tool calling", coding: "Coding", retrieval: "Long-context retrieval" }; + +export const SECTION_HINT: Record = { + 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", +}; diff --git a/src/lib/quality.test.ts b/src/lib/quality.test.ts new file mode 100644 index 0000000..f376500 --- /dev/null +++ b/src/lib/quality.test.ts @@ -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 }; + 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 = { + "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); + }); +}); diff --git a/src/lib/quality.ts b/src/lib/quality.ts new file mode 100644 index 0000000..9644aed --- /dev/null +++ b/src/lib/quality.ts @@ -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 } }; +export type CodingItem = { id: string; prompt: string; tests: string[] }; + +export const EVAL_SET = { + version: EVAL_SET_VERSION, + tools: tools as unknown as { tools: Record }>; 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; + 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; + } 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(); + 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 { + 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"; diff --git a/src/lib/sweeps.ts b/src/lib/sweeps.ts index add153a..f2a2402 100644 --- a/src/lib/sweeps.ts +++ b/src/lib/sweeps.ts @@ -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, 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 { 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)); diff --git a/src/worker/benchmarks.ts b/src/worker/benchmarks.ts index ea71be9..10fb78b 100644 --- a/src/worker/benchmarks.ts +++ b/src/worker/benchmarks.ts @@ -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. */ diff --git a/src/worker/quality.test.ts b/src/worker/quality.test.ts new file mode 100644 index 0000000..84bdda2 --- /dev/null +++ b/src/worker/quality.test.ts @@ -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((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[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); + }); +}); diff --git a/src/worker/quality.ts b/src/worker/quality.ts new file mode 100644 index 0000000..6eed227 --- /dev/null +++ b/src/worker/quality.ts @@ -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://: */ + 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: EvalTarget, path: string, body: unknown, signal: AbortSignal, timeoutMs: number): Promise { + 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, 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> { + 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> { + 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 { + 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> { + 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 Promise>> = { + 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 { + 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 }, + }; +} diff --git a/src/worker/sweeps.ts b/src/worker/sweeps.ts index 31bad3a..ab5d8eb 100644 --- a/src/worker/sweeps.ts +++ b/src/worker/sweeps.ts @@ -51,20 +51,21 @@ async function advance(sweep: Sweep): Promise { 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 { 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); }