diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c045b9..3f7c63e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ step 1 (Hugging Face downloader) is released as a minor version. ### Added +- **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another + running deployment of the same model as B. The same prompts go to both, alternating, with greedy + decoding, until the difference is known to ±the target precision (default 1 %, at most 200 + pairs). The report shows the verdict (faster/slower/no measurable difference), the confidence + interval, both sides, what differs between them and the caveats, after launch80's rules. +- **Sweeps**: vary one or two settings of a deployment (context size, KV cache type, quant file, + threads, parallel slots, batch sizes, flash attention, prompt cache, GPU layers, CPU limit; vLLM: + dtype, max sequences, KV cache, GPU memory share), up to 16 variants. Kaname deploys each variant + in turn, benchmarks it, removes it again, and shows all of them side by side (chart and table, + best values in bold), with a link to compare the runs in detail. Compare now takes up to 16 runs. +- **Resource usage in every run**: CPU (cores, average and peak), RAM (average and peak against the + container limit) from Docker, and per GPU VRAM, utilization and power from nvidia-smi, sampled + every 2 s while the benchmark runs. Shown on the report, the A/B report and the sweep table. - **Benchmarks** (new main menu entry) with [BetterBench](https://github.com/GGZ14/BetterBench) (Apache-2.0, the benchmark behind launch80.com), built into the image (v0.6.1, archive pinned by checksum). diff --git a/drizzle/0016_ab_resources_sweeps.sql b/drizzle/0016_ab_resources_sweeps.sql new file mode 100644 index 0000000..0687052 --- /dev/null +++ b/drizzle/0016_ab_resources_sweeps.sql @@ -0,0 +1,23 @@ +CREATE TABLE `benchmark_sweeps` ( + `id` text PRIMARY KEY NOT NULL, + `label` text, + `base_deployment_id` text, + `base` text NOT NULL, + `params` text NOT NULL, + `settings` text NOT NULL, + `variants` text NOT NULL, + `state` text DEFAULT 'queued' NOT NULL, + `cancel_requested_at` integer, + `started_at` integer, + `finished_at` integer, + `error` text, + `created_at` integer NOT NULL +); +--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `kind` text DEFAULT 'run' NOT NULL;--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `deployment_b_id` text;--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `snapshot_b` text;--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `ab` text;--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `resources` text;--> statement-breakpoint +ALTER TABLE `benchmark_runs` ADD `sweep_id` text;--> statement-breakpoint +ALTER TABLE `deployments` ADD `sweep_id` text; \ No newline at end of file diff --git a/drizzle/meta/0016_snapshot.json b/drizzle/meta/0016_snapshot.json new file mode 100644 index 0000000..bbb8551 --- /dev/null +++ b/drizzle/meta/0016_snapshot.json @@ -0,0 +1,1995 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "d2161b5a-7ea4-4555-a4da-9956d3d14281", + "prevId": "b794cf33-c3fd-4dc8-9a8c-8320abc1a056", + "tables": { + "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": {} + }, + "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 + }, + "sweep_id": { + "name": "sweep_id", + "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 + }, + "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 + }, + "sweep_id": { + "name": "sweep_id", + "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": { + "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 + }, + "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 + }, + "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 + }, + "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 a0aa61f..a365fb7 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -113,6 +113,13 @@ "when": 1791657884019, "tag": "0015_benchmark_publications", "breakpoints": true + }, + { + "idx": 16, + "version": "6", + "when": 1791658947930, + "tag": "0016_ab_resources_sweeps", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/benchmarks/[id]/ab-report.tsx b/src/app/(app)/benchmarks/[id]/ab-report.tsx new file mode 100644 index 0000000..81c8e97 --- /dev/null +++ b/src/app/(app)/benchmarks/[id]/ab-report.tsx @@ -0,0 +1,185 @@ +import { TriangleAlertIcon } from "lucide-react"; +import { BenchmarkResources } from "@/components/benchmark-resources"; +import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report"; +import { CONFIG_ROWS } from "@/lib/benchmark-view"; +import type { PairedResult } from "@/lib/db/schema"; +import { cn } from "@/lib/utils"; +import type { ListRow } from "../benchmark-list"; + +const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`; + +/** The difference with its 95% interval on a %-axis: zero line, the ±target band, the interval and the point. */ +function IntervalChart({ r, target }: { r: PairedResult; target: number }) { + const reach = Math.max(Math.abs(r.ci_low_pct), Math.abs(r.ci_high_pct), target) * 1.25 || 1; + const pos = (v: number) => `${((v + reach) / (2 * reach)) * 100}%`; + const ticks = [-reach, -reach / 2, 0, reach / 2, reach].map((t) => Math.round(t * 10) / 10); + return ( +
+
+ {/* ±target band: differences inside it are smaller than the precision asked for */} +
+
+
+
+
+
+ {ticks.map((t) => ( + + {t > 0 ? "+" : ""} + {t}% + + ))} +
+

+ Dot: B's difference from A. Bar: the 95% interval. Grey band: ±{target}%, the precision asked for. B is better to the {r.higher_is_better ? "right" : "left"}. +

+
+ ); +} + +function Side({ label, name, value, unit }: { label: string; name: string; value: number; unit: string }) { + return ( +
+ {label} + + {value.toFixed(unit === "ms" ? 2 : 1)} {unit} + + + {name} + +
+ ); +} + +export function AbReport({ run }: { run: ListRow }) { + const ab = run.ab; + const a = run.snapshot; + const b = run.snapshotB; + if (!ab || !b) return null; + const d = ab.decode_tps; + const g = ab.gap_median; + const caveats = abCaveats(ab); + const rows = CONFIG_ROWS.map((row) => ({ row, va: row.value(a), vb: row.value(b) })).filter((x) => x.va != null || x.vb != null); + const differs = rows.filter((x) => x.va !== x.vb); + const same = rows.filter((x) => x.va === x.vb); + + return ( +
+
+ + BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs + +

{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}

+

{abSummaryText(ab, a.deploymentName, b.deploymentName)}

+
+ +
+
+ Decode throughput + {abHeadline(d)} + + {sign(d.pct_diff)} · 95% CI {sign(d.ci_low_pct)} to {sign(d.ci_high_pct)} · {d.significant ? "significant" : "within noise"} + + +
+
+ {g.batched ? "Stream-update gap" : "Token-to-token smoothness"} + {abHeadline(g)} + + {sign(g.pct_diff)} · 95% CI {sign(g.ci_low_pct)} to {sign(g.ci_high_pct)} · lower is better + + +
+
+ +
+ + +
+ Pairs + {ab.pairs} + + ±{halfWidth(d).toFixed(2)}% reached · target ±{ab.target_mde_pct}% + +
+
+ Paired CV + {(ab.paired_cv * 100).toFixed(2)}% + ~{ab.pairs_needed_for_mde} pairs for ±{ab.target_mde_pct}% +
+
+ + {caveats.length > 0 && ( +
+ +
+ Read these first + {caveats.map((x) => ( +

+ {x} +

+ ))} +
+
+ )} + +
+

What differs

+
+ + + + + + + + + {differs.length === 0 && ( + + + + )} + {differs.map(({ row, va, vb }) => ( + + + + + + ))} + +
+ A · {a.deploymentName}B · {b.deploymentName}
+ Same settings on both sides (a null A/B: it shows how much noise the setup has). +
{row.label}{va ?? default}{vb ?? default}
+
+ {same.length > 0 &&

Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.

} +
+ + {run.resources && ( +
+

Resources

+ +
+ )} + +
+

Method

+
+ {abMethod(ab).map((p) => ( +

{p}

+ ))} +
+
+ +
+ Generated by Kaname from a BetterBench {ab.betterbenchVersion} paired A/B{ab.corpusVersion ? ` on corpus v${ab.corpusVersion}` : ""}. Every figure is BetterBench's own. +
+
+ ); +} diff --git a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx index 001232c..653e86a 100644 --- a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx +++ b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx @@ -1,6 +1,13 @@ "use client"; -import { DownloadIcon, ExternalLinkIcon, RotateCcwIcon, SquareIcon, Trash2Icon, TriangleAlertIcon } from "lucide-react"; +import { + DownloadIcon, + ExternalLinkIcon, + RotateCcwIcon, + SquareIcon, + Trash2Icon, + TriangleAlertIcon, +} from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; @@ -27,15 +34,23 @@ import { reportSummary, weightsLabel } from "@/lib/benchmark-report"; import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view"; import type { ListRow } from "../benchmark-list"; import { cancelBenchmark, deleteBenchmark, renameBenchmark } from "../actions"; +import { AbReport } from "./ab-report"; import { BenchmarkReport } from "./benchmark-report"; import { PublishCard } from "./publish-card"; function duration(a: string | null, b: string | null, now: number) { if (!a) return null; - const s = Math.max(0, ((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000); + const s = Math.max( + 0, + ((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000, + ); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); - return h ? `${h} h ${m} min` : m ? `${m} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`; + return h + ? `${h} h ${m} min` + : m + ? `${m} min ${Math.round(s % 60)} s` + : `${Math.round(s)} s`; } export function BenchmarkDetail({ initial }: { initial: ListRow }) { @@ -49,7 +64,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) { if (!active) return; const t = setInterval(async () => { setNow(Date.now()); - const res = await fetch(`/api/benchmarks/${r.id}`, { cache: "no-store" }).catch(() => null); + const res = await fetch(`/api/benchmarks/${r.id}`, { + cache: "no-store", + }).catch(() => null); if (res?.ok) setR(await res.json()); }, 2_000); return () => clearInterval(t); @@ -60,10 +77,18 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) { const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ deploymentId: r.deploymentId, label: r.label, ...r.settings }), + body: JSON.stringify({ + deploymentId: r.deploymentId, + deploymentBId: r.kind === "ab" ? r.deploymentBId : null, + label: r.label, + ...r.settings, + }), }); const json = await res.json().catch(() => ({})); - if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`); + if (!res.ok) + return toast.error( + json.error?.message ?? `Could not start (${res.status})`, + ); router.push(`/benchmarks/${json.id}`); } @@ -77,12 +102,28 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
-

{r.label ?? s.deploymentName}

- +

+ {r.label ?? + (r.kind === "ab" + ? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}` + : s.deploymentName)} +

+ {r.kind === "ab" && ( + + A/B + + )} +

{r.deploymentId ? ( - + {s.deploymentName} ) : ( @@ -97,33 +138,85 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) { s.repoId )}{" "} · {s.runtimeName} + {r.kind === "ab" && r.snapshotB && ( + <> + {" "} + · B:{" "} + {r.deploymentBId ? ( + + {r.snapshotB.deploymentName} + + ) : ( + r.snapshotB.deploymentName + )} + + )} + {r.sweepId && ( + <> + {" "} + ·{" "} + + part of a sweep + + + )}

- BetterBench · {describeSettings(r.settings)} · created - {took && ` · ${r.state === "running" ? "running for" : "took"} ${took}`} + BetterBench ·{" "} + {r.kind === "ab" + ? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs` + : describeSettings(r.settings)}{" "} + · created + {took && + ` · ${r.state === "running" ? "running for" : "took"} ${took}`}

{r.hasReport && ( - + Full report )} {r.state === "completed" && ( - + - results.json + {r.kind === "ab" ? "ab.json" : "results.json"} )} {active ? ( - ) : ( - r.deploymentId && ( - @@ -131,7 +224,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) { )} } + render={ +
diff --git a/src/app/(app)/benchmarks/[id]/benchmark-report.tsx b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx index 2c948cb..b318b81 100644 --- a/src/app/(app)/benchmarks/[id]/benchmark-report.tsx +++ b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx @@ -2,6 +2,7 @@ import { TriangleAlertIcon } from "lucide-react"; import { BarChart } from "@/components/bar-chart"; +import { BenchmarkResources } from "@/components/benchmark-resources"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report"; import { configChips } from "@/lib/benchmark-view"; @@ -199,6 +200,12 @@ export function BenchmarkReport({ run }: { run: ListRow }) { )} + {run.resources && ( +
+ +
+ )} +
{sum.single.length > 0 && (
diff --git a/src/app/(app)/benchmarks/benchmark-list.tsx b/src/app/(app)/benchmarks/benchmark-list.tsx index 59b14f7..c26216a 100644 --- a/src/app/(app)/benchmarks/benchmark-list.tsx +++ b/src/app/(app)/benchmarks/benchmark-list.tsx @@ -20,7 +20,7 @@ export type ListRow = Omit (v == null ? "–" : v.toFixed(digits)); /** All runs with their headline numbers; polls while something is queued or running. */ diff --git a/src/app/(app)/benchmarks/compare/page.tsx b/src/app/(app)/benchmarks/compare/page.tsx index 84ee800..2c9452c 100644 --- a/src/app/(app)/benchmarks/compare/page.tsx +++ b/src/app/(app)/benchmarks/compare/page.tsx @@ -39,7 +39,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar String(ids ?? "") .split(",") .filter(Boolean) - .slice(0, 6), + .slice(0, 16), ); if (runs.length < 2) { return ( diff --git a/src/app/(app)/benchmarks/sweeps/[id]/page.tsx b/src/app/(app)/benchmarks/sweeps/[id]/page.tsx new file mode 100644 index 0000000..816fb4e --- /dev/null +++ b/src/app/(app)/benchmarks/sweeps/[id]/page.tsx @@ -0,0 +1,13 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getSweep } from "@/lib/sweeps"; +import { SweepDetail } from "./sweep-detail"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Sweep · Benchmarks" }; + +export default async function SweepPage({ params }: PageProps<"/benchmarks/sweeps/[id]">) { + const data = await getSweep((await params).id); + if (!data) notFound(); + return ; +} diff --git a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx new file mode 100644 index 0000000..172a7aa --- /dev/null +++ b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx @@ -0,0 +1,234 @@ +"use client"; + +import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { toast } from "sonner"; +import { BarChart } from "@/components/bar-chart"; +import { BenchmarkStateBadge } from "@/components/benchmark-state"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { describeSettings, headline } from "@/lib/benchmark-view"; +import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, 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 }; +export type SweepData = { sweep: Sweep; runs: Run[] }; + +const VARIANT_STATE: Record = { + pending: "Waiting", + deploying: "Deploying", + benchmarking: "Benchmarking", + done: "Done", + failed: "Failed", + skipped: "Skipped", +}; + +type Row = { + v: SweepVariant; + run: Run | null; + decode: number | null; + ttft: number | null; + prefill: number | null; + peak: number | null; + cpu: number | null; + ram: number | null; + vram: 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 h = headline(run?.summary ?? null); + const c = run?.resources?.containers.find((x) => x.side === "a"); + const g = run?.resources?.gpus ?? []; + return { + v, + run, + decode: h.decode, + ttft: h.ttftMs, + prefill: h.prefill?.tps ?? null, + peak: h.peak?.tps ?? null, + cpu: c?.cpuAvg ?? null, + ram: c?.memPeakBytes ?? null, + vram: g.length ? g.reduce((s, x) => s + x.vramPeakMb, 0) : null, + }; + }); +} + +/** Best value per column (higher or lower is better), to set it in bold. */ +function best(rows: Row[], key: keyof Row, higher: boolean): number | null { + const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number"); + if (vals.length < 2) return null; + return higher ? Math.max(...vals) : Math.min(...vals); +} + +export function SweepDetail({ initial }: { initial: SweepData }) { + const router = useRouter(); + const [data, setData] = useState(initial); + const [busy, setBusy] = useState(false); + const { sweep } = data; + const active = sweep.state === "queued" || sweep.state === "running"; + + useEffect(() => { + if (!active) return; + const t = setInterval(async () => { + const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null); + if (res?.ok) setData(await res.json()); + }, 3_000); + return () => clearInterval(t); + }, [sweep.id, active]); + + async function act(path: string, method: string, done: () => void) { + setBusy(true); + try { + const res = await fetch(path, { method }); + const json = await res.json().catch(() => ({})); + if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`); + done(); + } finally { + setBusy(false); + } + } + + const rows = rowsOf(data); + const finished = rows.filter((r) => r.decode != null); + const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed")); + const bestOf = { + decode: best(rows, "decode", true), + ttft: best(rows, "ttft", false), + prefill: best(rows, "prefill", true), + peak: best(rows, "peak", true), + cpu: best(rows, "cpu", false), + ram: best(rows, "ram", false), + vram: best(rows, "vram", false), + }; + const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => ( + {v != null ? fmt(v) : "—"} + ); + const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length; + + return ( +
+
+
+

+ + {sweep.label ?? `Sweep of ${sweep.base.name}`} +

+

+ {sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "} + {sweep.baseDeploymentId ? ( + + {sweep.base.name} + + ) : ( + sweep.base.name + )} +

+
+
+ + {runIds.length >= 2 && ( + + + Compare in detail + + )} + {active ? ( + + ) : ( + + )} +
+
+ + {active && ( +

+ {done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another. +

+ )} + {sweep.error &&

{sweep.error}

} + + {finished.length > 0 && ( + + + Generation speed by variant + Single-stream decode, tokens per second (BetterBench combined score). Higher is better. + + + ({ + label: r.v.label, + value: r.decode, + valueLabel: r.decode!.toFixed(1), + details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean), + }))} + /> + + + )} + + + + Variants + Best value per column in bold. Resource figures are averages/peaks over the run. + + + + + + + + + + + + + + + + + + {rows.map((r) => ( + + + + {cell(r.decode, bestOf.decode, (x) => x.toFixed(1))} + {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))} + {cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))} + {cell(r.ram, bestOf.ram, (x) => formatBytes(x))} + {cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)} + + ))} + +
VariantStateDecode t/sTTFT msPrefill t/sPeak t/sCPU coresPeak RAMPeak VRAM
+ {r.v.runId ? ( + + {r.v.label} + + ) : ( + r.v.label + )} + + {VARIANT_STATE[r.v.state]} + {r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""} + {(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""} +
+
+
+
+ ); +} diff --git a/src/app/(app)/benchmarks/sweeps/new/page.tsx b/src/app/(app)/benchmarks/sweeps/new/page.tsx new file mode 100644 index 0000000..38843c9 --- /dev/null +++ b/src/app/(app)/benchmarks/sweeps/new/page.tsx @@ -0,0 +1,36 @@ +import type { Metadata } from "next"; +import { listDeployableModels, listDeployments } from "@/lib/deployments"; +import { SweepForm, type SweepBase } from "./sweep-form"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "New sweep" }; + +export default async function NewSweepPage({ searchParams }: PageProps<"/benchmarks/sweeps/new">) { + const { deployment } = await searchParams; + const [deployments, models] = await Promise.all([listDeployments(), listDeployableModels()]); + const bases: SweepBase[] = deployments + .filter((d) => !d.sweepId) + .map((d) => ({ + id: d.id, + name: d.name, + engine: d.engine, + accelerator: d.accelerator, + repoId: d.repoId, + options: d.options, + cpus: d.cpus, + memoryMb: d.memoryMb, + ggufFiles: models.find((m) => m.id === d.modelId)?.candidates.gguf.map((g) => g.path) ?? [], + })); + return ( +
+
+

New sweep

+

+ Vary one or two settings of a deployment. Kaname deploys each variant in turn, benchmarks it with BetterBench, removes it again and compares all of them, + including the resources each one used. +

+
+ +
+ ); +} diff --git a/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx b/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx new file mode 100644 index 0000000..04f7db5 --- /dev/null +++ b/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx @@ -0,0 +1,248 @@ +"use client"; + +import { Grid3x3Icon, PlusIcon, XIcon } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { NativeSelect } from "@/components/ui/native-select"; +import type { BenchmarkPhase, DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema"; +import { quantGroup } from "@/lib/selection"; +import { expandSweep, MAX_SWEEP_VARIANTS, splitValues, SweepError, sweepKeysFor } from "@/lib/sweep"; + +export type SweepBase = { + id: string; + name: string; + engine: RuntimeEngine; + accelerator: RuntimeAccelerator; + repoId: string; + options: DeploymentOptions; + cpus: number | null; + memoryMb: number | null; + ggufFiles: string[]; +}; + +const PHASES: { id: BenchmarkPhase; label: string }[] = [ + { id: "decode", label: "Generation" }, + { id: "prefill", label: "Prompt processing" }, + { id: "concurrency", label: "Parallel requests" }, +]; + +/** The base's current value of a sweep key, shown as a hint. */ +function currentValue(base: SweepBase, key: string): string { + const o = base.options; + const v: Record = { + contextSize: o.contextSize, + modelFile: o.modelFile, + kvCache: o.cacheTypeK ?? "f16", + threads: o.threads ?? "auto", + parallel: o.parallel ?? "auto", + batchSize: o.batchSize ?? "default", + ubatchSize: o.ubatchSize ?? "default", + flashAttn: o.flashAttn ?? "auto", + cacheRamMb: o.cacheRamMb ?? "8192 (default)", + gpuLayers: o.gpuLayers ?? "auto", + dtype: o.dtype ?? "runtime default", + maxNumSeqs: o.maxNumSeqs ?? "default", + kvCacheGb: o.kvCacheGb ?? "runtime default", + gpuMemoryUtilization: o.gpuMemoryUtilization ?? "0.9", + cpus: base.cpus ?? "no limit", + }; + return String(v[key] ?? ""); +} + +type Param = { key: string; text: string; files: string[] }; + +export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initialBaseId?: string }) { + const router = useRouter(); + const [baseId, setBaseId] = useState(initialBaseId && bases.some((b) => b.id === initialBaseId) ? initialBaseId : (bases[0]?.id ?? "")); + const base = bases.find((b) => b.id === baseId) ?? null; + const keys = base ? sweepKeysFor(base.engine, base.accelerator) : []; + const [params, setParams] = useState([{ key: "contextSize", text: "", files: [] }]); + const [label, setLabel] = useState(""); + const [mode, setMode] = useState("quick"); + const [passes, setPasses] = useState("10"); + const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]); + const [busy, setBusy] = useState(false); + + const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text)); + let preview: { variants: ReturnType | null; error: string | null } = { variants: null, error: null }; + if (base) { + try { + preview = { variants: expandSweep(params.map((p) => ({ key: p.key, values: values(p) })), base.engine, base.accelerator, { modelFiles: base.ggufFiles }), error: null }; + } catch (err) { + preview = { variants: null, error: err instanceof SweepError ? err.message : String(err) }; + } + } + + const setParam = (i: number, patch: Partial) => setParams((ps) => ps.map((p, j) => (j === i ? { ...p, ...patch } : p))); + + async function submit() { + if (!base || !preview.variants) return; + setBusy(true); + try { + const res = await fetch("/api/sweeps", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + baseDeploymentId: base.id, + label: label.trim() || null, + params: params.map((p) => ({ key: p.key, values: values(p) })), + quick: mode === "quick", + passes: mode === "custom" ? Number(passes) || 10 : null, + phases: phases.length === PHASES.length ? [] : phases, + }), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`); + router.push(`/benchmarks/sweeps/${json.id}`); + } finally { + setBusy(false); + } + } + + if (bases.length === 0) return

Create a deployment first; a sweep varies its settings.

; + + return ( +
+
+ + + Base deployment + Every variant starts from its settings. It doesn't need to be running. + + + setBaseId(e.target.value)} aria-label="Base deployment"> + {bases.map((b) => ( + + ))} + + + + + + + What to vary + One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}). + + + {base && + params.map((p, i) => { + const def = keys.find((k) => k.key === p.key); + return ( +
+
+ setParam(i, { key: e.target.value, text: "", files: [] })} aria-label={`Setting ${i + 1}`}> + {keys + .filter((k) => k.key === p.key || !params.some((q) => q.key === k.key)) + .map((k) => ( + + ))} + + {params.length > 1 && ( + + )} +
+ {p.key === "modelFile" ? ( +
+ {base.ggufFiles.map((f) => ( + + ))} + {base.ggufFiles.length < 2 &&

Only one GGUF file is downloaded; download more quants to compare them.

} +
+ ) : ( + setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" /> + )} +

Base value: {currentValue(base, p.key)}

+
+ ); + })} + {params.length < 2 && base && ( + + )} +
+
+ + + + Benchmark per variant + + +
+ setMode(e.target.value)} aria-label="Run length"> + + + + + {mode === "custom" && setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />} +
+
+ {PHASES.map((p) => ( + + ))} +
+
+ + setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" /> +
+
+
+
+ + + + + + {preview.variants ? `${preview.variants.length} variants` : "Variants"} + + + + {preview.error ? ( +

{preview.error}

+ ) : ( +
    + {preview.variants?.map((v) => ( +
  1. + {v.index + 1} + {v.label} +
  2. + ))} +
+ )} +

+ Variants run one after another, each in its own temporary deployment{base?.memoryMb ? " (memory limit: the base's, raised where a variant needs more)" : ""}. + {mode !== "quick" && " Full runs on a CPU can take hours per variant."} +

+ +
+
+
+ ); +} diff --git a/src/app/(app)/deployments/[id]/benchmark-card.tsx b/src/app/(app)/deployments/[id]/benchmark-card.tsx index 36c3d8a..37594c6 100644 --- a/src/app/(app)/deployments/[id]/benchmark-card.tsx +++ b/src/app/(app)/deployments/[id]/benchmark-card.tsx @@ -1,18 +1,20 @@ "use client"; -import { GaugeIcon } from "lucide-react"; +import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { toast } from "sonner"; import { BenchmarkStateBadge } from "@/components/benchmark-state"; -import { Button } from "@/components/ui/button"; +import { Button, buttonVariants } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; 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 { cn } from "@/lib/utils"; import type { ListRow } from "../../benchmarks/benchmark-list"; const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [ @@ -21,15 +23,23 @@ const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [ { id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" }, ]; -/** Start a BetterBench run against this deployment and list its recent runs. */ -export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId: string; running: boolean; initial: ListRow[] }) { +type Mode = "run" | "ab" | "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. */ +export function BenchmarkCard({ deploymentId, modelId, running, initial }: { deploymentId: string; modelId: string; running: boolean; initial: ListRow[] }) { const router = useRouter(); + const [tab, setTab] = useState("run"); const [mode, setMode] = useState("quick"); const [passes, setPasses] = useState("10"); const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]); const [label, setLabel] = useState(""); const [busy, setBusy] = useState(false); const [runs, setRuns] = useState(initial); + const [peers, setPeers] = useState(null); + const [peerId, setPeerId] = useState(""); + const [mde, setMde] = useState("1"); + const [maxPairs, setMaxPairs] = useState("200"); const active = runs.some((r) => r.state === "queued" || r.state === "running"); useEffect(() => { @@ -43,21 +53,27 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId return () => clearInterval(t); }, [deploymentId, active]); - async function start() { + // Other deployments of the same model (A/B partners). + useEffect(() => { + if (tab !== "ab") return; + let stop = false; + void fetch("/api/deployments", { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : [])) + .then((rows: Peer[]) => { + if (stop) return; + const list = rows.filter((p) => p.modelId === modelId && p.id !== deploymentId); + setPeers(list); + setPeerId((cur) => cur || list.find((p) => p.state === "running")?.id || ""); + }); + return () => { + stop = true; + }; + }, [tab, modelId, deploymentId]); + + async function start(body: Record) { setBusy(true); try { - const res = await fetch("/api/benchmarks", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - deploymentId, - label: label.trim() || null, - quick: mode === "quick", - passes: mode === "custom" ? Number(passes) || 10 : null, - // All three selected means "everything" (BetterBench's default). - phases: phases.length === PHASES.length ? [] : phases, - }), - }); + const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, ...body }) }); const json = await res.json().catch(() => ({})); if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`); router.push(`/benchmarks/${json.id}`); @@ -66,6 +82,13 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId } } + const peer = peers?.find((p) => p.id === peerId); + const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [ + { id: "run", label: "Run", icon: GaugeIcon }, + { id: "ab", label: "A/B", icon: GitCompareArrowsIcon }, + { id: "sweep", label: "Sweep", icon: Grid3x3Icon }, + ]; + return ( @@ -75,39 +98,128 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId -
- setMode(e.target.value)} aria-label="Run length"> - - - - - {mode === "custom" && ( - setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" /> - )} -
-
- {PHASES.map((p) => ( - +
+ {TABS.map((t) => ( + ))}
- setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" /> - -

- {running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."} -

+ + {tab === "run" && ( + <> +
+ setMode(e.target.value)} aria-label="Run length"> + + + + + {mode === "custom" && ( + setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" /> + )} +
+
+ {PHASES.map((p) => ( + + ))} +
+ setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" /> + +

+ {running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."} +

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

+ Paired A/B: the same prompts go to this deployment (A) and another one of the same model (B), alternating, until the difference is known to ±the target. Both + must be running and fit in memory together. +

+ {peers === null ? ( +

Loading…

+ ) : peers.length === 0 ? ( +

+ No other deployment of this model. Create one with the setting you want to compare (e.g. a different KV cache type), or run a sweep. +

+ ) : ( + <> + setPeerId(e.target.value)} aria-label="Deployment B"> + + {peers.map((p) => ( + + ))} + + {peer && peer.state !== "running" && ( +

+ {peer.name} isn't running.{" "} + + Start it + {" "} + first. +

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

Start this deployment (A) first.

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

+ Vary one or two settings (context size, KV cache type, threads, quant, GPU layers, …). Kaname deploys each variant in turn, benchmarks it, removes it again, and + compares all of them. This deployment doesn't need to run. +

+ + + Set up a sweep + + + )} {runs.length > 0 && (
@@ -115,9 +227,12 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId const h = headline(r.summary); return ( - {r.label ?? new Date(r.createdAt).toLocaleString()} + + {r.kind === "ab" && A/B} + {r.label ?? new Date(r.createdAt).toLocaleString()} + - {h.decode != null && `${h.decode.toFixed(1)} t/s`} + {r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`} diff --git a/src/app/(app)/deployments/[id]/deployment-detail.tsx b/src/app/(app)/deployments/[id]/deployment-detail.tsx index 58b4dd0..46cfc85 100644 --- a/src/app/(app)/deployments/[id]/deployment-detail.tsx +++ b/src/app/(app)/deployments/[id]/deployment-detail.tsx @@ -194,7 +194,7 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
- + Endpoint diff --git a/src/app/api/benchmarks/[id]/results/route.ts b/src/app/api/benchmarks/[id]/results/route.ts index ab85bc5..324af73 100644 --- a/src/app/api/benchmarks/[id]/results/route.ts +++ b/src/app/api/benchmarks/[id]/results/route.ts @@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { withAuth } from "@/lib/api-auth"; import { apiError } from "@/lib/api-errors"; -import { RESULTS_FILE, runDir } from "@/lib/benchmark-paths"; +import { AB_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths"; import { getBenchmark } from "@/lib/benchmarks"; export const dynamic = "force-dynamic"; @@ -11,15 +11,19 @@ export const dynamic = "force-dynamic"; export const GET = withAuth>(async (_req, { params }) => { const run = await getBenchmark((await params).id); if (!run) return apiError(404, "not_found", "Benchmark not found."); - const raw = await readFile(join(runDir(run.id), RESULTS_FILE), "utf8").catch(() => null); + const ab = run.kind === "ab"; + const raw = await readFile(join(runDir(run.id), ab ? AB_FILE : RESULTS_FILE), "utf8").catch(() => null); if (!raw) return apiError(404, "not_found", "This run has no results file."); // Like launch80's L80 CLI: the endpoint URL and host name never leave the machine. - const data = JSON.parse(raw) as { env?: Record }; + const data = JSON.parse(raw) as { env?: Record; endpoint_a?: unknown; endpoint_b?: unknown }; if (data.env) { delete data.env.endpoint; + delete data.env.endpoint_b; delete data.env.host; } + delete data.endpoint_a; + delete data.endpoint_b; const json = JSON.stringify(data, null, 2); - const name = `betterbench-${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`; + const name = `betterbench-${ab ? "ab-" : ""}${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`; return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } }); }); diff --git a/src/app/api/sweeps/[id]/cancel/route.ts b/src/app/api/sweeps/[id]/cancel/route.ts new file mode 100644 index 0000000..3b6a402 --- /dev/null +++ b/src/app/api/sweeps/[id]/cancel/route.ts @@ -0,0 +1,14 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { cancelSweep, SweepRequestError } from "@/lib/sweeps"; + +export const POST = withAuth>(async (_req, { params }) => { + try { + await cancelSweep((await params).id); + return new NextResponse(null, { status: 202 }); + } catch (err) { + if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/sweeps/[id]/route.ts b/src/app/api/sweeps/[id]/route.ts new file mode 100644 index 0000000..54478ef --- /dev/null +++ b/src/app/api/sweeps/[id]/route.ts @@ -0,0 +1,21 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { deleteSweep, getSweep, SweepRequestError } from "@/lib/sweeps"; + +export const dynamic = "force-dynamic"; + +export const GET = withAuth>(async (_req, { params }) => { + const s = await getSweep((await params).id); + return s ? NextResponse.json(s) : apiError(404, "not_found", "Sweep not found."); +}); + +export const DELETE = withAuth>(async (_req, { params }) => { + try { + await deleteSweep((await params).id); + return new NextResponse(null, { status: 204 }); + } catch (err) { + if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/sweeps/route.ts b/src/app/api/sweeps/route.ts new file mode 100644 index 0000000..ca9c809 --- /dev/null +++ b/src/app/api/sweeps/route.ts @@ -0,0 +1,18 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { createSweep, listSweeps, SweepBody, SweepRequestError } from "@/lib/sweeps"; + +export const dynamic = "force-dynamic"; + +export const GET = withAuth(async () => NextResponse.json(await listSweeps())); + +/** Queue a sweep: one or two settings varied over a base deployment, one benchmark per variant. */ +export const POST = withAuth(async (req) => { + try { + return NextResponse.json(await createSweep(SweepBody.parse(await req.json())), { status: 201 }); + } catch (err) { + if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/components/benchmark-resources.tsx b/src/components/benchmark-resources.tsx new file mode 100644 index 0000000..0bef426 --- /dev/null +++ b/src/components/benchmark-resources.tsx @@ -0,0 +1,58 @@ +import type { ResourceStats } from "@/lib/db/schema"; +import { formatBytes } from "@/lib/format"; + +const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1)); + +function Cell({ label, value, note }: { label: string; value: string; note?: string }) { + return ( +
+ {label} + {value} + {note && {note}} +
+ ); +} + +/** Resource use sampled during a run: per deployment (A/B: both sides) and per GPU. */ +export function BenchmarkResources({ stats, names }: { stats: ResourceStats; names?: { a: string; b?: string } }) { + if (stats.samples === 0 && stats.gpus.length === 0) return

No resource samples were recorded.

; + const multi = stats.containers.length > 1; + return ( +
+ {stats.containers.map((c) => ( +
+ {multi && {c.side === "a" ? `A · ${names?.a ?? ""}` : `B · ${names?.b ?? ""}`}} +
+ + + {c.memPeakBytes != null && c.memLimitBytes ? ( + + ) : ( + + )} +
+
+ ))} + {stats.gpus.map((g) => ( +
+ + GPU {g.index} · {g.name} + +
+ + + +
+
+ ))} +

+ Sampled every ~2 s over {stats.seconds} s ({stats.samples} samples). RAM is the container's usage without page cache, like docker stats; GPU + figures are for the whole GPU, so other work on it counts too. +

+
+ ); +} diff --git a/src/lib/ab-report.test.ts b/src/lib/ab-report.test.ts new file mode 100644 index 0000000..7ef7f9c --- /dev/null +++ b/src/lib/ab-report.test.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "./ab-report"; +import type { AbSummary, PairedResult } from "./db/schema"; + +const r = (p: Partial): PairedResult => ({ + metric: "decode_tps", + n_pairs: 12, + mean_a: 115, + mean_b: 120, + mean_diff: 5, + pct_diff: 4.37, + ci_low_pct: 3.24, + ci_high_pct: 5.5, + conf: 0.95, + significant: true, + verdict: "B is 4.37% faster — SIGNIFICANT", + higher_is_better: true, + ...p, +}); + +const ab: AbSummary = { + pairs: 12, + decode_tps: r({}), + gap_median: { ...r({ metric: "update_gap_median_ms", pct_diff: -4.6, ci_low_pct: -5.8, ci_high_pct: -3.4, higher_is_better: false }), batched: false }, + paired_cv: 0.0178, + pairs_needed_for_mde: 7, + target_mde_pct: 2, + conf: 0.95, + maxPairs: 24, + raw: { a_tps: [], b_tps: [] }, + betterbenchVersion: "0.6.1", + corpusVersion: "1.0", + timestamp: null, + config: { greedy: true, temperature: 0.7, warmup: 3, unique_nonce: true, ab_min_pairs: 12 }, +}; + +describe("A/B report text", () => { + it("states the result as BetterBench does", () => { + assert.equal(abHeadline(ab.decode_tps), "B is 4.37% faster"); + assert.equal(abHeadline(ab.gap_median), "B is 4.60% faster"); + assert.equal(abHeadline(r({ significant: false, pct_diff: 0.3 })), "No measurable difference"); + assert.equal(abHeadline(r({ pct_diff: -2 })), "B is 2.00% slower"); + assert.ok(Math.abs(halfWidth(ab.decode_tps) - 1.13) < 1e-9); + assert.equal(abSummaryText(ab, "4 threads", "8 threads"), "8 threads (B) against 4 threads (A), 12 interleaved pairs: decode +4.37% (95% CI +3.24% to +5.50%), significant."); + }); + + it("flags imprecise and inconclusive results", () => { + assert.deepEqual(abCaveats(ab), []); + const wide = { ...ab, pairs: 24, decode_tps: r({ ci_low_pct: -1, ci_high_pct: 5, significant: false }), pairs_needed_for_mde: 90 }; + const c = abCaveats(wide); + assert.match(c[0], /±3\.00%, wider than the 2% target: the run stopped at the 24-pair limit first\. About 90 pairs/); + assert.match(c[1], /can't be told apart/); + assert.match(abMethod(ab).join(" "), /narrower than ±2% \(after at least 12 pairs\), or after 24 pairs/); + }); +}); diff --git a/src/lib/ab-report.ts b/src/lib/ab-report.ts new file mode 100644 index 0000000..c076030 --- /dev/null +++ b/src/lib/ab-report.ts @@ -0,0 +1,43 @@ +// Text for a paired A/B report (betterbench ab). Every figure is one BetterBench reported. Pure. + +import type { AbSummary, PairedResult } from "@/lib/db/schema"; + +export const halfWidth = (r: PairedResult) => (r.ci_high_pct - r.ci_low_pct) / 2; +const pct = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`; + +/** "B is 4.37% faster" / "No measurable difference" — the headline, from BetterBench's verdict. */ +export function abHeadline(r: PairedResult): string { + if (!r.significant) return "No measurable difference"; + const better = r.higher_is_better ? r.pct_diff > 0 : r.pct_diff < 0; + return `B is ${Math.abs(r.pct_diff).toFixed(2)}% ${better ? "faster" : "slower"}`; +} + +export function abCaveats(ab: AbSummary): string[] { + const out: string[] = []; + const min = ab.config.ab_min_pairs ?? 12; + const hw = halfWidth(ab.decode_tps); + if (ab.pairs < min) out.push(`Only ${ab.pairs} pairs survived (BetterBench's minimum is ${min}); a pair counts only when both calls succeed. Treat the result as indicative.`); + if (hw > ab.target_mde_pct) { + out.push( + `The 95% interval is ±${hw.toFixed(2)}%, wider than the ${ab.target_mde_pct}% target: the run ${ab.maxPairs && ab.pairs >= ab.maxPairs ? `stopped at the ${ab.maxPairs}-pair limit` : "ended"} first. About ${ab.pairs_needed_for_mde} pairs would be needed; differences smaller than ±${hw.toFixed(1)}% can't be told apart here.`, + ); + } + if (!ab.decode_tps.significant) out.push("The interval includes zero: A and B can't be told apart at this precision. That is a result, not a failure."); + if (ab.gap_median.batched) out.push("At least one side streamed several tokens per update (speculative or batched decoding), so smoothness is compared as the stream-update gap, not per-token latency."); + return out; +} + +export function abMethod(ab: AbSummary): string[] { + const c = ab.config; + return [ + `Paired A/B with BetterBench ${ab.betterbenchVersion}${ab.corpusVersion ? `, corpus v${ab.corpusVersion}` : ""}: the same prompt goes to A and B back to back, the order alternating every pair, so drift (heat, caches, background load) hits both sides equally.`, + `${c.greedy ? "Greedy decoding (identical token counts on both sides)" : `Sampled decoding${c.temperature != null ? `, temperature ${c.temperature}` : ""}`}, ${c.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (a unique nonce per pair)"}${c.warmup != null ? `, ${c.warmup} warmup pairs` : ""}.`, + `It stops once the ${Math.round(ab.conf * 100)}% confidence interval of the decode difference is narrower than ±${ab.target_mde_pct}% (after at least ${c.ab_min_pairs ?? 12} pairs)${ab.maxPairs ? `, or after ${ab.maxPairs} pairs` : ""}. The interval is a paired t-interval on the per-pair differences; a difference is significant when it excludes zero.`, + `Decode is tokens per second per request (higher is better); smoothness is the median gap between streamed updates in ms (lower is better). Paired CV ${(ab.paired_cv * 100).toFixed(2)}%: how much the per-pair difference varies.`, + ]; +} + +export function abSummaryText(ab: AbSummary, a: string, b: string): string { + const d = ab.decode_tps; + return `${b} (B) against ${a} (A), ${ab.pairs} interleaved pairs: decode ${pct(d.pct_diff)} (95% CI ${pct(d.ci_low_pct)} to ${pct(d.ci_high_pct)}), ${d.significant ? "significant" : "within noise"}.`; +} diff --git a/src/lib/benchmark-paths.ts b/src/lib/benchmark-paths.ts index ee83783..6da749c 100644 --- a/src/lib/benchmark-paths.ts +++ b/src/lib/benchmark-paths.ts @@ -21,3 +21,4 @@ export function runDir(runId: string): string { export const RESULTS_FILE = "results.json"; export const REPORT_FILE = "results.html"; +export const AB_FILE = "ab.json"; diff --git a/src/lib/benchmark-snapshot.ts b/src/lib/benchmark-snapshot.ts new file mode 100644 index 0000000..97fee11 --- /dev/null +++ b/src/lib/benchmark-snapshot.ts @@ -0,0 +1,62 @@ +// What a benchmark run records about the deployment it measures. Shared by the web app and the worker +// (sweeps create runs there), so no "server-only" here. + +import { and, eq, isNull } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema"; + +/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */ +async function hostFacts(uuids: string[] | null, nvidia: boolean) { + const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }); + const h = ws?.docker; + const gpus = h?.gpus ?? []; + return { + gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [], + host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null }, + }; +} + +/** The deployment as it is now; null when it doesn't exist (or is being deleted). */ +export async function deploymentSnapshot(deploymentId: string): Promise<{ id: string; modelId: string; state: string; snapshot: BenchmarkSnapshot } | null> { + const [d] = await db() + .select({ + id: deployments.id, + name: deployments.name, + state: deployments.state, + options: deployments.options, + cpus: deployments.cpus, + memoryMb: deployments.memoryMb, + command: deployments.command, + imageId: deployments.imageId, + modelId: deployments.modelId, + repoId: models.repoId, + runtimeName: runtimes.name, + engine: runtimes.engine, + accelerator: runtimes.accelerator, + image: runtimes.image, + }) + .from(deployments) + .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) + .innerJoin(models, eq(models.id, deployments.modelId)) + .where(and(eq(deployments.id, deploymentId), isNull(deployments.deleteRequestedAt))); + if (!d) return null; + return { + id: d.id, + modelId: d.modelId, + state: d.state, + snapshot: { + deploymentName: d.name, + repoId: d.repoId, + runtimeName: d.runtimeName, + engine: d.engine, + accelerator: d.accelerator, + ...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")), + image: d.image, + imageId: d.imageId, + options: d.options, + cpus: d.cpus, + memoryMb: d.memoryMb, + command: [d.image, ...(d.command ?? [])].join(" "), + }, + }; +} diff --git a/src/lib/benchmarks.ts b/src/lib/benchmarks.ts index ea114e6..0b07888 100644 --- a/src/lib/benchmarks.ts +++ b/src/lib/benchmarks.ts @@ -1,10 +1,11 @@ import "server-only"; import { rm } from "node:fs/promises"; -import { and, asc, desc, eq, gt, inArray, isNull } from "drizzle-orm"; +import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm"; 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, type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema"; +import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns } from "@/lib/db/schema"; export class BenchmarkError extends Error { constructor( @@ -24,68 +25,55 @@ export const BenchmarkBody = z.object({ warmup: z.number().int().min(0).max(50).nullable().optional(), /** Empty: all phases. */ phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]), + /** A/B: the second deployment (B), the target minimum detectable effect in % and the pair ceiling. */ + deploymentBId: z.string().min(1).nullable().optional(), + mdePct: z.number().min(0.1).max(50).nullable().optional(), + maxPairs: z.number().int().min(12).max(2000).nullable().optional(), + /** Set by sweeps. */ + sweepId: z.string().nullable().optional(), }); export type BenchmarkInput = z.infer; -/** Names of the GPUs a deployment uses (all detected ones when none are picked). */ -async function hostFacts(uuids: string[] | null, nvidia: boolean) { - const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }); - const h = ws?.docker; - const gpus = h?.gpus ?? []; - return { - gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [], - host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null }, - }; +/** A running deployment as it is now: what a run measures and records. */ +async function snapshotOf(deploymentId: string, role: string) { + const d = await deploymentSnapshot(deploymentId); + if (!d) throw new BenchmarkError("not_found", `${role} not found.`, 404); + if (d.state !== "running") throw new BenchmarkError("invalid", `Start ${role.toLowerCase()} first; benchmarks run against a running server.`, 409); + return d; } -/** Queue a run against a running deployment; the worker runs one benchmark at a time. */ +/** + * Queue a run against a running deployment, or a paired A/B between two running deployments of the + * same model (BetterBench sends one model name to both). The worker runs one benchmark at a time. + */ export async function createBenchmark(input: BenchmarkInput) { - const [d] = await db() - .select({ - id: deployments.id, - name: deployments.name, - state: deployments.state, - options: deployments.options, - cpus: deployments.cpus, - memoryMb: deployments.memoryMb, - command: deployments.command, - imageId: deployments.imageId, - modelId: deployments.modelId, - repoId: models.repoId, - runtimeName: runtimes.name, - engine: runtimes.engine, - accelerator: runtimes.accelerator, - image: runtimes.image, - }) - .from(deployments) - .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) - .innerJoin(models, eq(models.id, deployments.modelId)) - .where(and(eq(deployments.id, input.deploymentId), isNull(deployments.deleteRequestedAt))); - if (!d) throw new BenchmarkError("not_found", "Deployment not found.", 404); - if (d.state !== "running") throw new BenchmarkError("invalid", "Start the deployment first; benchmarks run against a running server.", 409); - - const snapshot: BenchmarkSnapshot = { - deploymentName: d.name, - repoId: d.repoId, - runtimeName: d.runtimeName, - engine: d.engine, - accelerator: d.accelerator, - ...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")), - image: d.image, - imageId: d.imageId, - options: d.options, - cpus: d.cpus, - memoryMb: d.memoryMb, - command: [d.image, ...(d.command ?? [])].join(" "), - }; + const ab = !!input.deploymentBId; + const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment"); + const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null; + if (b) { + if (b.id === a.id) throw new BenchmarkError("invalid", "Pick two different deployments for an A/B.", 400); + if (b.snapshot.repoId !== a.snapshot.repoId) { + throw new BenchmarkError("invalid", "An A/B compares two deployments of the same model (BetterBench requests one model name from both).", 400); + } + } const [row] = await db() .insert(benchmarkRuns) .values({ - deploymentId: d.id, - modelId: d.modelId, + kind: ab ? "ab" : "run", + deploymentId: a.id, + deploymentBId: b?.id ?? null, + modelId: a.modelId, label: input.label || null, - settings: { quick: input.quick, passes: input.passes ?? null, warmup: input.warmup ?? null, phases: input.phases }, - snapshot, + settings: { + 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, }) .returning({ id: benchmarkRuns.id }); return row; @@ -107,6 +95,12 @@ const listColumns = { error: benchmarkRuns.error, summary: benchmarkRuns.summary, hasReport: benchmarkRuns.hasReport, + kind: benchmarkRuns.kind, + deploymentBId: benchmarkRuns.deploymentBId, + snapshotB: benchmarkRuns.snapshotB, + ab: benchmarkRuns.ab, + resources: benchmarkRuns.resources, + sweepId: benchmarkRuns.sweepId, createdAt: benchmarkRuns.createdAt, }; @@ -118,7 +112,7 @@ export async function listBenchmarks(filter: { deploymentId?: string; modelId?: .from(benchmarkRuns) .where( and( - filter.deploymentId ? eq(benchmarkRuns.deploymentId, filter.deploymentId) : undefined, + filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined, filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined, ), ) diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 64b3d91..28e4e29 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -525,6 +525,8 @@ export const deployments = sqliteTable("deployments", { exitCode: integer("exit_code"), error: text("error"), stats: text("stats", { mode: "json" }).$type(), + /** Temporary deployment created by a benchmark sweep (removed when its variant is done). */ + sweepId: text("sweep_id"), createdAt: createdAt(), updatedAt: updatedAt(), }); @@ -572,6 +574,61 @@ export type BenchmarkSettings = { passes: number | null; warmup: number | null; phases: BenchmarkPhase[]; + /** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */ + mdePct?: number | null; + maxPairs?: number | null; +}; + +export const BENCHMARK_KINDS = ["run", "ab"] as const; +export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number]; + +/** One side of a paired comparison, as BetterBench's paired_compare reports it. */ +export type PairedResult = { + metric: string; + n_pairs: number; + mean_a: number; + mean_b: number; + mean_diff: number; + pct_diff: number; + ci_low_pct: number; + ci_high_pct: number; + conf: number; + significant: boolean; + verdict: string; + higher_is_better: boolean; +}; + +/** `betterbench ab` result without the endpoints (raw per-pair series kept for the chart). */ +export type AbSummary = { + pairs: number; + decode_tps: PairedResult; + gap_median: PairedResult & { batched: boolean }; + paired_cv: number; + pairs_needed_for_mde: number; + target_mde_pct: number; + conf: number; + maxPairs: number | null; + raw: { a_tps: number[]; b_tps: number[] }; + betterbenchVersion: string; + corpusVersion: string; + timestamp: string | null; + config: { greedy?: boolean | null; temperature?: number | null; warmup?: number | null; unique_nonce?: boolean | null; ab_min_pairs?: number | null }; +}; + +/** Resource use sampled during a run (every ~2 s), per deployment and per GPU. */ +export type ResourceStats = { + samples: number; + seconds: number; + containers: { + side: "a" | "b"; + cpuAvg: number | null; + cpuPeak: number | null; + memAvgBytes: number | null; + memPeakBytes: number | null; + memLimitBytes: number | null; + }[]; + /** Whole-GPU figures (nvidia-smi), not per process. */ + gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[]; }; /** The deployment as it was when the run started, so results stay comparable after edits. */ @@ -701,6 +758,14 @@ export const benchmarkRuns = sqliteTable( summary: text("summary", { mode: "json" }).$type(), /** Files under BENCHMARKS_DIR//: results.json and results.html. */ hasReport: integer("has_report", { mode: "boolean" }).notNull().default(false), + kind: text("kind", { enum: BENCHMARK_KINDS }).notNull().default("run"), + /** A/B: the second deployment (B); `deploymentId` is A. */ + deploymentBId: text("deployment_b_id"), + snapshotB: text("snapshot_b", { mode: "json" }).$type(), + ab: text("ab", { mode: "json" }).$type(), + resources: text("resources", { mode: "json" }).$type(), + /** Run of a sweep variant. */ + sweepId: text("sweep_id"), createdAt: createdAt(), }, (t) => [index("benchmark_runs_created_idx").on(t.createdAt)], @@ -753,3 +818,43 @@ export const benchmarkPublications = sqliteTable( }, (t) => [index("benchmark_publications_run_idx").on(t.runId)], ); + +// --------------------------------------------------------------------------- +// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant +// --------------------------------------------------------------------------- + +export const SWEEP_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const; +export type SweepState = (typeof SWEEP_STATES)[number]; + +/** A setting a sweep varies; values are strings as entered (parsed per key). */ +export type SweepParam = { key: string; values: string[] }; + +export type SweepVariant = { + index: number; + /** 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"; + deploymentId?: string | null; + runId?: string | null; + error?: string | null; +}; + +export const benchmarkSweeps = sqliteTable("benchmark_sweeps", { + id: id(), + label: text("label"), + /** The deployment the variants are copied from (may be deleted later; `base` keeps it). */ + baseDeploymentId: text("base_deployment_id"), + base: text("base", { mode: "json" }) + .$type<{ name: string; runtimeId: string; modelId: string; options: DeploymentOptions; cpus: number | null; memoryMb: number | null }>() + .notNull(), + params: text("params", { mode: "json" }).$type().notNull(), + settings: text("settings", { mode: "json" }).$type().notNull(), + variants: text("variants", { mode: "json" }).$type().notNull(), + state: text("state", { enum: SWEEP_STATES }).notNull().default("queued"), + cancelRequestedAt: ts("cancel_requested_at"), + startedAt: ts("started_at"), + finishedAt: ts("finished_at"), + error: text("error"), + createdAt: createdAt(), +}); diff --git a/src/lib/deployments.ts b/src/lib/deployments.ts index a7bcdfc..8ef579e 100644 --- a/src/lib/deployments.ts +++ b/src/lib/deployments.ts @@ -228,6 +228,7 @@ const listColumns = { runtimeName: runtimes.name, runtimeImage: runtimes.image, accelerator: runtimes.accelerator, + sweepId: deployments.sweepId, engine: runtimes.engine, modelId: deployments.modelId, repoId: models.repoId, diff --git a/src/lib/sweep.test.ts b/src/lib/sweep.test.ts new file mode 100644 index 0000000..73b336f --- /dev/null +++ b/src/lib/sweep.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { applyOverrides, expandSweep, splitValues, SweepError, sweepKeysFor } from "./sweep"; + +describe("sweeps", () => { + it("expands two settings into a cartesian product with labels", () => { + const v = expandSweep( + [ + { key: "contextSize", values: ["4096", "8192"] }, + { key: "kvCache", values: ["f16", "q8_0"] }, + ], + "llama.cpp", + "cpu", + ); + assert.equal(v.length, 4); + assert.deepEqual(v[0], { index: 0, overrides: { contextSize: 4096, cacheTypeK: null, cacheTypeV: null }, label: "ctx 4096 · KV f16" }); + assert.deepEqual(v[3].overrides, { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }); + }); + + it("rejects bad values, keys and sizes", () => { + assert.throws(() => expandSweep([{ key: "contextSize", values: ["big", "8192"] }], "llama.cpp", "cpu"), SweepError); + assert.throws(() => expandSweep([{ key: "gpuLayers", values: ["10", "20"] }], "llama.cpp", "cpu"), /can't be varied/); + assert.throws(() => expandSweep([{ key: "dtype", values: ["float32", "bfloat16"] }], "llama.cpp", "cpu"), /can't be varied/); + assert.throws(() => expandSweep([{ key: "threads", values: ["4"] }], "llama.cpp", "cpu"), /at least two variants/); + assert.throws( + () => + expandSweep( + [ + { key: "threads", values: ["1", "2", "3", "4", "5"] }, + { key: "parallel", values: ["1", "2", "3", "4"] }, + ], + "llama.cpp", + "cpu", + ), + /20 variants/, + ); + assert.throws(() => expandSweep([{ key: "modelFile", values: ["a.gguf", "x.gguf"] }], "llama.cpp", "cpu", { modelFiles: ["a.gguf", "b.gguf"] }), /x\.gguf/); + }); + + it("offers GPU keys only on GPU runtimes and applies overrides", () => { + assert.ok(sweepKeysFor("llama.cpp", "nvidia").some((d) => d.key === "gpuLayers")); + assert.ok(!sweepKeysFor("vllm", "nvidia").some((d) => d.key === "kvCacheGb")); + assert.deepEqual(splitValues("4096, 8192 8192;16384"), ["4096", "8192", "16384"]); + const r = applyOverrides({ options: { modelFile: "m.gguf", contextSize: 4096, threads: 4, extraArgs: [] }, cpus: 4 }, { threads: 8, cpus: 8 }); + assert.deepEqual(r, { options: { modelFile: "m.gguf", contextSize: 4096, threads: 8, extraArgs: [] }, cpus: 8 }); + }); +}); diff --git a/src/lib/sweep.ts b/src/lib/sweep.ts new file mode 100644 index 0000000..319bb40 --- /dev/null +++ b/src/lib/sweep.ts @@ -0,0 +1,101 @@ +// Benchmark sweeps: which settings can vary, how their values parse, and the variant list (the +// cartesian product of up to two settings). Pure; shared by the form, the API and the worker. + +import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine, SweepParam } from "@/lib/db/schema"; + +export const MAX_SWEEP_VARIANTS = 16; +export const MAX_SWEEP_PARAMS = 2; + +/** Overrides for one variant: deployment options plus the container's CPU limit. */ +export type VariantOverrides = Partial & { cpus?: number | null }; + +type Def = { + key: string; + label: string; + /** Which runtimes it applies to. */ + engines: RuntimeEngine[]; + gpuOnly?: boolean; + cpuOnly?: boolean; + /** Example values for the form. */ + hint: string; + parse: (v: string) => VariantOverrides | null; + /** Short form for labels, e.g. "ctx 8192". */ + short: (v: string) => string; +}; + +const int = (min: number, max: number) => (v: string) => { + const n = Number(v); + return Number.isInteger(n) && n >= min && n <= max ? n : null; +}; +const num = (min: number, max: number) => (v: string) => { + const n = Number(v); + return Number.isFinite(n) && n >= min && n <= max ? n : null; +}; +const oneOf = (...xs: T[]) => (v: string) => (xs.includes(v as T) ? (v as T) : null); +const wrap = (f: (v: string) => T | null, to: (x: T) => VariantOverrides) => (v: string) => { + const x = f(v.trim()); + return x == null ? null : to(x); +}; + +export const SWEEP_KEYS: Def[] = [ + { key: "contextSize", label: "Context size", engines: ["llama.cpp", "vllm"], hint: "4096, 8192, 16384", parse: wrap(int(128, 1_048_576), (x) => ({ contextSize: x })), short: (v) => `ctx ${v}` }, + { key: "modelFile", label: "Model file (quant)", engines: ["llama.cpp"], hint: "pick downloaded GGUF files", parse: (v) => (v.trim() ? { modelFile: v.trim() } : null), short: (v) => v.replace(/\.gguf$/i, "").split(/[/-]/).slice(-1)[0] }, + { key: "kvCache", label: "KV cache type (K and V)", engines: ["llama.cpp"], hint: "f16, q8_0, q4_0", parse: wrap(oneOf("f16", "q8_0", "q4_0"), (x) => ({ cacheTypeK: x === "f16" ? null : x, cacheTypeV: x === "f16" ? null : x })), short: (v) => `KV ${v}` }, + { key: "threads", label: "Threads", engines: ["llama.cpp"], hint: "4, 8, 16", parse: wrap(int(1, 1024), (x) => ({ threads: x })), short: (v) => `${v} threads` }, + { key: "parallel", label: "Parallel slots", engines: ["llama.cpp"], hint: "1, 2, 4", parse: wrap(int(1, 256), (x) => ({ parallel: x })), short: (v) => `np ${v}` }, + { key: "batchSize", label: "Batch size", engines: ["llama.cpp"], hint: "512, 1024, 2048", parse: wrap(int(1, 65_536), (x) => ({ batchSize: x })), short: (v) => `b ${v}` }, + { key: "ubatchSize", label: "Micro-batch size", engines: ["llama.cpp"], hint: "128, 256, 512", parse: wrap(int(1, 65_536), (x) => ({ ubatchSize: x })), short: (v) => `ub ${v}` }, + { key: "flashAttn", label: "Flash attention", engines: ["llama.cpp"], hint: "on, off", parse: wrap(oneOf("auto", "on", "off"), (x) => ({ flashAttn: x })), short: (v) => `fa ${v}` }, + { key: "cacheRamMb", label: "Prompt cache in RAM (MiB)", engines: ["llama.cpp"], hint: "0, 1024, 8192", parse: wrap(int(-1, 1_048_576), (x) => ({ cacheRamMb: x })), short: (v) => `cram ${v}` }, + { key: "gpuLayers", label: "GPU layers", engines: ["llama.cpp"], gpuOnly: true, hint: "auto, 20, all", parse: (v) => (/^(auto|all|\d{1,4})$/.test(v.trim()) ? { gpuLayers: v.trim() } : null), short: (v) => `ngl ${v}` }, + { key: "dtype", label: "Data type", engines: ["vllm"], hint: "bfloat16, float32", parse: wrap(oneOf("auto", "bfloat16", "float16", "float32"), (x) => ({ dtype: x })), short: (v) => v }, + { key: "maxNumSeqs", label: "Max sequences", engines: ["vllm"], hint: "8, 16, 32", parse: wrap(int(1, 1024), (x) => ({ maxNumSeqs: x })), short: (v) => `seqs ${v}` }, + { key: "kvCacheGb", label: "KV cache (GiB)", engines: ["vllm"], cpuOnly: true, hint: "1, 2, 4", parse: wrap(num(0.25, 1024), (x) => ({ kvCacheGb: x })), short: (v) => `KV ${v} GiB` }, + { key: "gpuMemoryUtilization", label: "GPU memory share", engines: ["vllm"], gpuOnly: true, hint: "0.8, 0.9", parse: wrap(num(0.05, 1), (x) => ({ gpuMemoryUtilization: x })), short: (v) => `gmu ${v}` }, + { key: "cpus", label: "CPU limit (cores)", engines: ["llama.cpp", "vllm"], hint: "2, 4, 8", parse: wrap(num(0.1, 1024), (x) => ({ cpus: x })), short: (v) => `${v} cores` }, +]; + +export function sweepKeysFor(engine: RuntimeEngine, accelerator: RuntimeAccelerator): Def[] { + const gpu = accelerator !== "cpu"; + return SWEEP_KEYS.filter((d) => d.engines.includes(engine) && !(d.gpuOnly && !gpu) && !(d.cpuOnly && gpu)); +} + +/** "4096, 8192 16384" → ["4096", "8192", "16384"] (deduplicated, order kept). */ +export function splitValues(text: string): string[] { + return [...new Set(text.split(/[\s,;]+/).map((v) => v.trim()).filter(Boolean))]; +} + +export class SweepError extends Error {} + +export type Variant = { index: number; overrides: VariantOverrides; label: string }; + +/** Validate the parameters and expand them into variants (cartesian product). Throws SweepError. */ +export function expandSweep(params: SweepParam[], engine: RuntimeEngine, accelerator: RuntimeAccelerator, opts: { modelFiles?: string[] } = {}): Variant[] { + if (params.length === 0 || params.length > MAX_SWEEP_PARAMS) throw new SweepError(`Vary one or two settings.`); + const allowed = sweepKeysFor(engine, accelerator); + if (new Set(params.map((p) => p.key)).size !== params.length) throw new SweepError("Each setting can only be varied once."); + const axes = params.map((p) => { + const def = allowed.find((d) => d.key === p.key); + if (!def) throw new SweepError(`"${p.key}" can't be varied for this runtime.`); + const values = [...new Set(p.values.map((v) => v.trim()).filter(Boolean))]; + if (values.length < 1) throw new SweepError(`Give at least one value for ${def.label}.`); + return values.map((v) => { + const o = def.parse(v); + if (!o) throw new SweepError(`"${v}" isn't a valid value for ${def.label} (e.g. ${def.hint}).`); + if (p.key === "modelFile" && opts.modelFiles && !opts.modelFiles.includes(v)) throw new SweepError(`${v} isn't a downloaded GGUF file of this model.`); + return { o, s: def.short(v) }; + }); + }); + const total = axes.reduce((n, a) => n * a.length, 1); + if (total < 2) throw new SweepError("A sweep needs at least two variants."); + if (total > MAX_SWEEP_VARIANTS) throw new SweepError(`That's ${total} variants; the limit is ${MAX_SWEEP_VARIANTS}.`); + let combos: { o: VariantOverrides; s: string[] }[] = [{ o: {}, s: [] }]; + for (const axis of axes) combos = combos.flatMap((c) => axis.map((v) => ({ o: { ...c.o, ...v.o }, s: [...c.s, v.s] }))); + return combos.map((c, index) => ({ index, overrides: c.o, label: c.s.join(" · ") })); +} + +/** Apply a variant's overrides to the base deployment's options / CPU limit. */ +export function applyOverrides(base: { options: DeploymentOptions; cpus: number | null }, o: VariantOverrides) { + const { cpus, ...rest } = o; + return { options: { ...base.options, ...rest } as DeploymentOptions, cpus: cpus !== undefined ? cpus : base.cpus }; +} diff --git a/src/lib/sweeps.ts b/src/lib/sweeps.ts new file mode 100644 index 0000000..7f4ab9f --- /dev/null +++ b/src/lib/sweeps.ts @@ -0,0 +1,121 @@ +import "server-only"; +import { rm } from "node:fs/promises"; +import { and, desc, eq, inArray } from "drizzle-orm"; +import { z } from "zod"; +import { runDir } from "@/lib/benchmark-paths"; +import { db } from "@/lib/db/client"; +import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema"; +import { modelCandidates } from "@/lib/deploy-candidates"; +import { expandSweep, MAX_SWEEP_PARAMS, SweepError } from "@/lib/sweep"; + +export class SweepRequestError extends Error { + constructor( + public code: "invalid" | "not_found" | "busy", + message: string, + public status: number, + ) { + super(message); + } +} + +export const SweepBody = z.object({ + baseDeploymentId: z.string().min(1), + label: z.string().trim().max(80).nullable().optional(), + params: z + .array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) })) + .min(1) + .max(MAX_SWEEP_PARAMS), + 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([]), +}); + +/** Validate against the base deployment's runtime and model files, then queue the sweep. */ +export async function createSweep(input: z.infer) { + const [base] = await db() + .select({ + id: deployments.id, + name: deployments.name, + runtimeId: deployments.runtimeId, + modelId: deployments.modelId, + options: deployments.options, + cpus: deployments.cpus, + memoryMb: deployments.memoryMb, + engine: runtimes.engine, + accelerator: runtimes.accelerator, + imageState: runtimes.imageState, + }) + .from(deployments) + .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) + .where(eq(deployments.id, input.baseDeploymentId)); + if (!base) throw new SweepRequestError("not_found", "Base deployment not found.", 404); + if (base.imageState !== "present") throw new SweepRequestError("invalid", "The runtime's image isn't pulled.", 409); + const files = await db() + .select({ path: modelFiles.path, size: modelFiles.size }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, base.modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"]))); + const gguf = modelCandidates(files).gguf.map((g) => g.path); + let variants; + try { + variants = expandSweep(input.params, base.engine, base.accelerator, { modelFiles: gguf }); + } catch (err) { + if (err instanceof SweepError) throw new SweepRequestError("invalid", err.message, 400); + throw err; + } + const [row] = await db() + .insert(benchmarkSweeps) + .values({ + label: input.label || null, + baseDeploymentId: base.id, + // 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 }, + variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })), + }) + .returning({ id: benchmarkSweeps.id }); + return row; +} + +export type SweepRow = typeof benchmarkSweeps.$inferSelect; + +export async function listSweeps(): Promise { + return db().select().from(benchmarkSweeps).orderBy(desc(benchmarkSweeps.createdAt)); +} + +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 runs = runIds.length + ? await db() + .select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error }) + .from(benchmarkRuns) + .where(inArray(benchmarkRuns.id, runIds)) + : []; + return { sweep, runs }; +} + +export async function cancelSweep(id: string) { + const s = await db().query.benchmarkSweeps.findFirst({ columns: { state: true }, where: eq(benchmarkSweeps.id, id) }); + if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404); + if (s.state === "queued") { + await db().update(benchmarkSweeps).set({ state: "cancelled", finishedAt: new Date() }).where(eq(benchmarkSweeps.id, id)); + } else if (s.state === "running") { + await db().update(benchmarkSweeps).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkSweeps.id, id)); + } +} + +/** Delete a finished sweep with its runs (and their files). */ +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); + if (runIds.length) { + await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds)); + await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds)); + for (const r of runIds) await rm(runDir(r), { recursive: true, force: true }); + } + await db().delete(benchmarkSweeps).where(eq(benchmarkSweeps.id, id)); +} diff --git a/src/worker/ab-summary.ts b/src/worker/ab-summary.ts new file mode 100644 index 0000000..d2bed48 --- /dev/null +++ b/src/worker/ab-summary.ts @@ -0,0 +1,50 @@ +// `betterbench ab` output (ab.json) → Kaname's AbSummary. Keeps BetterBench's own paired_compare +// results as reported; drops the endpoints (they never leave the machine). Pure, for tests. + +import type { AbSummary, PairedResult } from "@/lib/db/schema"; + +type AbJson = { + betterbench_version?: string; + corpus_version?: string; + config?: Record; + env?: { timestamp?: string }; + pairs: number; + decode_tps: PairedResult; + gap_median?: PairedResult & { batched?: boolean }; + itl_median?: PairedResult; + paired_cv: number; + pairs_needed_for_mde: number; + target_mde_pct: number; + conf: number; + raw?: { a_tps?: number[]; b_tps?: number[] }; +}; + +const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null); + +export function abSummary(raw: string, maxPairs: number | null): AbSummary { + const j = JSON.parse(raw) as AbJson; + if (!j.decode_tps || typeof j.pairs !== "number") throw new Error("not a BetterBench ab.json"); + const gap = j.gap_median ?? (j.itl_median ? { ...j.itl_median, batched: false } : null); + const cfg = j.config ?? {}; + return { + pairs: j.pairs, + decode_tps: j.decode_tps, + gap_median: { ...(gap as PairedResult), batched: !!(gap as { batched?: boolean } | null)?.batched }, + paired_cv: j.paired_cv, + pairs_needed_for_mde: j.pairs_needed_for_mde, + target_mde_pct: j.target_mde_pct, + conf: j.conf, + maxPairs, + raw: { a_tps: j.raw?.a_tps ?? [], b_tps: j.raw?.b_tps ?? [] }, + betterbenchVersion: j.betterbench_version ?? "", + corpusVersion: j.corpus_version ?? "", + timestamp: j.env?.timestamp ?? null, + config: { + greedy: typeof cfg.greedy === "boolean" ? cfg.greedy : null, + temperature: num(cfg.temperature), + warmup: num(cfg.warmup), + unique_nonce: typeof cfg.unique_nonce === "boolean" ? cfg.unique_nonce : null, + ab_min_pairs: num(cfg.ab_min_pairs), + }, + }; +} diff --git a/src/worker/benchmarks.ts b/src/worker/benchmarks.ts index 10793ff..e29f117 100644 --- a/src/worker/benchmarks.ts +++ b/src/worker/benchmarks.ts @@ -2,7 +2,7 @@ // measure each other). import { type ChildProcess, execFile, spawn } from "node:child_process"; -import { access, mkdir } from "node:fs/promises"; +import { access, mkdir, readFile } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; import { asc, eq } from "drizzle-orm"; @@ -11,12 +11,25 @@ import { db } from "@/lib/db/client"; import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema"; import { ENGINE_PORT } from "@/lib/deploy-command"; import { coreEnv } from "@/lib/env"; -import { betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench"; +import { abSummary } from "./ab-summary"; +import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench"; import { sanitizeLine } from "./job-log"; import { log } from "./log"; import { errorCauses } from "./log-causes"; +import { ResourceSampler } from "./resources"; +import { docker, workerImage } from "./runtimes"; -type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] }; +type Current = { + runId: string; + kind: "run" | "ab"; + deploymentIds: string[]; + child: ChildProcess; + sampler: ResourceSampler | null; + maxPairs: number | null; + cancelled: boolean; + lost: string | null; + secrets: string[]; +}; let current: Current | null = null; let starting = false; @@ -114,36 +127,61 @@ async function summarize(results: string): Promise { return JSON.parse(stdout) as BenchmarkSummary; } +type Target = { id: string; containerId: string; containerName: string; engine: "llama.cpp" | "vllm"; accelerator: string }; + +async function target(deploymentId: string | null): Promise { + if (!deploymentId) return null; + const [d] = await db() + .select({ state: deployments.state, containerId: deployments.containerId, containerName: deployments.containerName, engine: runtimes.engine, accelerator: runtimes.accelerator }) + .from(deployments) + .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) + .where(eq(deployments.id, deploymentId)); + if (!d || d.state !== "running" || !d.containerName || !d.containerId) return null; + return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator }; +} + +const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`; + async function start(run: typeof benchmarkRuns.$inferSelect) { const fail = (error: string) => finish(run.id, { state: "failed", error }); - const [d] = run.deploymentId - ? await db() - .select({ state: deployments.state, containerName: deployments.containerName, engine: runtimes.engine }) - .from(deployments) - .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId)) - .where(eq(deployments.id, run.deploymentId)) - : []; - if (!d || d.state !== "running" || !d.containerName) return fail("The deployment isn't running anymore."); + const a = await target(run.deploymentId); + if (!a) return fail(run.kind === "ab" ? "Deployment A isn't running anymore." : "The deployment isn't running anymore."); + const b = run.kind === "ab" ? await target(run.deploymentBId) : null; + if (run.kind === "ab" && !b) return fail("Deployment B isn't running anymore."); const dir = runDir(run.id); await mkdir(dir, { recursive: true }); - const keys = run.snapshot.options.requireApiKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : []; + const needsKey = run.snapshot.options.requireApiKey || run.snapshotB?.options.requireApiKey; + // One key works for both: BETTERBENCH_API_KEY fills in every missing key flag. + const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : []; const s = run.snapshot; - const args = runArgs({ - endpoint: `http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1`, - model: s.repoId, - out: join(dir, RESULTS_FILE), - settings: run.settings, - maxModelLen: s.options.contextSize ?? null, - notes: { - deployment: s.deploymentName, - runtime: s.runtimeName, - image: s.image, - ...(s.options.modelFile ? { file: s.options.modelFile } : {}), - ctx: String(s.options.contextSize), - ...(run.label ? { label: run.label } : {}), - }, - }); + const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS; + const args = + run.kind === "ab" && b + ? abArgs({ + endpointA: endpoint(a), + endpointB: endpoint(b), + model: s.repoId, + out: join(dir, AB_FILE), + mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT, + maxPairs, + notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}) }, + }) + : runArgs({ + endpoint: endpoint(a), + model: s.repoId, + out: join(dir, RESULTS_FILE), + settings: run.settings, + maxModelLen: s.options.contextSize ?? null, + notes: { + deployment: s.deploymentName, + runtime: s.runtimeName, + image: s.image, + ...(s.options.modelFile ? { file: s.options.modelFile } : {}), + ctx: String(s.options.contextSize), + ...(run.label ? { label: run.label } : {}), + }, + }); // Only what BetterBench needs: no HF_TOKEN or other worker secrets. const env: Record = { PATH: process.env.PATH, @@ -156,20 +194,48 @@ async function start(run: typeof benchmarkRuns.$inferSelect) { ...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}), }; - addLog(run.id, "system", `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`); + addLog( + run.id, + "system", + run.kind === "ab" + ? `Paired A/B: ${s.deploymentName} (A) vs ${run.snapshotB?.deploymentName} (B), ${s.repoId}, with BetterBench` + : `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`, + ); addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys); await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id)); + // Resource use of the server(s) under test; GPUs when any side runs on NVIDIA. + const c = docker(); + const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia"; + const sampler = c + ? new ResourceSampler( + c, + [{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])], + nvidia ? workerImage() : null, + ) + : null; + await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`)); + const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); - const cur: Current = { runId: run.id, deploymentId: run.deploymentId, child, cancelled: false, lost: null, secrets: keys }; + const cur: Current = { + runId: run.id, + kind: run.kind, + deploymentIds: [a.id, ...(b ? [b.id] : [])], + child, + sampler, + maxPairs: run.kind === "ab" ? maxPairs : null, + cancelled: false, + lost: null, + secrets: keys, + }; current = cur; - child.stdout.on("data", (b: Buffer) => chunk(run.id, "stdout", b, keys)); - child.stderr.on("data", (b: Buffer) => chunk(run.id, "stderr", b, keys)); + child.stdout.on("data", (buf: Buffer) => chunk(run.id, "stdout", buf, keys)); + child.stderr.on("data", (buf: Buffer) => chunk(run.id, "stderr", buf, keys)); child.on("error", (err: NodeJS.ErrnoException) => { addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`); }); child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err))); - log.info(`benchmark ${run.id}: started for ${s.deploymentName}`); + log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`); } async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) { @@ -179,26 +245,33 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals | if (rest?.trim()) addLog(id, stream, rest, cur.secrets); partial.delete(`${id}:${stream}`); } + const resources = (await cur.sampler?.stop().catch(() => null)) ?? null; if (current === cur) current = null; const dir = runDir(id); - const results = join(dir, RESULTS_FILE); - const hasReport = await exists(join(dir, REPORT_FILE)); + const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE); + const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE))); if (cur.cancelled) { addLog(id, "system", "Cancelled."); - await finish(id, { state: "cancelled", hasReport }); + await finish(id, { state: "cancelled", hasReport, resources }); } else if (cur.lost) { addLog(id, "system", cur.lost); - await finish(id, { state: "failed", error: cur.lost, hasReport }); + await finish(id, { state: "failed", error: cur.lost, hasReport, resources }); } else if (code === 0 && (await exists(results))) { try { - const summary = { ...(await summarize(results)), quick: false }; - const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) }); - summary.quick = !!run?.settings.quick; - addLog(id, "system", "Done."); - await finish(id, { state: "completed", summary, hasReport }); + if (cur.kind === "ab") { + const ab = abSummary(await readFile(results, "utf8"), cur.maxPairs); + addLog(id, "system", `Done: ${ab.decode_tps.verdict} (${ab.pairs} pairs).`); + await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, resources, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." }); + } else { + const summary = { ...(await summarize(results)), quick: false }; + const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) }); + summary.quick = !!run?.settings.quick; + addLog(id, "system", "Done."); + await finish(id, { state: "completed", summary, hasReport, resources }); + } } catch (err) { - await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport }); + await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport, resources }); } } else { const lines = tails.get(id) ?? []; @@ -209,6 +282,7 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals | state: "failed", error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"), hasReport, + resources, }); } tails.delete(id); @@ -233,11 +307,12 @@ export async function tickBenchmarks(): Promise { stop(cur); return; } - if (cur.deploymentId) { - const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId)); + for (const depId of cur.deploymentIds) { + const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId)); if (!d || d.state !== "running") { - cur.lost = "The deployment stopped during the run."; + cur.lost = cur.deploymentIds.length > 1 ? "A deployment of the A/B stopped during the run." : "The deployment stopped during the run."; stop(cur); + break; } } return; diff --git a/src/worker/betterbench.ts b/src/worker/betterbench.ts index f8e7a59..b0fa184 100644 --- a/src/worker/betterbench.ts +++ b/src/worker/betterbench.ts @@ -43,6 +43,39 @@ export function runArgs(o: { ]; } +/** `betterbench ab`: interleaved paired A/B until the CI is tighter than --mde (or --max-pairs). */ +export function abArgs(o: { + endpointA: string; + endpointB: string; + model: string; + out: string; + mdePct: number; + maxPairs: number; + notes: Record; +}): string[] { + return [ + "ab", + "--endpoint-a", + o.endpointA, + "--endpoint-b", + o.endpointB, + "--model", + o.model, + "--out", + o.out, + "--mde", + String(o.mdePct), + "--max-pairs", + String(o.maxPairs), + ...Object.entries(o.notes).flatMap(([k, v]) => ["--note", `${k}=${v}`]), + "--no-update-check", + ]; +} + +export { AB_FILE } from "@/lib/benchmark-paths"; +export const AB_DEFAULT_MDE_PCT = 1; +export const AB_DEFAULT_MAX_PAIRS = 200; + /** * Prints Kaname's BenchmarkSummary for a results.json, using BetterBench's own report functions * so the numbers match its HTML report. diff --git a/src/worker/index.ts b/src/worker/index.ts index b1cb971..cd058e7 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -14,6 +14,7 @@ import { backfillMetadata } from "@/lib/hub/refresh"; import { DeleteRunner } from "./delete"; import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks"; import { reportL80Status, tickPublications } from "./publish"; +import { tickSweeps } from "./sweeps"; import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments"; import { DownloadRunner } from "./download"; import { log } from "./log"; @@ -414,6 +415,7 @@ async function main() { void refreshSummaries(); void reportL80Status(); timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS)); + timers.push(setInterval(() => void tickSweeps(), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS)); void scanFolders(); diff --git a/src/worker/resources.ts b/src/worker/resources.ts new file mode 100644 index 0000000..8ee52e8 --- /dev/null +++ b/src/worker/resources.ts @@ -0,0 +1,132 @@ +// Samples resource use while a benchmark runs: CPU and memory of the deployment containers (Docker +// stats, every ~2 s) and, on NVIDIA hosts, whole-GPU VRAM/utilization/power from one long-lived +// `nvidia-smi -lms` probe container. Aggregation is pure (summarizeSamples) for tests. + +import type { ResourceStats } from "@/lib/db/schema"; +import type { DockerClient } from "./docker/client"; +import { log } from "./log"; + +const INTERVAL_MS = 2_000; + +export type ContainerSample = { side: "a" | "b"; cpuPercent: number; memoryBytes: number; memoryLimitBytes: number }; +export type GpuSample = { index: number; name: string; vramTotalMb: number; vramUsedMb: number; util: number; powerW: number | null }; + +const avg = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null); +const peak = (xs: number[]) => (xs.length ? Math.max(...xs) : null); + +/** One CSV line of `nvidia-smi --query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw`. */ +export function parseGpuLine(line: string): GpuSample | null { + const p = line.split(",").map((x) => x.trim()); + if (p.length < 6 || !/^\d+$/.test(p[0])) return null; + const n = (s: string) => (Number.isFinite(Number(s)) ? Number(s) : null); + return { index: Number(p[0]), name: p[1], vramTotalMb: n(p[2]) ?? 0, vramUsedMb: n(p[3]) ?? 0, util: n(p[4]) ?? 0, powerW: n(p[5]) }; +} + +export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number): ResourceStats { + const sides = [...new Set(containers.map((c) => c.side))].sort(); + return { + samples: containers.length, + seconds: Math.round(seconds), + containers: sides.map((side) => { + const xs = containers.filter((c) => c.side === side); + // Docker reports CPU in percent of one core; keep cores. + const cpu = xs.map((x) => x.cpuPercent / 100); + const mem = xs.map((x) => x.memoryBytes); + const limit = xs.find((x) => x.memoryLimitBytes > 0)?.memoryLimitBytes ?? null; + return { + side, + cpuAvg: avg(cpu), + cpuPeak: peak(cpu), + memAvgBytes: avg(mem), + memPeakBytes: peak(mem), + // Without a limit Docker reports the host's memory; that isn't a limit. + memLimitBytes: limit, + }; + }), + gpus: [...new Set(gpus.map((g) => g.index))].sort((a, b) => a - b).map((index) => { + const xs = gpus.filter((g) => g.index === index); + const power = xs.map((x) => x.powerW).filter((x): x is number => x != null); + return { + index, + name: xs[0].name, + vramTotalMb: xs[0].vramTotalMb, + vramPeakMb: peak(xs.map((x) => x.vramUsedMb)) ?? 0, + vramAvgMb: avg(xs.map((x) => x.vramUsedMb)) ?? 0, + utilAvg: avg(xs.map((x) => x.util)) ?? 0, + utilPeak: peak(xs.map((x) => x.util)) ?? 0, + powerAvgW: avg(power), + powerPeakW: peak(power), + }; + }), + }; +} + +export class ResourceSampler { + private containerSamples: ContainerSample[] = []; + private gpuSamples: GpuSample[] = []; + private timer?: NodeJS.Timeout; + private busy = false; + private probeId: string | null = null; + private abort = new AbortController(); + private started = Date.now(); + + constructor( + private c: DockerClient, + private targets: { side: "a" | "b"; containerId: string }[], + private gpuProbeImage: string | null, + ) {} + + async start(): Promise { + this.started = Date.now(); + this.timer = setInterval(() => void this.sample(), INTERVAL_MS); + void this.sample(); + if (this.gpuProbeImage) await this.startGpuProbe(this.gpuProbeImage).catch((err) => log.warn(`GPU sampling unavailable: ${err instanceof Error ? err.message : err}`)); + } + + private async sample() { + if (this.busy) return; + this.busy = true; + try { + for (const t of this.targets) { + const s = await this.c.containerStats(t.containerId).catch(() => null); + if (s) this.containerSamples.push({ side: t.side, ...s }); + } + } finally { + this.busy = false; + } + } + + private async startGpuProbe(image: string) { + const created = await this.c.createContainer(`kaname-gpu-sampler-${Date.now().toString(36)}`, { + Image: image, + Entrypoint: ["nvidia-smi"], + Cmd: ["--query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw", "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)], + Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"], + Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" }, + HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false }, + }); + this.probeId = created.Id; + await this.c.startContainer(created.Id); + void this.c + .followLogs( + created.Id, + (_s, line) => { + const g = parseGpuLine(line); + if (g) this.gpuSamples.push(g); + }, + { tail: "all", signal: this.abort.signal }, + ) + .catch(() => {}); + } + + /** Stop sampling and return the aggregate (never throws). */ + async stop(): Promise { + clearInterval(this.timer); + this.abort.abort(); + if (this.probeId) { + await this.c.stopContainer(this.probeId, 1).catch(() => {}); + await this.c.removeContainer(this.probeId).catch(() => {}); + } + return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000); + } +} diff --git a/src/worker/runtimes.ts b/src/worker/runtimes.ts index c42c941..ffe8209 100644 --- a/src/worker/runtimes.ts +++ b/src/worker/runtimes.ts @@ -62,6 +62,10 @@ async function selfDetect(c: DockerClient): Promise ownImage; let gpuCache: { at: number; gpus: HostGpu[]; error: string | null } | null = null; /** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */ @@ -146,6 +150,7 @@ export async function refreshDockerInfo(instanceId: string): Promise { try { const [v, i] = await Promise.all([c.version(), c.info()]); const self = await selfDetect(c); + ownImage = self.image; info = { connected: true, error: null, diff --git a/src/worker/sweeps.ts b/src/worker/sweeps.ts new file mode 100644 index 0000000..d4a4a40 --- /dev/null +++ b/src/worker/sweeps.ts @@ -0,0 +1,153 @@ +// Runs benchmark sweeps one variant at a time: a temporary deployment with the variant's settings, +// a benchmark run against it once it is healthy, then the deployment is removed again. State lives in +// the sweep row, so a worker restart picks up where it was (an interrupted run fails its variant). + +import { and, asc, eq, inArray } from "drizzle-orm"; +import { deploymentSnapshot } from "@/lib/benchmark-snapshot"; +import { db } from "@/lib/db/client"; +import { benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema"; +import { estimateMemoryMb } from "@/lib/deploy-command"; +import { applyOverrides } from "@/lib/sweep"; +import { log } from "./log"; + +let busy = false; +const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); + +type Sweep = typeof benchmarkSweeps.$inferSelect; + +async function save(id: string, set: Partial) { + await db().update(benchmarkSweeps).set(set).where(eq(benchmarkSweeps.id, id)); +} + +/** Stop and remove a sweep's temporary deployment (the deployments reconciler does the work). */ +async function removeDeployment(id: string | null | undefined) { + if (!id) return; + await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id)); +} + +/** The variant's memory limit: the base limit, raised to the estimate when the variant needs more. */ +async function memoryFor(sweep: Sweep, options: Sweep["base"]["options"], accelerator: string, engine: "llama.cpp" | "vllm"): Promise { + if (!sweep.base.memoryMb) return null; + const files = await db() + .select({ path: modelFiles.path, size: modelFiles.size }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, sweep.base.modelId), eq(modelFiles.selected, true))); + const bytes = + engine === "llama.cpp" + ? files.filter((f) => [options.modelFile, options.mmproj, options.draftFile].includes(f.path)).reduce((s, f) => s + f.size, 0) + : files.reduce((s, f) => s + f.size, 0); + const est = estimateMemoryMb(bytes, options.contextSize, engine, { ...options, accelerator: accelerator as never }); + return Math.max(sweep.base.memoryMb, est); +} + +async function advance(sweep: Sweep): Promise { + const variants = [...sweep.variants]; + const put = async (i: number, patch: Partial) => { + variants[i] = { ...variants[i], ...patch }; + await save(sweep.id, { variants }); + }; + + if (sweep.cancelRequestedAt) { + 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); + } + await save(sweep.id, { + state: "cancelled", + finishedAt: new Date(), + variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)), + }); + log.info(`sweep ${sweep.id}: cancelled`); + return; + } + + const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking"); + 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." }); + log.info(`sweep ${sweep.id}: ${ok}/${variants.length} variants done`); + return; + } + const v = variants[i]; + + if (v.state === "pending") { + const rt = await db().query.runtimes.findFirst({ columns: { engine: true, accelerator: true }, where: eq(runtimes.id, sweep.base.runtimeId) }); + if (!rt) return void (await put(i, { state: "failed", error: "The runtime was deleted." })); + const { options, cpus } = applyOverrides(sweep.base, v.overrides); + const memoryMb = await memoryFor(sweep, options, rt.accelerator, rt.engine); + const [row] = await db() + .insert(deployments) + .values({ + name: `${sweep.base.name} · ${v.label}`.slice(0, 80), + runtimeId: sweep.base.runtimeId, + modelId: sweep.base.modelId, + options, + cpus, + memoryMb, + hostPort: null, + desiredState: "running", + sweepId: sweep.id, + }) + .returning({ id: deployments.id }); + await put(i, { state: "deploying", deploymentId: row.id }); + log.info(`sweep ${sweep.id}: variant ${i + 1}/${variants.length} (${v.label}) deploying`); + return; + } + + if (v.state === "deploying") { + const d = v.deploymentId ? await db().query.deployments.findFirst({ columns: { state: true, error: true }, where: eq(deployments.id, v.deploymentId) }) : null; + if (!d) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." })); + if (d.state === "failed") { + await put(i, { state: "failed", error: d.error ?? "The deployment failed to start." }); + return removeDeployment(v.deploymentId); + } + if (d.state !== "running") return; // still starting + const snap = await deploymentSnapshot(v.deploymentId!); + if (!snap) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." })); + const [run] = await db() + .insert(benchmarkRuns) + .values({ + kind: "run", + deploymentId: snap.id, + modelId: snap.modelId, + label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label}`.slice(0, 120), + settings: sweep.settings, + snapshot: snap.snapshot, + sweepId: sweep.id, + }) + .returning({ id: benchmarkRuns.id }); + await put(i, { state: "benchmarking", runId: run.id }); + return; + } + + // benchmarking + const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.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}.` }); + await removeDeployment(v.deploymentId); +} + +/** Drive the running sweep (or start the oldest queued one). */ +export async function tickSweeps(): Promise { + if (busy) return; + busy = true; + try { + let sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.state, "running"), orderBy: asc(benchmarkSweeps.createdAt) }); + if (!sweep) { + const next = await db().query.benchmarkSweeps.findFirst({ where: inArray(benchmarkSweeps.state, ["queued"]), orderBy: asc(benchmarkSweeps.createdAt) }); + if (!next) return; + await save(next.id, { state: "running", startedAt: new Date() }); + sweep = { ...next, state: "running" }; + log.info(`sweep ${next.id}: started (${next.variants.length} variants)`); + } + await advance(sweep).catch((err) => log.error(`sweep ${sweep!.id}`, err)); + } catch (err) { + log.error("sweeps", message(err)); + } finally { + busy = false; + } +}