Compare commits

...
10 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 2532f2f2b3 Release 0.9.0: benchmarks
Release / release (push) Successful in 3m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:29:30 +02:00
Pascal LinxweilerandClaude Opus 5.5 85af566b93 Downloads: speed limit in Settings
hf has no bandwidth option, so the worker pauses hf (SIGSTOP/SIGCONT) whenever it is ahead of a
token bucket over bytes on disk. The limit is shared by all running downloads and re-read every
5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:04:48 +02:00
Pascal LinxweilerandClaude Opus 5.5 b623b16a6d Benchmarks: paired A/B runs, sweeps, resource usage
- A/B with betterbench ab between two deployments of the same model, with verdict, confidence
  interval and caveats.
- Sweeps vary one or two deployment settings, deploy, benchmark and remove each variant, and
  compare them in one table.
- Every run records CPU, RAM, VRAM, GPU utilization and power.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:04:40 +02:00
Pascal LinxweilerandClaude Opus 5.5 9e167a44f6 Benchmarks with BetterBench, launch80-style reports and publishing, GPU support
- Benchmarks: BetterBench 0.6.1 (pinned by checksum) runs against a running
  deployment, one at a time; quick/full/custom passes, phase selection, live
  step and output, cancel, run again, compare runs side by side.
- Report page after launch80's bench.betterbench.v1: headline tiles,
  "Read these first" caveats (quick, sample gate, max_tokens truncation,
  batched streams, failures, skipped depths, prefix-cache hits), charts, full
  tables with daggered under-sampled cells, method text. All figures come from
  BetterBench's own report functions.
- Publish to launch80 as a double opt-in: L80 dry run builds the exact payload
  for inspection, an explicit confirmation publishes that file (L80 CLI 0.4.0
  pinned by checksum, L80_TOKEN worker-only). Endpoint and host never leave.
- GPUs: runtime accelerator (CPU, NVIDIA, /dev/dri, ROCm) with presets for the
  official CUDA/Vulkan/Intel/ROCm builds; NVIDIA GPUs probed via nvidia-smi in
  a short-lived container; per-deployment GPU picking, -ngl, split mode,
  tensor split, MoE offload, vLLM tensor parallel and GPU memory share.
- llama.cpp --cache-ram option (1 GiB for new deployments) and a memory
  estimate that counts it and the KV cache: the 8 GiB default made containers
  thrash at their memory limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:54:38 +02:00
Pascal LinxweilerandClaude Opus 5.5 f0b4adda63 Release 0.8.0: deployments
Release / release (push) Successful in 3m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:30:14 +02:00
Pascal LinxweilerandClaude Opus 5.5 ea1f18cc74 Deployments: API keys, deploy from the library, reorganized form
- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:28:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 66e6a8c4f7 Deployments: llama.cpp web UI toggle, clearer start failures, log fixes
- Web UI option for llama.cpp deployments (--no-webui when off); the deployment
  page links to it on the published host port.
- Follow container logs after the start with tail=all: following a created
  container returned an already-closed stream, so startup output was lost.
- Failed starts name the cause from the log (vLLM ValueError, llama.cpp error
  lines) before the last output.
- A deployment's vLLM dtype replaces the runtime's --dtype instead of repeating it.
- vLLM memory estimate: 3 GiB overhead (measured ~6.9 GiB for SmolLM2-135M
  with a 4 GiB KV cache).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:01:52 +02:00
Pascal LinxweilerandClaude Opus 5.5 8b74fa69db Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

Not yet tested end-to-end against real containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:31:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 4f7ae1fc8c Fix image pull progress never being written
`void query` doesn't execute a Drizzle query (it runs on then/await), so
pull progress stayed at "Starting" until the pull finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:39:15 +02:00
Pascal LinxweilerandClaude Opus 5.5 a756eb3794 Release workflow: drop setup-node's npm cache
The act_runner cache server isn't reachable from job containers
(getCacheEntry ETIMEDOUT), so restoring and saving the cache timed out
for ~4.5 min each, ~9 of the ~12 minutes per release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:30:25 +02:00
128 changed files with 20400 additions and 65 deletions

No files matched your search

+5
View File
@@ -19,6 +19,11 @@ OIDC_ALLOWED_GROUPS=
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
HF_TOKEN=
# Optional: launch80.com publish token (comes with the launch80 Supporter role). Lets you publish a
# benchmark run as a public launch80 page, after a preview and an explicit confirmation. Stays on
# the server; never sent to the browser or written to logs.
L80_TOKEN=
# ---------------------------------------------------------------------------
# Folders on the Docker host (deploy/compose.yaml); both must be owned by uid 1000
# ---------------------------------------------------------------------------
+2 -1
View File
@@ -14,10 +14,11 @@ jobs:
steps:
- uses: actions/checkout@v4
# No `cache: npm`: the runner's cache server isn't reachable from job containers here, and the
# restore + save timeouts cost ~9 minutes per run. `npm ci` alone takes ~20 s.
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Resolve version and image name
run: |
+123
View File
@@ -6,6 +6,129 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.9.0] - 2026-10-13
Model testing, part three: benchmarks. Measure deployments with BetterBench (the benchmark behind
launch80.com) and get a launch80-style report: single runs, paired A/B runs and sweeps over launch
options, with CPU, RAM and GPU usage recorded during each run. Runs can be published to launch80
with a preview and an explicit confirmation. Runtimes can use NVIDIA, Intel/AMD and ROCm GPUs, and
downloads can be speed-limited.
No changes to `compose.yaml`. Optional new `.env` setting: `L80_TOKEN` (launch80 publishing). The
new database tables are created on start.
### Added
- **Download speed limit** (Settings → Downloads), in MB/s, for all downloads together; changes
apply to running downloads within seconds. `hf download` and hf_xet have no bandwidth option
(checked with huggingface_hub 2.1.1 / hf_xet 1.6.0), so the worker pauses and resumes the hf
process (SIGSTOP/SIGCONT) whenever it gets ahead of the limit: short bursts above it, the
average holds (tested: 145 MB at a 2 MB/s limit took 67 s). Linux only; ignored on Windows.
- **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).
- Start a run from a running deployment: quick (5 passes) or full (20), choose generation,
prompt processing (input lengths up to the context size) and parallel requests, add a label.
- Runs go one at a time; the run page shows the current step, the live BetterBench output, then
headline numbers (weighted decode t/s, time to first token, prefill t/s, peak throughput) and
the per-category, per-length and per-load tables, BetterBench's own HTML report (sandboxed)
and its `results.json`.
- Each run keeps a snapshot of the deployment's settings (and the CPU/GPU it ran on). Select runs
to **compare** them: differing settings are highlighted, numbers show the change against the
first run.
- Cancel, run again with the same settings, rename, delete.
- **Benchmark report page** after launch80's `bench.betterbench.v1`: headline tiles (combined
decode, ITL 1% low or stream-update p99, TTFT p50), "Read these first" caveats with launch80's
rules (quick run, under-sampled percentiles marked †, runs stopped at max_tokens, batched streams,
failed requests, skipped prefill depths, prefix-cache hits), charts for decode by category, ITL
range, prefill and parallel load, the full tables, the reasoning split and a Method section. Every
figure comes from BetterBench's own report functions; existing runs are recomputed on start.
- **Publish to launch80** (double opt-in, as the L80 docs describe): step 1 runs
`L80 betterbench --results … --dry-run --payload-out` and shows exactly what would be sent
(template, size, title, summary, notes; endpoint and host removed; the payload is downloadable);
step 2 publishes that same file with `L80 publish` only after an explicit confirmation. Needs
`L80_TOKEN` (launch80 Supporter) for the worker; the L80 CLI 0.4.0 ships in the image, pinned by
checksum. The link, who confirmed it and when it expires (5 days) are kept per run.
- `results.json` downloads no longer contain the endpoint URL or host name.
- **GPUs.** Runtimes have a type: CPU, NVIDIA (CUDA), Intel/AMD via `/dev/dri` (Vulkan, SYCL,
XPU) or AMD ROCm, with presets for the official CUDA, Vulkan, Intel and ROCm builds of
llama.cpp and vLLM.
- The worker lists NVIDIA GPUs (name, VRAM, driver) with a short-lived probe container and shows
them under Settings → Runtimes; the first time one shows up, a "llama.cpp (CUDA)" runtime is
added.
- Deployments on GPU runtimes pick which GPUs to use and set GPU layers (`-ngl`), split mode,
tensor split and MoE experts in RAM (llama.cpp) or tensor parallelism and GPU memory share
(vLLM).
- llama.cpp **prompt cache in RAM** (`--cache-ram`) as a deployment option, 1 GiB for new
deployments.
### Fixed
- llama-server keeps up to 8 GiB of earlier prompts in RAM by default. Under a container memory
limit it grew until the limit and then slowed to a crawl (the memory-mapped model got evicted).
The memory estimate now counts the prompt cache and the KV cache (by context size and cache
type).
## [0.8.0] - 2026-10-06
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
container, tune its launch options, protect it with API keys and try it from Kaname.
No changes to `compose.yaml`; the new database tables are created on start.
### Added
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
published host port and extra arguments. A live preview shows the exact `docker run` command.
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
memory limits of running deployments wouldn't fit. Containers keep running across worker
restarts; orphaned ones are removed.
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
time to first token and tokens/s.
- llama.cpp's built-in **web UI** can be switched on or off per deployment (`--no-webui`); with a
published host port the deployment page links to it.
- A failed start names the cause from the log (e.g. vLLM's `ValueError` instead of the end of the
traceback), followed by the last lines of output.
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
deployment with the model and a fitting runtime preselected. The library and the model page link
to the deployments that use a model.
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
### Fixed
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
follow the theme.
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
written (Drizzle queries only run when awaited).
## [0.7.0] - 2026-10-06
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
+24 -2
View File
@@ -1,3 +1,4 @@
# syntax=docker/dockerfile:1.7
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
FROM node:24-trixie-slim AS node
@@ -22,9 +23,28 @@ COPY --from=node /usr/local/bin/node /usr/local/bin/node
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
# re-verify that before bumping.
ARG HF_HUB_VERSION=2.1.1
# BetterBench (Apache-2.0), the benchmark run against deployments. Not on PyPI: the release
# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
ARG BETTERBENCH_VERSION=0.6.1
ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /tmp/betterbench.tar.gz
# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
# by checksum (from the release's checksums.txt); the per-architecture one is installed.
ARG L80_VERSION=0.4.0
ARG TARGETARCH
ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /tmp/l80/amd64.tar.gz
ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /tmp/l80/arm64.tar.gz
RUN mkdir -p /opt/l80 \
&& tar -xzf "/tmp/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
&& chmod 0755 /opt/l80/L80 \
&& rm -rf /tmp/l80
RUN python -m venv /opt/hf \
&& /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \
&& rm -rf /root/.cache \
&& python -m venv /opt/betterbench \
&& /opt/betterbench/bin/pip install --no-cache-dir /tmp/betterbench.tar.gz \
&& rm -rf /root/.cache /tmp/betterbench.tar.gz \
&& useradd --uid 1000 --create-home --shell /usr/sbin/nologin app \
&& mkdir -p /data /models \
&& chown app:app /data /models
@@ -38,7 +58,9 @@ ENV PATH=/opt/hf/bin:$PATH \
HOSTNAME=0.0.0.0 \
DATABASE_URL=file:/data/app.db \
MODELS_DIR=/models \
HF_HOME=/data/hf-home
HF_HOME=/data/hf-home \
BETTERBENCH_BIN=/opt/betterbench/bin/betterbench \
L80_BIN=/opt/l80/L80
WORKDIR /app
COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE `deployment_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deployment_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
CREATE TABLE `deployments` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`runtime_id` text NOT NULL,
`model_id` text NOT NULL,
`options` text NOT NULL,
`cpus` real,
`memory_mb` integer,
`host_port` integer,
`desired_state` text DEFAULT 'stopped' NOT NULL,
`state` text DEFAULT 'stopped' NOT NULL,
`delete_requested_at` integer,
`container_id` text,
`container_name` text,
`command` text,
`image_id` text,
`started_at` integer,
`ready_at` integer,
`stopped_at` integer,
`exit_code` integer,
`error` text,
`stats` text,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE `api_keys` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`key` text NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
+29
View File
@@ -0,0 +1,29 @@
CREATE TABLE `benchmark_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`run_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_logs_idx` ON `benchmark_logs` (`run_id`,`id`);--> statement-breakpoint
CREATE TABLE `benchmark_runs` (
`id` text PRIMARY KEY NOT NULL,
`deployment_id` text,
`model_id` text,
`tool` text DEFAULT 'betterbench' NOT NULL,
`settings` text NOT NULL,
`snapshot` text NOT NULL,
`label` text,
`state` text DEFAULT 'queued' NOT NULL,
`phase` text,
`cancel_requested_at` integer,
`started_at` integer,
`finished_at` integer,
`error` text,
`summary` text,
`has_report` integer DEFAULT false NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_runs_created_idx` ON `benchmark_runs` (`created_at`);
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `runtimes` ADD `accelerator` text DEFAULT 'cpu' NOT NULL;
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE `benchmark_publications` (
`id` text PRIMARY KEY NOT NULL,
`run_id` text NOT NULL,
`state` text DEFAULT 'preview' NOT NULL,
`template` text DEFAULT 'bench.betterbench.v1' NOT NULL,
`title` text,
`summary` text,
`payload_bytes` integer,
`previewed_at` integer,
`confirmed_by` text,
`confirmed_at` integer,
`url` text,
`guid` text,
`published_at` integer,
`error` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `benchmark_publications_run_idx` ON `benchmark_publications` (`run_id`);
+23
View File
@@ -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;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+42
View File
@@ -78,6 +78,48 @@
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
},
{
"idx": 12,
"version": "6",
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
},
{
"idx": 13,
"version": "6",
"when": 1791654372298,
"tag": "0013_benchmarks",
"breakpoints": true
},
{
"idx": 14,
"version": "6",
"when": 1791655909335,
"tag": "0014_runtime_accelerator",
"breakpoints": true
},
{
"idx": 15,
"version": "6",
"when": 1791657884019,
"tag": "0015_benchmark_publications",
"breakpoints": true
},
{
"idx": 16,
"version": "6",
"when": 1791658947930,
"tag": "0016_ab_resources_sweeps",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.7.0",
"version": "0.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.7.0",
"version": "0.9.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.7.0",
"version": "0.9.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+44 -1
View File
@@ -9,6 +9,8 @@ import {
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
@@ -17,12 +19,14 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
@@ -97,13 +101,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs] = await Promise.all([
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
@@ -143,6 +151,15 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
@@ -287,6 +304,32 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
+185
View File
@@ -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 (
<div className="flex flex-col gap-1" role="img" aria-label={`Difference ${sign(r.pct_diff)}, 95% interval ${sign(r.ci_low_pct)} to ${sign(r.ci_high_pct)}`}>
<div className="relative h-12">
{/* ±target band: differences inside it are smaller than the precision asked for */}
<div className="absolute inset-y-2 bg-muted" style={{ left: pos(-target), width: `calc(${pos(target)} - ${pos(-target)})` }} />
<div className="absolute inset-y-0 w-px bg-foreground/50" style={{ left: pos(0) }} />
<div
className={cn("absolute top-1/2 h-2 -translate-y-1/2 rounded-full", r.significant ? "bg-series" : "bg-foreground/40")}
style={{ left: pos(r.ci_low_pct), width: `calc(${pos(r.ci_high_pct)} - ${pos(r.ci_low_pct)})` }}
/>
<div
className={cn("absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-card", r.significant ? "bg-series" : "bg-foreground/60")}
style={{ left: pos(r.pct_diff) }}
/>
</div>
<div className="relative h-4 text-[11px] text-muted-foreground tabular-nums">
{ticks.map((t) => (
<span key={t} className="absolute -translate-x-1/2" style={{ left: pos(t) }}>
{t > 0 ? "+" : ""}
{t}%
</span>
))}
</div>
<p className="text-[11px] text-muted-foreground">
Dot: B&apos;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"}.
</p>
</div>
);
}
function Side({ label, name, value, unit }: { label: string; name: string; value: number; unit: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-lg font-semibold">
{value.toFixed(unit === "ms" ? 2 : 1)} <span className="text-sm font-normal text-muted-foreground">{unit}</span>
</span>
<span className="truncate text-[11px] text-muted-foreground" title={name}>
{name}
</span>
</div>
);
}
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 (
<article className="flex flex-col gap-8 rounded-2xl bg-card px-5 py-6 ring-1 ring-foreground/10 sm:px-8 sm:py-8">
<header className="flex flex-col gap-3">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs
</span>
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}</h2>
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, a.deploymentName, b.deploymentName)}</p>
</header>
<section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Decode throughput</span>
<span className={cn("text-3xl font-semibold", d.significant ? "" : "text-muted-foreground")}>{abHeadline(d)}</span>
<span className="text-sm text-muted-foreground">
{sign(d.pct_diff)} · 95% CI {sign(d.ci_low_pct)} to {sign(d.ci_high_pct)} · {d.significant ? "significant" : "within noise"}
</span>
<IntervalChart r={d} target={ab.target_mde_pct} />
</div>
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g.batched ? "Stream-update gap" : "Token-to-token smoothness"}</span>
<span className={cn("text-3xl font-semibold", g.significant ? "" : "text-muted-foreground")}>{abHeadline(g)}</span>
<span className="text-sm text-muted-foreground">
{sign(g.pct_diff)} · 95% CI {sign(g.ci_low_pct)} to {sign(g.ci_high_pct)} · lower is better
</span>
<IntervalChart r={g} target={ab.target_mde_pct} />
</div>
</section>
<div className="grid gap-2 sm:grid-cols-4">
<Side label="A · decode, mean" name={a.deploymentName} value={d.mean_a} unit="t/s" />
<Side label="B · decode, mean" name={b.deploymentName} value={d.mean_b} unit="t/s" />
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Pairs</span>
<span className="text-lg font-semibold">{ab.pairs}</span>
<span className="text-[11px] text-muted-foreground">
±{halfWidth(d).toFixed(2)}% reached · target ±{ab.target_mde_pct}%
</span>
</div>
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Paired CV</span>
<span className="text-lg font-semibold">{(ab.paired_cv * 100).toFixed(2)}%</span>
<span className="text-[11px] text-muted-foreground">~{ab.pairs_needed_for_mde} pairs for ±{ab.target_mde_pct}%</span>
</div>
</div>
{caveats.length > 0 && (
<div className="flex gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex flex-col gap-1.5">
<span className="font-medium text-amber-800 dark:text-amber-200">Read these first</span>
{caveats.map((x) => (
<p key={x} className="text-foreground/80">
{x}
</p>
))}
</div>
</div>
)}
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">What differs</h3>
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<table className="w-full text-xs">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-3 py-2 font-medium" />
<th className="px-3 py-2 font-medium">A · {a.deploymentName}</th>
<th className="px-3 py-2 font-medium">B · {b.deploymentName}</th>
</tr>
</thead>
<tbody>
{differs.length === 0 && (
<tr>
<td colSpan={3} className="px-3 py-2 text-muted-foreground">
Same settings on both sides (a null A/B: it shows how much noise the setup has).
</td>
</tr>
)}
{differs.map(({ row, va, vb }) => (
<tr key={row.key} className="border-b bg-amber-500/5 last:border-0">
<td className="px-3 py-1.5 font-medium">{row.label}</td>
<td className="px-3 py-1.5 font-mono break-all">{va ?? <span className="text-muted-foreground">default</span>}</td>
<td className="px-3 py-1.5 font-mono break-all">{vb ?? <span className="text-muted-foreground">default</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
{same.length > 0 && <p className="text-xs text-muted-foreground">Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.</p>}
</section>
{run.resources && (
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">Resources</h3>
<BenchmarkResources stats={run.resources} names={{ a: a.deploymentName, b: b.deploymentName }} />
</section>
)}
<section className="flex flex-col gap-2">
<h3 className="text-base font-semibold">Method</h3>
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
{abMethod(ab).map((p) => (
<p key={p}>{p}</p>
))}
</div>
</section>
<footer className="border-t pt-4 text-xs text-muted-foreground">
Generated by Kaname from a BetterBench {ab.betterbenchVersion} paired A/B{ab.corpusVersion ? ` on corpus v${ab.corpusVersion}` : ""}. Every figure is BetterBench&apos;s own.
</footer>
</article>
);
}
@@ -0,0 +1,360 @@
"use client";
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";
import { toast } from "sonner";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { CopyButton } from "@/components/copy-button";
import { LiveLog } from "@/components/live-log";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
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 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`;
}
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const router = useRouter();
const [r, setR] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const [label, setLabel] = useState(initial.label ?? "");
const active = r.state === "queued" || r.state === "running";
useEffect(() => {
if (!active) return;
const t = setInterval(async () => {
setNow(Date.now());
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);
}, [active, r.id]);
async function again() {
if (!r.deploymentId) return;
const res = await fetch("/api/benchmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
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})`,
);
router.push(`/benchmarks/${json.id}`);
}
const s = r.snapshot;
const sum = r.summary;
const took = duration(r.startedAt, r.finishedAt, now);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">
{r.label ??
(r.kind === "ab"
? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}`
: s.deploymentName)}
</h1>
{r.kind === "ab" && (
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
A/B
</span>
)}
<BenchmarkStateBadge
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
</div>
<p className="text-sm text-muted-foreground">
{r.deploymentId ? (
<Link
href={`/deployments/${r.deploymentId}`}
className="hover:underline"
>
{s.deploymentName}
</Link>
) : (
`${s.deploymentName} (deleted)`
)}{" "}
·{" "}
{r.modelId ? (
<Link href={`/${s.repoId}`} className="hover:underline">
{s.repoId}
</Link>
) : (
s.repoId
)}{" "}
· {s.runtimeName}
{r.kind === "ab" && r.snapshotB && (
<>
{" "}
· B:{" "}
{r.deploymentBId ? (
<Link
href={`/deployments/${r.deploymentBId}`}
className="hover:underline"
>
{r.snapshotB.deploymentName}
</Link>
) : (
r.snapshotB.deploymentName
)}
</>
)}
{r.sweepId && (
<>
{" "}
·{" "}
<Link
href={`/benchmarks/sweeps/${r.sweepId}`}
className="hover:underline"
>
part of a sweep
</Link>
</>
)}
</p>
<p className="text-xs text-muted-foreground">
BetterBench ·{" "}
{r.kind === "ab"
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
: describeSettings(r.settings)}{" "}
· created <LocalTime value={r.createdAt} />
{took &&
` · ${r.state === "running" ? "running for" : "took"} ${took}`}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{r.hasReport && (
<a
href={`/api/benchmarks/${r.id}/report`}
target="_blank"
rel="noreferrer"
className={buttonVariants({ variant: "outline" })}
>
<ExternalLinkIcon />
Full report
</a>
)}
{r.state === "completed" && (
<a
href={`/api/benchmarks/${r.id}/results`}
className={buttonVariants({ variant: "outline" })}
>
<DownloadIcon />
{r.kind === "ab" ? "ab.json" : "results.json"}
</a>
)}
{active ? (
<Button
variant="outline"
disabled={!!r.cancelRequestedAt}
onClick={async () =>
(await cancelBenchmark(r.id)) && router.refresh()
}
>
<SquareIcon />
Cancel
</Button>
) : (
r.deploymentId &&
!r.sweepId && (
<Button
variant="outline"
onClick={again}
title="Queue a new run with the same settings (the deployment must be running)"
>
<RotateCcwIcon />
Run again
</Button>
)
)}
<AlertDialog>
<AlertDialogTrigger
render={
<Button
variant="outline"
disabled={r.state === "running"}
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
/>
}
>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this benchmark?</AlertDialogTitle>
<AlertDialogDescription>
Its numbers, log, results.json and HTML report are removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteBenchmark(r.id)) {
router.push("/benchmarks");
router.refresh();
}
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{r.error && (
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
<pre className="min-w-0 flex-1 font-sans break-words whitespace-pre-wrap">
{r.error}
</pre>
</div>
)}
{r.state === "queued" && (
<p className="text-sm text-muted-foreground">
Waiting: benchmarks run one at a time.
</p>
)}
{r.state === "running" && r.phase && (
<p className="text-sm text-muted-foreground">Now: {r.phase}</p>
)}
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
<div className="flex min-w-0 flex-col gap-4">
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
<LiveLog
url={`/api/benchmarks/${r.id}/logs`}
title="BetterBench output"
live={active}
/>
</div>
<aside className="flex flex-col gap-4">
{r.kind === "run" && r.state === "completed" && r.summary && (
<PublishCard
runId={r.id}
defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`}
defaultSummary={reportSummary(r)}
/>
)}
<Card size="sm">
<CardHeader>
<CardTitle>Label</CardTitle>
</CardHeader>
<CardContent>
<Input
value={label}
maxLength={120}
placeholder="e.g. q8_0 KV cache"
onChange={(e) => setLabel(e.target.value)}
onBlur={async () =>
label !== (r.label ?? "") &&
(await renameBenchmark(r.id, label || null)) &&
setR({ ...r, label: label.trim() || null })
}
onKeyDown={(e) =>
e.key === "Enter" && (e.target as HTMLInputElement).blur()
}
/>
</CardContent>
</Card>
{r.kind === "run" && (
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
{CONFIG_ROWS.map((row) => {
const v = row.value(s);
return v == null ? null : (
<div key={row.key} className="contents">
<dt className="text-muted-foreground">{row.label}</dt>
<dd className="min-w-0 font-mono break-all">{v}</dd>
</div>
);
})}
</dl>
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between text-xs text-muted-foreground">
Command
<CopyButton value={s.command} label="Copy command" />
</div>
<pre className="rounded-md bg-muted/60 px-2 py-1.5 font-mono text-[11px] break-all whitespace-pre-wrap">
{s.command}
</pre>
</div>
{sum && (
<p className="text-[11px] text-muted-foreground">
BetterBench {sum.betterbenchVersion} · corpus v
{sum.corpusVersion} · phases: {sum.phases.join(", ") || "–"}
</p>
)}
</CardContent>
</Card>
)}
</aside>
</div>
</div>
);
}
@@ -0,0 +1,389 @@
"use client";
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";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
return (
<div className="flex flex-col gap-1 rounded-xl bg-muted/50 px-4 py-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-3xl font-semibold">
{value}
<span className="ml-1 text-base font-normal text-muted-foreground">{unit}</span>
</span>
<span className="text-xs text-muted-foreground">{note}</span>
</div>
);
}
function Section({ title, intro, children }: { title: string; intro?: string; children: React.ReactNode }) {
return (
<section className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<h2 className="text-base font-semibold">{title}</h2>
{intro && <p className="max-w-3xl text-sm text-muted-foreground">{intro}</p>}
</div>
{children}
</section>
);
}
/** A percentile cell, daggered when it fails BetterBench's sample gate. */
function Gated({ v, sum, section, k, metric, fmt = f1 }: { v: number | null | undefined; sum: BenchmarkSummary; section: string; k: string | number; metric: string; fmt?: (v: number | null | undefined) => string }) {
const gated = v != null && undersampled(sum, section, k, metric);
return (
<span className={cn(gated && "text-amber-700 dark:text-amber-300")} title={gated ? "Under-sampled: roughly the worst observed, not a percentile" : undefined}>
{fmt(v)}
{gated && "†"}
</span>
);
}
const date = (iso: string | null | undefined) =>
iso
? new Date(iso.replace(/([+-]\d\d)(\d\d)$/, "$1:$2"))
.toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" })
.toUpperCase()
.replace(",", " ·")
: "";
/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
export function BenchmarkReport({ run }: { run: ListRow }) {
const sum = run.summary;
if (!sum) return null;
const s = run.snapshot;
const batched = isBatched(sum);
const caveats = reportCaveats(run);
const c = sum.combined;
const peak = sum.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
const cfg = sum.config ?? {};
const chips = [
sum.corpusVersion && `corpus v${sum.corpusVersion}`,
sum.single.length && sum.passes ? `${sum.passes} passes/cat` : null,
cfg.greedy ? "greedy" : cfg.temperature != null ? `temp ${cfg.temperature}` : null,
cfg.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (nonce)",
`phases: ${sum.phases.join(", ")}`,
].filter(Boolean) as string[];
return (
<article className="flex flex-col gap-8 rounded-2xl bg-card px-5 py-6 ring-1 ring-foreground/10 sm:px-8 sm:py-8">
<header className="flex flex-col gap-3">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
BetterBench {sum.betterbenchVersion} · {date(sum.timestamp ?? run.startedAt)}
</span>
<div className="flex flex-col gap-1">
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${s.repoId} ${weightsLabel(s) !== "safetensors" ? weightsLabel(s) : ""}`.trim()}</h2>
<p className="text-sm text-muted-foreground">{reportSubtitle(run)}</p>
</div>
<div className="flex flex-wrap gap-1.5">
{chips.map((x) => (
<span key={x} className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
{x}
</span>
))}
<span className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">{s.runtimeName}</span>
{configChips(s).map((x) => (
<span key={x} className="rounded-md bg-muted px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
{x}
</span>
))}
</div>
<p className="max-w-3xl text-sm leading-relaxed">{reportSummary(run)}</p>
</header>
{c && (
<div className="grid gap-3 sm:grid-cols-3">
<Tile label="Combined decode" value={f1(c.decode)} unit="t/s" note="weighted across categories" />
{batched ? (
<Tile label="Combined update p99" value={f1(c.update_p99)} unit="ms" note="gap between stream updates" />
) : (
<Tile label="Combined ITL 1% low" value={f1(c.itl_low1)} unit="t/s" note="the trustworthy tail metric" />
)}
<Tile label="Combined TTFT p50" value={f0(c.ttft_p50)} unit="ms" note="single-stream, batch = 1" />
</div>
)}
{caveats.length > 0 && (
<div className="flex gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex flex-col gap-1.5">
<span className="font-medium text-amber-800 dark:text-amber-200">Read these first</span>
{caveats.map((x) => (
<p key={x} className="text-foreground/80">
{x}
</p>
))}
</div>
</div>
)}
{sum.single.length > 0 && (
<Section
title="Decode throughput by category"
intro={`Median per-pass decode t/s at batch = 1, ${sum.passes} passes per category. The vertical line is the weighted combined score.`}
>
<BarChart
axisLabel="Decode t/s (median)"
reference={c?.decode != null ? { value: c.decode, label: `combined ${f1(c.decode)}` } : null}
rows={sum.single.map((r) => ({
label: r.category,
value: r.decode_med,
valueLabel: f1(r.decode_med),
details: [
`decode ${f1(r.decode_med)} t/s`,
r.decode_iqr != null ? `IQR ${f1(r.decode_iqr)}` : "",
r.decode_cv != null ? `CV ${(r.decode_cv * 100).toFixed(1)}%` : "",
`${r.runs} passes`,
].filter(Boolean),
}))}
/>
<p className="text-xs text-muted-foreground">Hover a bar for its IQR and coefficient of variation. A high CV means the category&apos;s passes disagree, so read small differences there with care.</p>
</Section>
)}
{sum.single.length > 0 && !batched && sum.single.some((r) => r.itl_low1 != null && r.itl_high99 != null) && (
<Section
title="Inter-token latency range by category"
intro="Each bar spans the 1% low to the 99% high instantaneous token rate, with a tick at the median. Wide bars stutter; narrow bars feel smooth."
>
<BarChart
mode="range"
axisLabel="Instantaneous t/s"
rows={sum.single.map((r) => ({
label: r.category,
value: r.itl_med ?? null,
range: r.itl_low1 != null && r.itl_high99 != null ? [r.itl_low1, r.itl_high99] : null,
valueLabel: r.itl_low1 != null ? `${f1(r.itl_low1)} – ${f1(r.itl_high99)}${undersampled(sum, "single_stream", r.category, "itl_high99") ? "†" : ""}` : undefined,
details: [`1% low ${f1(r.itl_low1)} t/s`, `median ${f1(r.itl_med)} t/s`, `99% high ${f1(r.itl_high99)} t/s`],
}))}
/>
</Section>
)}
{sum.prefill.some((p) => !p.skipped) && (
<Section title="Prompt processing by input length" intro="Median prefill t/s (prompt tokens ÷ TTFT) at increasing input depth, cold prefix cache.">
<BarChart
axisLabel="Prefill t/s (median)"
rows={sum.prefill
.filter((p) => !p.skipped)
.map((p) => ({
label: `~${p.target_depth.toLocaleString("en-US")} tok`,
value: p.pp_med ?? null,
valueLabel: f0(p.pp_med),
details: [`prompt ${f0(p.prompt_tokens_med)} tokens`, `TTFT ${f0(p.ttft_p50)} ms`, `1% low ${f0(p.pp_low1)} · 99% high ${f0(p.pp_p99)} t/s`, `${p.pp_n ?? "?"} runs`],
}))}
/>
</Section>
)}
{sum.concurrency.length > 0 && (
<Section
title="Throughput under parallel load"
intro={`Aggregate t/s across all requests at each concurrency level${peak ? `; the knee is where the bars stop growing (peak at ${peak.level})` : ""}.`}
>
<BarChart
axisLabel="Aggregate t/s"
rows={sum.concurrency.map((x) => ({
label: `${x.level} parallel`,
value: x.aggregate_tps,
valueLabel: f1(x.aggregate_tps),
details: [`per request ${f1(x.decode_med)} t/s`, `TTFT p50 ${f0(x.ttft_p50)} ms · p99 ${f0(x.ttft_p99)} ms`, `${x.ok}/${x.requests} requests ok`],
}))}
/>
</Section>
)}
{run.resources && (
<Section title="Resources" intro="What the server used while BetterBench measured it.">
<BenchmarkResources stats={run.resources} />
</Section>
)}
<Section title="Full numbers">
{sum.single.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Category</TableHead>
<TableHead className="text-right">Passes</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="text-right">TTFT p99</TableHead>
{batched ? (
<>
<TableHead className="text-right">Update p50</TableHead>
<TableHead className="text-right">Update p99</TableHead>
<TableHead className="text-right">Tok/update</TableHead>
</>
) : (
<>
<TableHead className="text-right">ITL 1% low</TableHead>
<TableHead className="text-right">ITL med</TableHead>
<TableHead className="text-right">ITL 99% high</TableHead>
</>
)}
<TableHead className="text-right">Decode med</TableHead>
<TableHead className="text-right">±IQR</TableHead>
<TableHead className="pr-3 text-right">CV</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.single.map((r) => (
<TableRow key={r.category}>
<TableCell className="pl-3">{r.category}</TableCell>
<TableCell className="text-right">{r.runs}</TableCell>
<TableCell className="text-right">{f1(r.ttft_p50)}</TableCell>
<TableCell className="text-right">
<Gated v={r.ttft_p99} sum={sum} section="single_stream" k={r.category} metric="ttft_p99" />
</TableCell>
{batched ? (
<>
<TableCell className="text-right">{f1(r.update_p50)}</TableCell>
<TableCell className="text-right">
<Gated v={r.update_p99} sum={sum} section="single_stream" k={r.category} metric="update_p99" />
</TableCell>
<TableCell className="text-right">{r.tok_per_update != null ? r.tok_per_update.toFixed(2) : "—"}</TableCell>
</>
) : (
<>
<TableCell className="text-right">{f1(r.itl_low1)}</TableCell>
<TableCell className="text-right">{f1(r.itl_med)}</TableCell>
<TableCell className="text-right">
<Gated v={r.itl_high99} sum={sum} section="single_stream" k={r.category} metric="itl_high99" />
</TableCell>
</>
)}
<TableCell className="text-right font-medium">{f1(r.decode_med)}</TableCell>
<TableCell className="text-right">{f1(r.decode_iqr)}</TableCell>
<TableCell className="pr-3 text-right">{r.decode_cv != null ? `${(r.decode_cv * 100).toFixed(1)}%` : "—"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
<div className="grid gap-4 md:grid-cols-2">
{sum.concurrency.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Concurrency</TableHead>
<TableHead className="text-right">OK</TableHead>
<TableHead className="text-right">Aggregate t/s</TableHead>
<TableHead className="text-right">Decode med</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="pr-3 text-right">TTFT p99</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.concurrency.map((x) => (
<TableRow key={x.level}>
<TableCell className="pl-3">{x.level}</TableCell>
<TableCell className="text-right">
{x.ok}/{x.requests}
</TableCell>
<TableCell className="text-right font-medium">{f1(x.aggregate_tps)}</TableCell>
<TableCell className="text-right">{f1(x.decode_med)}</TableCell>
<TableCell className="text-right">{f1(x.ttft_p50)}</TableCell>
<TableCell className="pr-3 text-right">
<Gated v={x.ttft_p99} sum={sum} section="concurrency" k={x.level} metric="ttft_p99" />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
{sum.prefill.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Depth</TableHead>
<TableHead className="text-right">Prompt tok</TableHead>
<TableHead className="text-right">TTFT p50</TableHead>
<TableHead className="text-right">PP 1% low</TableHead>
<TableHead className="text-right">PP med</TableHead>
<TableHead className="pr-3 text-right">PP 99%</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.prefill.map((p) => (
<TableRow key={p.target_depth}>
<TableCell className="pl-3">~{p.target_depth.toLocaleString("en-US")}</TableCell>
{p.skipped ? (
<TableCell colSpan={5} className="pr-3 text-right text-muted-foreground">
skipped
</TableCell>
) : (
<>
<TableCell className="text-right">{f0(p.prompt_tokens_med)}</TableCell>
<TableCell className="text-right">{f1(p.ttft_p50)}</TableCell>
<TableCell className="text-right">{f1(p.pp_low1)}</TableCell>
<TableCell className="text-right font-medium">{f1(p.pp_med)}</TableCell>
<TableCell className="pr-3 text-right">
<Gated v={p.pp_p99} sum={sum} section="prefill" k={p.target_depth} metric="pp_p99" />
</TableCell>
</>
)}
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
{sum.reasoning && sum.reasoning.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<Table className="text-xs">
<TableHeader>
<TableRow>
<TableHead className="pl-3">Category</TableHead>
<TableHead className="text-right">Split known</TableHead>
<TableHead className="text-right">Reasoning share</TableHead>
<TableHead className="text-right">Never answered</TableHead>
<TableHead className="pr-3 text-right">Time to first answer p50</TableHead>
</TableRow>
</TableHeader>
<TableBody className="tabular-nums">
{sum.reasoning.map((x) => (
<TableRow key={x.category}>
<TableCell className="pl-3">{x.category}</TableCell>
<TableCell className="text-right">
{x.known}/{x.runs}
</TableCell>
<TableCell className="text-right">{x.reasoning_share != null ? `${Math.round(x.reasoning_share * 100)}%` : "unknown"}</TableCell>
<TableCell className="text-right">{x.never_answered}</TableCell>
<TableCell className="pr-3 text-right">{x.ttfa_p50 != null ? `${f0(x.ttfa_p50)} ms` : "unknown"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</Section>
<Section title="Method">
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
{reportMethod(sum).map((p) => (
<p key={p}>{p}</p>
))}
</div>
</Section>
<footer className="border-t pt-4 text-xs text-muted-foreground">
Generated by Kaname from a BetterBench {sum.betterbenchVersion} run{sum.corpusVersion ? ` on corpus v${sum.corpusVersion}` : ""}
{sum.corpusHash ? ` (corpus hash ${sum.corpusHash})` : ""}. Results are only comparable within a corpus version. Every figure comes from BetterBench&apos;s own report
functions; Kaname adds none.
</footer>
</article>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getBenchmark } from "@/lib/benchmarks";
import { BenchmarkDetail } from "./benchmark-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/benchmarks/[id]">): Promise<Metadata> {
const run = await getBenchmark((await params).id);
return { title: run ? `${run.label ?? run.snapshot.deploymentName} · Benchmark` : "Benchmark" };
}
export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
const run = await getBenchmark((await params).id);
if (!run) notFound();
return <BenchmarkDetail initial={JSON.parse(JSON.stringify(run))} />;
}
@@ -0,0 +1,257 @@
"use client";
import { CheckIcon, DownloadIcon, ExternalLinkIcon, EyeIcon, LoaderCircleIcon, SendIcon, Trash2Icon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
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 { Label } from "@/components/ui/label";
import type { L80Status, PayloadPreview, PublicationRow } from "@/lib/publications";
type Pub = Omit<PublicationRow, "createdAt" | "previewedAt" | "confirmedAt" | "publishedAt"> & {
createdAt: string;
previewedAt: string | null;
confirmedAt: string | null;
publishedAt: string | null;
};
const RETENTION_DAYS = 5;
const textareaClass =
"min-h-24 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
async function send(url: string, method: string, body?: unknown) {
const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Request failed (${res.status})`);
return res.ok ? json : null;
}
/**
* Publish to launch80 as a double opt-in, the way the L80 docs describe it: first a dry run that
* builds the exact payload (nothing is sent), then an explicit confirmation that publishes that file.
*/
export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: string; defaultTitle: string; defaultSummary: string }) {
const [status, setStatus] = useState<L80Status>(null);
const [pubs, setPubs] = useState<Pub[] | null>(null);
const [title, setTitle] = useState(defaultTitle.slice(0, 120));
const [summary, setSummary] = useState(defaultSummary.slice(0, 600));
const [preview, setPreview] = useState<{ id: string; data: PayloadPreview | null } | null>(null);
const [ack, setAck] = useState(false);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
const res = await fetch(`/api/benchmarks/${runId}/publications`, { cache: "no-store" }).catch(() => null);
if (!res?.ok) return;
const json = (await res.json()) as { status: L80Status; publications: Pub[] };
setStatus(json.status);
setPubs(json.publications);
}, [runId]);
const current = pubs?.find((p) => p.state !== "published") ?? null;
const pending = !!pubs?.some((p) => p.state === "preview" || p.state === "publish");
useEffect(() => {
const first = setTimeout(load, 0);
const t = setInterval(load, pending ? 1_500 : 20_000);
return () => {
clearTimeout(first);
clearInterval(t);
};
}, [load, pending]);
// Load what the previewed payload contains once its preview is ready.
const previewId = current?.state === "previewed" ? current.id : null;
useEffect(() => {
if (!previewId || preview?.id === previewId) return;
let stop = false;
void fetch(`/api/benchmarks/${runId}/publications/${previewId}`, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((j) => !stop && setPreview({ id: previewId, data: j?.preview ?? null }));
return () => {
stop = true;
};
}, [previewId, preview?.id, runId]);
async function prepare() {
setBusy(true);
setAck(false);
try {
if (await send(`/api/benchmarks/${runId}/publications`, "POST", { title: title.trim() || null, summary: summary.trim() || null })) await load();
} finally {
setBusy(false);
}
}
async function publish(id: string) {
setBusy(true);
try {
if (await send(`/api/benchmarks/${runId}/publications/${id}`, "POST", { confirm: true })) await load();
} finally {
setBusy(false);
}
}
async function discard(id: string) {
const res = await fetch(`/api/benchmarks/${runId}/publications/${id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not discard (${res.status})`);
setPreview(null);
setAck(false);
await load();
}
const published = pubs?.filter((p) => p.state === "published") ?? [];
const p = preview?.id === current?.id ? preview?.data : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<SendIcon className="size-4 text-muted-foreground" />
Publish to launch80
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{pubs === null ? (
<p className="text-xs text-muted-foreground">Loading…</p>
) : !status?.version ? (
<p className="text-xs text-muted-foreground">The L80 CLI isn&apos;t available in this installation, so runs can&apos;t be published.</p>
) : (
<>
{published.map((x) => (
<div key={x.id} className="flex flex-col gap-1 rounded-lg bg-emerald-500/10 px-3 py-2">
<span className="flex items-center gap-1.5 text-xs font-medium text-emerald-700 dark:text-emerald-300">
<CheckIcon className="size-3.5" />
Published <LocalTime value={x.publishedAt} />
</span>
<span className="flex items-center gap-1">
<a href={x.url ?? "#"} target="_blank" rel="noreferrer" className="min-w-0 flex-1 truncate font-mono text-xs underline">
{x.url}
</a>
<CopyButton value={x.url ?? ""} label="Copy link" />
</span>
<span className="text-[11px] text-muted-foreground">
Public until about <LocalTime value={x.publishedAt ? new Date(new Date(x.publishedAt).getTime() + RETENTION_DAYS * 86_400_000).toISOString() : null} />
{x.confirmedBy && ` · confirmed by ${x.confirmedBy}`}
</span>
</div>
))}
{!current && (
<>
<p className="text-xs text-muted-foreground">
Step 1 of 2: prepare a preview. The L80 CLI builds the exact page payload from this run&apos;s results.json (endpoint and host removed). Nothing is sent yet.
</p>
<div className="flex flex-col gap-1.5">
<Label htmlFor="pub-title">Page title</Label>
<Input id="pub-title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={120} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="pub-summary">Summary</Label>
<textarea id="pub-summary" value={summary} onChange={(e) => setSummary(e.target.value)} maxLength={600} className={textareaClass} />
<span className="text-right text-[11px] text-muted-foreground tabular-nums">{summary.length}/600</span>
</div>
<Button variant="outline" onClick={prepare} disabled={busy}>
<EyeIcon />
Prepare preview
</Button>
</>
)}
{current?.state === "preview" && (
<p className="flex items-center gap-2 text-xs text-muted-foreground">
<LoaderCircleIcon className="size-3.5 animate-spin" />
Building the payload (dry run)…
</p>
)}
{current?.state === "previewed" && (
<div className="flex flex-col gap-3">
<p className="text-xs text-muted-foreground">Step 2 of 2: check what would be published.</p>
{p ? (
<dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 rounded-lg bg-muted/50 px-3 py-2 text-xs">
<dt className="text-muted-foreground">Template</dt>
<dd className="font-mono">{p.template}</dd>
<dt className="text-muted-foreground">Size</dt>
<dd>{(p.bytes / 1024).toFixed(1)} KB</dd>
<dt className="text-muted-foreground">Title</dt>
<dd>{p.title ?? <span className="text-muted-foreground">model name</span>}</dd>
<dt className="text-muted-foreground">Summary</dt>
<dd className="line-clamp-4">{p.summary ?? <span className="text-muted-foreground">none</span>}</dd>
<dt className="text-muted-foreground">Model</dt>
<dd className="font-mono break-all">{p.model}</dd>
<dt className="text-muted-foreground">Notes</dt>
<dd className="flex flex-wrap gap-1">
{Object.entries(p.notes).map(([k, v]) => (
<span key={k} className="rounded bg-background px-1 font-mono text-[11px]">
{k}={v}
</span>
))}
</dd>
<dt className="text-muted-foreground">Data</dt>
<dd>{p.phases.join(", ")} · every raw sample</dd>
<dt className="text-muted-foreground">Removed</dt>
<dd className={p.hostRemoved ? "" : "text-destructive"}>{p.hostRemoved ? "endpoint URL and host name" : "endpoint or host still present!"}</dd>
</dl>
) : (
<p className="text-xs text-muted-foreground">Reading the payload…</p>
)}
<a href={`/api/benchmarks/${runId}/publications/${current.id}/payload`} className={buttonVariants({ variant: "ghost", size: "sm" }) + " self-start"}>
<DownloadIcon />
Exact payload (JSON)
</a>
<ul className="list-disc pl-4 text-xs text-muted-foreground">
<li>Public: anyone with the link can read it.</li>
<li>Immutable: to change it, publish again.</li>
<li>Unindexed, self-contained, marked &ldquo;self-reported, not verified by launch80&rdquo;.</li>
<li>Removed after {RETENTION_DAYS} days. Counts against your token&apos;s 10 publishes per day.</li>
</ul>
{!status.tokenSet && (
<p className="text-xs text-amber-700 dark:text-amber-300">No launch80 token: set L80_TOKEN (launch80 Supporter) for the worker to publish.</p>
)}
<label className="flex cursor-pointer items-start gap-2 text-xs">
<Checkbox checked={ack} onCheckedChange={(v) => setAck(v === true)} className="mt-0.5" disabled={!status.tokenSet || !p?.hostRemoved} />
<span>I want this run published as a public page on launch80.com, exactly as previewed.</span>
</label>
<div className="flex flex-wrap gap-2">
<Button onClick={() => publish(current.id)} disabled={!ack || busy || !status.tokenSet || !p?.hostRemoved}>
<SendIcon />
Publish
</Button>
<Button variant="ghost" onClick={() => discard(current.id)} disabled={busy}>
<Trash2Icon />
Discard
</Button>
</div>
</div>
)}
{current?.state === "publish" && (
<p className="flex items-center gap-2 text-xs text-muted-foreground">
<LoaderCircleIcon className="size-3.5 animate-spin" />
Publishing…
</p>
)}
{current?.state === "failed" && (
<div className="flex flex-col gap-2">
<pre className="rounded-lg bg-destructive/10 px-3 py-2 font-sans text-xs break-words whitespace-pre-wrap text-destructive">{current.error}</pre>
<Button variant="outline" size="sm" className="self-start" onClick={() => discard(current.id)}>
Start over
</Button>
</div>
)}
{published.length > 0 && !current && (
<a href="https://launch80.com" target="_blank" rel="noreferrer" className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
launch80.com <ExternalLinkIcon className="size-3" />
</a>
)}
</>
)}
</CardContent>
</Card>
);
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string, body?: unknown): Promise<boolean> {
const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
if (res.ok) return true;
const json = await res.json().catch(() => ({}));
toast.error(json.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const cancelBenchmark = (id: string) => call(`/api/benchmarks/${id}/cancel`, "POST");
export const deleteBenchmark = (id: string) => call(`/api/benchmarks/${id}`, "DELETE");
export const renameBenchmark = (id: string, label: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { label });
+151
View File
@@ -0,0 +1,151 @@
"use client";
import { GaugeIcon, GitCompareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { LocalTime } from "@/components/local-time";
import { buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { BenchmarkRow } from "@/lib/benchmarks";
import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
import { cn } from "@/lib/utils";
export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
createdAt: string;
startedAt: string | null;
finishedAt: string | null;
cancelRequestedAt: string | null;
};
const MAX_COMPARE = 16;
const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
/** All runs with their headline numbers; polls while something is queued or running. */
export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; compact?: boolean }) {
const [rows, setRows] = useState(initial);
const [selected, setSelected] = useState<string[]>([]);
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
useEffect(() => {
if (!busy || compact) return;
const t = setInterval(async () => {
const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}, 3_000);
return () => clearInterval(t);
}, [busy, compact]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<GaugeIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
No benchmarks yet. Open a running{" "}
<Link href="/deployments" className="underline">
deployment
</Link>{" "}
and start one there.
</p>
</Card>
);
}
const toggle = (id: string) => setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : s.length < MAX_COMPARE ? [...s, id] : s));
const comparable = rows.filter((r) => r.state === "completed");
return (
<div className="flex flex-col gap-3">
{!compact && comparable.length > 1 && (
<div className="flex items-center justify-between gap-2 text-sm">
<span className="text-muted-foreground">{selected.length === 0 ? "Select completed runs to compare them." : `${selected.length} selected (up to ${MAX_COMPARE}).`}</span>
<Link
href={`/benchmarks/compare?ids=${selected.join(",")}`}
className={cn(buttonVariants({ size: "sm" }), selected.length < 2 && "pointer-events-none opacity-50")}
aria-disabled={selected.length < 2}
>
<GitCompareIcon />
Compare
</Link>
</div>
)}
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
{!compact && <TableHead className="w-8" />}
<TableHead>Run</TableHead>
<TableHead className="hidden lg:table-cell">Settings</TableHead>
<TableHead className="text-right" title="Weighted single-stream decode speed">
Decode t/s
</TableHead>
<TableHead className="text-right" title="Median time to first token">
TTFT
</TableHead>
<TableHead className="hidden text-right md:table-cell" title="Prompt processing at the deepest measured input">
Prefill t/s
</TableHead>
<TableHead className="hidden text-right md:table-cell" title="Best aggregate throughput under parallel load">
Peak t/s
</TableHead>
<TableHead className="w-28">State</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((r) => {
const h = headline(r.summary);
const s = r.snapshot;
return (
<TableRow key={r.id} data-state={selected.includes(r.id) ? "selected" : undefined}>
{!compact && (
<TableCell>
<Checkbox
checked={selected.includes(r.id)}
disabled={r.state !== "completed"}
onCheckedChange={() => toggle(r.id)}
aria-label={`Select ${r.label ?? s.deploymentName} for comparison`}
/>
</TableCell>
)}
<TableCell className="whitespace-normal">
<Link href={`/benchmarks/${r.id}`} className="font-medium hover:underline">
{r.label ?? s.deploymentName}
</Link>
<div className="text-xs text-muted-foreground">
{r.label && `${s.deploymentName} · `}
{s.repoId} · <LocalTime value={r.createdAt} />
</div>
</TableCell>
<TableCell className="hidden max-w-md whitespace-normal lg:table-cell">
<div className="flex flex-wrap gap-1">
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">{s.runtimeName}</span>
{configChips(s).map((c) => (
<span key={c} className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground">
{c}
</span>
))}
</div>
<div className="mt-0.5 text-[11px] text-muted-foreground">{describeSettings(r.settings)}</div>
</TableCell>
<TableCell className="text-right font-medium tabular-nums">{fmt(h.decode)}</TableCell>
<TableCell className="text-right tabular-nums">{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}</TableCell>
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.prefill ? `at ${h.prefill.depth} tokens` : undefined}>
{fmt(h.prefill?.tps, 0)}
</TableCell>
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.peak ? `at ${h.peak.level} parallel` : undefined}>
{fmt(h.peak?.tps)}
</TableCell>
<TableCell>
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
</div>
);
}
+187
View File
@@ -0,0 +1,187 @@
import type { Metadata } from "next";
import Link from "next/link";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { getBenchmarks } from "@/lib/benchmarks";
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Compare benchmarks" };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null) => number | null };
/** Differences smaller than this are shown without color: below what a single run can resolve. */
const NOISE_PCT = 2;
function Delta({ v, base, higherIsBetter }: { v: number | null; base: number | null; higherIsBetter: boolean }) {
const d = deltaPct(v, base);
if (d == null) return null;
const good = higherIsBetter ? d > 0 : d < 0;
return (
<span
className={cn(
"ml-1.5 text-[11px] tabular-nums",
Math.abs(d) < NOISE_PCT ? "text-muted-foreground" : good ? "text-emerald-600 dark:text-emerald-400" : "text-destructive",
)}
>
{d > 0 ? "+" : ""}
{d.toFixed(1)}%
</span>
);
}
export default async function ComparePage({ searchParams }: PageProps<"/benchmarks/compare">) {
const { ids } = await searchParams;
const runs = await getBenchmarks(
String(ids ?? "")
.split(",")
.filter(Boolean)
.slice(0, 16),
);
if (runs.length < 2) {
return (
<p className="text-sm text-muted-foreground">
Pick at least two completed runs on the{" "}
<Link href="/benchmarks" className="underline">
Benchmarks
</Link>{" "}
page.
</p>
);
}
const sums = runs.map((r) => r.summary);
const depths = [...new Set(sums.flatMap((s) => s?.prefill.filter((p) => !p.skipped).map((p) => p.target_depth) ?? []))].sort((a, b) => a - b);
const levels = [...new Set(sums.flatMap((s) => s?.concurrency.map((c) => c.level) ?? []))].sort((a, b) => a - b);
const categories = [...new Set(sums.flatMap((s) => s?.single.map((c) => c.category) ?? []))];
const groups: { group: string; rows: Metric[] }[] = [
{
group: "Headline",
rows: [
{ label: "Decode (weighted)", unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => headline(s).decode },
{ label: "Time to first token", unit: "ms", higherIsBetter: false, digits: 0, get: (s) => headline(s).ttftMs },
],
},
{
group: "Decode per category",
rows: categories.map((c) => ({ label: c, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.single.find((x) => x.category === c)?.decode_med ?? null })),
},
{
group: "Prompt processing",
rows: depths.map((d) => ({
label: `${d.toLocaleString()} tokens`,
unit: "t/s",
higherIsBetter: true,
digits: 0,
get: (s) => s?.prefill.find((p) => p.target_depth === d && !p.skipped)?.pp_med ?? null,
})),
},
{
group: "Parallel requests (total)",
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
},
];
const metrics = groups.filter((g) => g.rows.length > 0);
const configRows = CONFIG_ROWS.map((row) => ({ row, values: runs.map((r) => row.value(r.snapshot)) })).filter((x) => x.values.some((v) => v != null));
const corpora = new Set(sums.map((s) => s?.corpusVersion).filter(Boolean));
const anyQuick = runs.some((r) => r.summary?.quick);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">Compare benchmarks</h1>
<p className="text-sm text-muted-foreground">
Differences are against the first run. Separate runs aren&apos;t paired in time, so differences below ~{NOISE_PCT}% are within normal noise.
</p>
{corpora.size > 1 && <p className="text-sm text-destructive">These runs used different prompt sets (corpus versions), so their numbers aren&apos;t comparable.</p>}
{anyQuick && <p className="text-sm text-amber-700 dark:text-amber-300">Some runs are quick runs (5 passes); their numbers are rough.</p>}
</div>
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-48" />
{runs.map((r, i) => (
<TableHead key={r.id} className="align-top whitespace-normal">
<Link href={`/benchmarks/${r.id}`} className="font-medium text-foreground hover:underline">
{r.label ?? r.snapshot.deploymentName}
</Link>
<div className="flex flex-wrap items-center gap-1 py-1 text-[11px] font-normal">
{i === 0 && <span className="rounded-4xl bg-primary px-1.5 text-primary-foreground">baseline</span>}
<BenchmarkStateBadge state={r.state} />
</div>
<div className="text-[11px] font-normal text-muted-foreground">{describeSettings(r.settings)}</div>
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Settings
</TableCell>
</TableRow>
{configRows.map(({ row, values }) => {
const differs = new Set(values.map((v) => v ?? "")).size > 1;
return (
<TableRow key={row.key} className={cn(differs && "bg-amber-500/5")}>
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{row.label}</TableCell>
{values.map((v, i) => (
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
{v ?? <span className="text-muted-foreground">default</span>}
</TableCell>
))}
</TableRow>
);
})}
{metrics.map((g) => (
<MetricGroup key={g.group} group={g.group} rows={g.rows} sums={sums} cols={runs.length} />
))}
</TableBody>
</Table>
</Card>
</div>
);
}
function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[]; sums: (BenchmarkSummary | null)[]; cols: number }) {
return (
<>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={cols + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
{group}
</TableCell>
</TableRow>
{rows.map((m) => {
const vals = sums.map((s) => m.get(s));
const present = vals.filter((v): v is number => v != null);
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
return (
<TableRow key={m.label}>
<TableCell className="text-xs">{m.label}</TableCell>
{vals.map((v, i) => (
<TableCell key={i} className="tabular-nums whitespace-nowrap">
{v == null ? (
<span className="text-muted-foreground">–</span>
) : (
<>
<span className={cn(v === best && "font-semibold")}>
{v.toFixed(m.digits)} <span className="text-[11px] text-muted-foreground">{m.unit}</span>
</span>
{i > 0 && <Delta v={v} base={vals[0]} higherIsBetter={m.higherIsBetter} />}
</>
)}
</TableCell>
))}
</TableRow>
);
})}
</>
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { listBenchmarks } from "@/lib/benchmarks";
import { BenchmarkList } from "./benchmark-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Benchmarks" };
export default async function BenchmarksPage() {
const rows = await listBenchmarks();
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">Benchmarks</h1>
<p className="text-sm text-muted-foreground">
BetterBench runs against your deployments. Start one from a running deployment; select runs to compare their settings and numbers.
</p>
</div>
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
@@ -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 <SweepDetail initial={JSON.parse(JSON.stringify(data))} />;
}
@@ -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<SweepVariant["state"], string> = {
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) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
);
const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length;
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex flex-col gap-1">
<h1 className="flex items-center gap-2 text-xl font-semibold">
<Grid3x3Icon className="size-5 text-muted-foreground" />
{sweep.label ?? `Sweep of ${sweep.base.name}`}
</h1>
<p className="text-sm text-muted-foreground">
{sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "}
{sweep.baseDeploymentId ? (
<Link href={`/deployments/${sweep.baseDeploymentId}`} className="underline">
{sweep.base.name}
</Link>
) : (
sweep.base.name
)}
</p>
</div>
<div className="flex items-center gap-2">
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
{runIds.length >= 2 && (
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
<GitCompareIcon />
Compare in detail
</Link>
)}
{active ? (
<Button variant="outline" size="sm" disabled={busy || !!sweep.cancelRequestedAt} onClick={() => act(`/api/sweeps/${sweep.id}/cancel`, "POST", () => router.refresh())}>
<SquareIcon />
Cancel
</Button>
) : (
<Button variant="outline" size="sm" disabled={busy} onClick={() => act(`/api/sweeps/${sweep.id}`, "DELETE", () => router.push("/benchmarks"))}>
<Trash2Icon />
Delete
</Button>
)}
</div>
</div>
{active && (
<p className="text-sm text-muted-foreground">
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
</p>
)}
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
{finished.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Generation speed by variant</CardTitle>
<CardDescription>Single-stream decode, tokens per second (BetterBench combined score). Higher is better.</CardDescription>
</CardHeader>
<CardContent>
<BarChart
axisLabel="Decode t/s"
rows={finished.map((r) => ({
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),
}))}
/>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Variants</CardTitle>
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
</CardHeader>
<CardContent className="overflow-x-auto px-0">
<table className="w-full text-sm">
<thead className="text-xs text-muted-foreground">
<tr className="border-b">
<th className="px-3 py-2 text-left font-medium">Variant</th>
<th className="px-3 py-2 text-left font-medium">State</th>
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.v.index} className="border-b last:border-0">
<td className="px-3 py-2 font-mono text-xs">
{r.v.runId ? (
<Link href={`/benchmarks/${r.v.runId}`} className="underline-offset-2 hover:underline">
{r.v.label}
</Link>
) : (
r.v.label
)}
</td>
<td className="px-3 py-2 text-xs text-muted-foreground" title={r.v.error ?? r.run?.error ?? undefined}>
{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)}` : ""}
</td>
{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`)}
</tr>
))}
</tbody>
</table>
</CardContent>
</Card>
</div>
);
}
@@ -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 (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">New sweep</h1>
<p className="max-w-3xl text-sm text-muted-foreground">
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.
</p>
</div>
<SweepForm bases={bases} initialBaseId={typeof deployment === "string" ? deployment : undefined} />
</div>
);
}
@@ -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<string, unknown> = {
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<Param[]>([{ key: "contextSize", text: "", files: [] }]);
const [label, setLabel] = useState("");
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [busy, setBusy] = useState(false);
const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text));
let preview: { variants: ReturnType<typeof expandSweep> | 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<Param>) => 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 <p className="text-sm text-muted-foreground">Create a deployment first; a sweep varies its settings.</p>;
return (
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Base deployment</CardTitle>
<CardDescription>Every variant starts from its settings. It doesn&apos;t need to be running.</CardDescription>
</CardHeader>
<CardContent>
<NativeSelect value={baseId} onChange={(e) => setBaseId(e.target.value)} aria-label="Base deployment">
{bases.map((b) => (
<option key={b.id} value={b.id}>
{b.name} · {b.repoId}
</option>
))}
</NativeSelect>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>What to vary</CardTitle>
<CardDescription>One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}).</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{base &&
params.map((p, i) => {
const def = keys.find((k) => k.key === p.key);
return (
<div key={i} className="flex flex-col gap-2 rounded-lg border px-3 py-3">
<div className="flex items-center gap-2">
<NativeSelect value={p.key} onChange={(e) => 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) => (
<option key={k.key} value={k.key}>
{k.label}
</option>
))}
</NativeSelect>
{params.length > 1 && (
<Button variant="ghost" size="icon-sm" aria-label="Remove setting" onClick={() => setParams((ps) => ps.filter((_, j) => j !== i))}>
<XIcon />
</Button>
)}
</div>
{p.key === "modelFile" ? (
<div className="flex flex-col gap-1">
{base.ggufFiles.map((f) => (
<label key={f} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={p.files.includes(f)} onCheckedChange={(v) => setParam(i, { files: v ? [...p.files, f] : p.files.filter((x) => x !== f) })} />
<span className="font-mono text-xs">{quantGroup(f) ?? f}</span>
</label>
))}
{base.ggufFiles.length < 2 && <p className="text-xs text-muted-foreground">Only one GGUF file is downloaded; download more quants to compare them.</p>}
</div>
) : (
<Input value={p.text} onChange={(e) => setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" />
)}
<p className="text-xs text-muted-foreground">Base value: {currentValue(base, p.key)}</p>
</div>
);
})}
{params.length < 2 && base && (
<Button
variant="outline"
size="sm"
className="self-start"
onClick={() => setParams((ps) => [...ps, { key: keys.find((k) => !ps.some((q) => q.key === k.key))?.key ?? "threads", text: "", files: [] }])}
>
<PlusIcon />
Vary a second setting
</Button>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Benchmark per variant</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && <Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />}
</div>
<div className="flex flex-wrap gap-4">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} />
{p.label}
</label>
))}
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="sw-label">Label</Label>
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
</div>
</CardContent>
</Card>
</div>
<Card className="lg:sticky lg:top-4">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<Grid3x3Icon className="size-4 text-muted-foreground" />
{preview.variants ? `${preview.variants.length} variants` : "Variants"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{preview.error ? (
<p className="text-xs text-muted-foreground">{preview.error}</p>
) : (
<ol className="flex flex-col gap-1">
{preview.variants?.map((v) => (
<li key={v.index} className="flex gap-2 text-xs">
<span className="w-5 text-right text-muted-foreground tabular-nums">{v.index + 1}</span>
<span className="font-mono">{v.label}</span>
</li>
))}
</ol>
)}
<p className="text-xs text-muted-foreground">
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."}
</p>
<Button onClick={submit} disabled={!preview.variants || busy || phases.length === 0}>
<Grid3x3Icon />
Start sweep
</Button>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,249 @@
"use client";
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, 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 }[] = [
{ id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
{ id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
];
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<Mode>("run");
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [label, setLabel] = useState("");
const [busy, setBusy] = useState(false);
const [runs, setRuns] = useState(initial);
const [peers, setPeers] = useState<Peer[] | null>(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(() => {
const t = setInterval(
async () => {
const res = await fetch(`/api/benchmarks?deployment=${deploymentId}`, { cache: "no-store" }).catch(() => null);
if (res?.ok) setRuns(await res.json());
},
active ? 3_000 : 15_000,
);
return () => clearInterval(t);
}, [deploymentId, active]);
// 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<string, unknown>) {
setBusy(true);
try {
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}`);
} finally {
setBusy(false);
}
}
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 (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<GaugeIcon className="size-4 text-muted-foreground" />
Benchmark
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
<div className="inline-flex self-start rounded-lg bg-muted p-1" role="tablist">
{TABS.map((t) => (
<button
key={t.id}
type="button"
role="tab"
aria-selected={tab === t.id}
onClick={() => setTab(t.id)}
className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
>
<t.icon className="size-3.5" />
{t.label}
</button>
))}
</div>
{tab === "run" && (
<>
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && (
<Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
)}
</div>
<div className="flex flex-col gap-1.5">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{p.label}</span>
<span className="text-xs text-muted-foreground">{p.hint}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button
onClick={() =>
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
}
disabled={!running || busy || phases.length === 0}
>
<GaugeIcon />
Run benchmark
</Button>
<p className="text-xs text-muted-foreground">
{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."}
</p>
</>
)}
{tab === "ab" && (
<>
<p className="text-xs text-muted-foreground">
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.
</p>
{peers === null ? (
<p className="text-xs text-muted-foreground">Loading…</p>
) : peers.length === 0 ? (
<p className="text-xs text-muted-foreground">
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.
</p>
) : (
<>
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Deployment B">
<option value="">Choose B…</option>
{peers.map((p) => (
<option key={p.id} value={p.id}>
{p.name} {p.state !== "running" ? `(${p.state})` : ""}
</option>
))}
</NativeSelect>
{peer && peer.state !== "running" && (
<p className="text-xs text-amber-700 dark:text-amber-300">
{peer.name} isn&apos;t running.{" "}
<Link href={`/deployments/${peer.id}`} className="underline">
Start it
</Link>{" "}
first.
</p>
)}
<div className="grid grid-cols-2 gap-2">
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Target precision (±%)</span>
<Input value={mde} onChange={(e) => setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
</label>
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Max pairs</span>
<Input value={maxPairs} onChange={(e) => setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</label>
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
<Button
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
disabled={!running || busy || !peer || peer.state !== "running"}
>
<GitCompareArrowsIcon />
Start A/B
</Button>
</>
)}
{!running && <p className="text-xs text-muted-foreground">Start this deployment (A) first.</p>}
</>
)}
{tab === "sweep" && (
<>
<p className="text-xs text-muted-foreground">
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&apos;t need to run.
</p>
<Link href={`/benchmarks/sweeps/new?deployment=${deploymentId}`} className={buttonVariants()}>
<Grid3x3Icon />
Set up a sweep
</Link>
</>
)}
{runs.length > 0 && (
<div className="flex flex-col gap-1 border-t pt-3">
{runs.slice(0, 5).map((r) => {
const h = headline(r.summary);
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
<span className="min-w-0 truncate">
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
{r.label ?? new Date(r.createdAt).toLocaleString()}
</span>
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</span>
</Link>
);
})}
<Link href="/benchmarks" className="self-start px-1.5 text-xs text-muted-foreground hover:text-foreground">
All benchmarks →
</Link>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,373 @@
"use client";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LiveLog } from "@/components/live-log";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
import type { ListRow } from "../../benchmarks/benchmark-list";
import { BenchmarkCard } from "./benchmark-card";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment; benchmarks: ListRow[] }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
const hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{webUi && (
<a
href={webUi}
target="_blank"
rel="noreferrer"
className={cn(buttonVariants({ variant: "outline" }), d.state !== "running" && "pointer-events-none opacity-50")}
aria-disabled={d.state !== "running"}
>
<ExternalLinkIcon />
Web UI
</a>
)}
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<LiveLog url={`/api/deployments/${d.id}/logs`} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<BenchmarkCard deploymentId={d.id} modelId={d.modelId} running={d.state === "running"} initial={benchmarks} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Runs on</dt>
<dd>
{ACCELERATOR_LABEL[d.accelerator]}
{d.accelerator === "nvidia" && ` · ${d.options.gpus?.length ? `${d.options.gpus.length} selected GPU${d.options.gpus.length === 1 ? "" : "s"}` : "all GPUs"}`}
</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { listBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const { id } = await params;
const [d, runs] = await Promise.all([getDeployment(id), listBenchmarks({ deploymentId: id })]);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} benchmarks={JSON.parse(JSON.stringify(runs))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,107 @@
"use client";
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
const isActive = (r: Row) => r.desiredState === "running" || r.state === "starting" || r.state === "running" || r.state === "stopping";
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
const [rows, setRows] = useState(initial);
const hostname = useHostname();
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
async function reload() {
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
return (
<Card className="items-center gap-3 py-10 text-center">
<RocketIcon className="size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
return (
<div className="grid gap-3 md:grid-cols-2">
{rows.map((r) => {
const file = r.options.modelFile ? (quantGroup(r.options.modelFile) ?? r.options.modelFile) : null;
const loadSecs = r.readyAt && r.startedAt ? (new Date(r.readyAt).getTime() - new Date(r.startedAt).getTime()) / 1000 : null;
return (
<Card key={r.id} className="gap-3 px-4 py-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-0.5">
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
{r.name}
</Link>
<span className="truncate text-xs text-muted-foreground">
{r.repoId}
{file && ` · ${file}`}
{r.options.mmproj && " · vision"}
{r.options.draftFile && " · MTP/draft"}
</span>
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
</div>
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">
{r.state === "running" && r.stats
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
: r.state === "failed"
? (r.error?.split("\n")[0] ?? "failed")
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
</span>
<span className="flex items-center gap-1.5">
{r.state === "running" && webUiUrl(r, hostname) && (
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
<ExternalLinkIcon />
Web UI
</a>
)}
{isActive(r) ? (
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
<SquareIcon />
Stop
</Button>
) : (
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
<PlayIcon />
Start
</Button>
)}
</span>
</div>
</Card>
);
})}
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs, accelerator: r.accelerator })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures, nvidia: !!docker.nvidia, gpus: docker.gpus ?? [] } : null,
apiKeyCount: keys.length,
};
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
+36 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
@@ -10,7 +10,7 @@ import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -19,6 +19,7 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -180,6 +181,9 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -195,6 +199,23 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
@@ -236,6 +257,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
);
})}
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
}
+8 -2
View File
@@ -1,10 +1,16 @@
import type { Metadata } from "next";
import { getRecommendedRoles } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
import { SpeedLimit } from "./speed-limit";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() {
return <RecommendedSettings initial={await getRecommendedRoles()} />;
return (
<div className="flex flex-col gap-4">
<SpeedLimit initial={await getDownloadSpeedLimit()} />
<RecommendedSettings initial={await getRecommendedRoles()} />
</div>
);
}
@@ -0,0 +1,86 @@
"use client";
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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const MB = 1_000_000;
/** Download speed limit in MB/s; empty means no limit. Applies to running downloads within seconds. */
export function SpeedLimit({ initial }: { initial: number | null }) {
const [saved, setSaved] = useState(initial);
const [text, setText] = useState(initial ? String(initial / MB) : "");
const [busy, setBusy] = useState(false);
const value = text.trim() === "" ? null : Number(text.replace(",", "."));
const invalid = value != null && !(value >= 0.1);
const dirty = value !== (saved == null ? null : saved / MB);
async function save(next: number | null) {
setBusy(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ maxBytesPerSecond: next == null ? null : Math.round(next * MB) }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
setSaved(body.maxBytesPerSecond);
setText(body.maxBytesPerSecond ? String(body.maxBytesPerSecond / MB) : "");
toast.success(body.maxBytesPerSecond ? `Downloads limited to ${body.maxBytesPerSecond / MB} MB/s` : "Download speed is no longer limited");
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Speed limit</CardTitle>
<CardDescription>
Caps the total download speed from Hugging Face, e.g. to leave bandwidth for others. It also applies to downloads that are already running. Leave empty for
no limit.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<form
className="flex items-end gap-2"
onSubmit={(e) => {
e.preventDefault();
if (!invalid) void save(value);
}}
>
<div className="flex flex-col gap-1.5">
<Label htmlFor="speed-limit">Maximum speed (MB/s)</Label>
<Input
id="speed-limit"
value={text}
onChange={(e) => setText(e.target.value.replace(/[^\d.,]/g, ""))}
inputMode="decimal"
placeholder="No limit"
className="w-40"
aria-invalid={invalid}
/>
</div>
<Button type="submit" disabled={busy || invalid || !dirty}>
Save
</Button>
{saved != null && (
<Button type="button" variant="ghost" disabled={busy} onClick={() => void save(null)}>
Remove limit
</Button>
)}
</form>
<p className="text-xs text-muted-foreground">
{invalid
? "At least 0.1 MB/s."
: `1 MB/s ≈ 8 Mbit/s. hf has no speed option of its own, so Kaname pauses it whenever it gets ahead; short bursts above the limit are normal, the average holds.`}
</p>
</CardContent>
</Card>
);
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { BoxesIcon, DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
@@ -6,6 +6,7 @@ const SECTIONS = [
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
@@ -1,12 +1,15 @@
"use client";
import { useState } from "react";
import { ArgsEditor } from "@/components/args-editor";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { NativeSelect } from "@/components/ui/native-select";
import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { ACCELERATOR_DEVICES, ACCELERATOR_LABEL, formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
@@ -31,10 +34,11 @@ export function RuntimeForm({
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
const [accelerator, setAccelerator] = useState<RuntimeAccelerator>(initial.accelerator ?? "cpu");
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argsText, setArgsText] = useState((initial.extraArgs ?? []).join("\n"));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
@@ -48,10 +52,11 @@ export function RuntimeForm({
value = validateRuntime({
name,
engine,
accelerator,
image,
description,
env: parseEnvLines(envText),
extraArgs: argsText.split("\n"),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
@@ -112,36 +117,56 @@ export function RuntimeForm({
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-acc">Runs on</Label>
<NativeSelect
id="rt-acc"
value={accelerator}
onChange={(e) => {
const next = e.target.value as RuntimeAccelerator;
setAccelerator(next);
// Suggest the device nodes the accelerator needs.
if (!devicesText.trim()) setDevicesText(ACCELERATOR_DEVICES[next].join(", "));
}}
>
{RUNTIME_ACCELERATORS.map((a) => (
<option key={a} value={a}>
{ACCELERATOR_LABEL[a]}
</option>
))}
</NativeSelect>
<p className="text-xs text-muted-foreground">
{accelerator === "nvidia"
? "GPUs are requested from Docker (NVIDIA Container Toolkit on the host); each deployment picks which ones."
: accelerator === "dri"
? "Intel and AMD GPUs are passed in as /dev/dri (Vulkan, Intel SYCL, vLLM XPU). The image must be built for it."
: accelerator === "rocm"
? "AMD GPUs with ROCm: /dev/kfd and /dev/dri are passed in."
: "CPU and RAM only."}
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-desc">Description</Label>
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-args">Extra arguments</Label>
<textarea
id="rt-args"
value={argsText}
onChange={(e) => setArgsText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"--dtype=bfloat16"}
/>
<p className="text-xs text-muted-foreground">One per line, appended to the generated command.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Extra arguments</Label>
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
<p className="text-xs text-muted-foreground">Added to every deployment&apos;s command; a deployment can override them.</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
@@ -157,7 +182,7 @@ export function RuntimeForm({
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="/dev/dri (Intel/AMD GPUs, later)"
placeholder="/dev/dri, /dev/kfd"
/>
</div>
</div>
@@ -30,7 +30,7 @@ import {
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
@@ -63,6 +63,7 @@ async function send(url: string, method: string, body?: unknown): Promise<boolea
const toInput = (r: Runtime): RuntimeInput => ({
name: r.name,
engine: r.engine,
accelerator: r.accelerator,
image: r.image,
description: r.description,
env: r.env,
@@ -218,6 +219,24 @@ function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; wor
</dd>
<dt className="text-muted-foreground">Memory</dt>
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
<dt className="text-muted-foreground">GPUs</dt>
<dd className="flex flex-col gap-0.5">
{docker.gpus && docker.gpus.length > 0 ? (
docker.gpus.map((g) => (
<span key={g.uuid}>
{g.index}: {g.name} <span className="text-muted-foreground">· {formatBytes(g.memoryMb * 2 ** 20)} · driver {g.driver}</span>
</span>
))
) : docker.nvidia ? (
<span className={cn(docker.gpuError && "text-amber-700 dark:text-amber-300")}>
{docker.gpuError ? `NVIDIA runtime found, but listing GPUs failed: ${docker.gpuError}` : "NVIDIA runtime found, no GPUs listed."}
</span>
) : (
<span className="text-muted-foreground">
No NVIDIA GPUs (no NVIDIA runtime in Docker). Intel/AMD GPUs aren&apos;t listed; pass /dev/dri to a runtime to use them.
</span>
)}
</dd>
<dt className="text-muted-foreground">Network</dt>
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
@@ -290,6 +309,9 @@ function RuntimeRow({
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{r.name}</span>
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
{r.accelerator !== "cpu" && (
<span className="rounded-md border border-emerald-500/30 px-1.5 text-xs text-emerald-700 dark:text-emerald-300">{ACCELERATOR_LABEL[r.accelerator]}</span>
)}
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
</div>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
+29
View File
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** The key's value ("show key" in Settings). */
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Remove a key; running deployments keep accepting it until they restart. */
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteApiKey(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** Keys without their values (only the last characters). */
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
/** Add a key (generated when `key` is missing); the response carries the full key once. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkError, cancelBenchmark } from "@/lib/benchmarks";
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/cancel">>(async (_req, { params }) => {
try {
await cancelBenchmark((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+11
View File
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listBenchmarkLogs } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listBenchmarkLogs((await params).id, after));
});
@@ -0,0 +1,20 @@
import { readFile } from "node:fs/promises";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { payloadFile } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** The exact payload the preview built, byte for byte what would be sent to launch80. */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]/payload">>(async (_req, { params }) => {
const { id, pubId } = await params;
let path: string;
try {
path = payloadFile(id, pubId);
} catch {
return apiError(404, "not_found", "No payload for this preview.");
}
const body = await readFile(path).catch(() => null);
if (!body) return apiError(404, "not_found", "No payload for this preview.");
return new Response(body, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="launch80-payload-${pubId.slice(-6).toLowerCase()}.json"` } });
});
@@ -0,0 +1,45 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { confirmPublication, discardPublication, PublicationError, readPayloadPreview } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** What the previewed payload contains (read from the exact file that would be sent). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (_req, { params }) => {
try {
const { id, pubId } = await params;
return NextResponse.json({ preview: await readPayloadPreview(id, pubId) });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
const Confirm = z.object({ confirm: z.literal(true) });
/** Opt-in 2: publish the previewed payload. Requires `{ "confirm": true }`. */
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (req, { params, session }) => {
try {
const { id, pubId } = await params;
Confirm.parse(await req.json());
await confirmPublication(id, pubId, session.user.email ?? session.user.name ?? null);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Discard a preview. */
export const DELETE = withAuth<RouteContext<"/api/benchmarks/[id]/publications/[pubId]">>(async (_req, { params }) => {
try {
const { id, pubId } = await params;
await discardPublication(id, pubId);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,24 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getL80Status, listPublications, PreviewBody, PublicationError, requestPreview } from "@/lib/publications";
export const dynamic = "force-dynamic";
/** This run's launch80 publications and whether publishing is available (never the token). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/publications">>(async (_req, { params }) => {
const { id } = await params;
const [status, publications] = await Promise.all([getL80Status(), listPublications(id)]);
return NextResponse.json({ status, publications });
});
/** Opt-in 1: prepare a preview (L80 dry run). Nothing is sent to launch80. */
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/publications">>(async (req, { params }) => {
try {
const { id } = await params;
return NextResponse.json(await requestPreview(id, PreviewBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,27 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { REPORT_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/**
* BetterBench's self-contained HTML report. Served sandboxed (opaque origin, no network): it is
* generated content and must not run with access to Kaname's session.
*/
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/report">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
if (!run?.hasReport) return apiError(404, "not_found", "This run has no report.");
const html = await readFile(join(runDir(run.id), REPORT_FILE)).catch(() => null);
if (!html) return apiError(404, "not_found", "The report file is missing.");
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, max-age=300",
},
});
});
@@ -0,0 +1,29 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { AB_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** BetterBench's results.json without endpoint and host, as a download (works with `betterbench report/compare` and `L80 betterbench --results`). */
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/results">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
if (!run) return apiError(404, "not_found", "Benchmark not found.");
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<string, unknown>; 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-${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}"` } });
});
+36
View File
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkError, deleteBenchmark, getBenchmark, updateBenchmarkLabel } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
});
const Patch = z.object({ label: z.string().max(120).nullable() });
/** Rename (label) a run. */
export const PATCH = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (req, { params }) => {
try {
await updateBenchmarkLabel((await params).id, Patch.parse(await req.json()).label);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Delete a run with its log and files. */
export const DELETE = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, { params }) => {
try {
await deleteBenchmark((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { BenchmarkBody, BenchmarkError, createBenchmark, listBenchmarks } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
/** All runs, newest first; `?deployment=<id>` or `?model=<id>` narrows them. */
export const GET = withAuth(async (req) => {
const sp = new URL(req.url).searchParams;
return NextResponse.json(await listBenchmarks({ deploymentId: sp.get("deployment") ?? undefined, modelId: sp.get("model") ?? undefined }));
});
/** Queue a BetterBench run against a running deployment. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createBenchmark(BenchmarkBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,45 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { apiKeyValues } from "@/lib/api-keys";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
const Body = z.object({
messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
maxTokens: z.number().int().min(1).max(8192).default(256),
});
/**
* Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
* streams the server-sent events back unchanged.
*/
export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (req, { params }) => {
try {
const d = await getDeployment((await params).id);
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
// Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listDeploymentLogs } from "@/lib/deployments";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/deployments/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listDeploymentLogs((await params).id, after));
});
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
const d = await getDeployment((await params).id);
return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
});
export const PUT = withAuth<RouteContext<"/api/deployments/[id]">>(async (req, { params }) => {
try {
await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Stop the container (if running) and delete the deployment. */
export const DELETE = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
try {
await requestDelete((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/start">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "running");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/stop">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "stopped");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
/** Create a deployment; `start: true` starts it right away. */
export const POST = withAuth(async (req) => {
try {
const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+15 -6
View File
@@ -2,19 +2,28 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles, saveDownloadSpeedLimit, saveRecommendedRoles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Download settings: which file kinds are picked along with model weights. */
export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() }));
async function current() {
return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit() };
}
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) });
/** Download settings: which file kinds are picked along with model weights, and the speed limit. */
export const GET = withAuth(async () => NextResponse.json(await current()));
const Body = z.object({
recommendedRoles: z.array(z.string()).max(32).optional(),
maxBytesPerSecond: z.number().nullable().optional(),
});
export const PUT = withAuth(async (req) => {
try {
const { recommendedRoles } = Body.parse(await req.json());
return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) });
const body = Body.parse(await req.json());
if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles);
if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond);
return NextResponse.json(await current());
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
+14
View File
@@ -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<RouteContext<"/api/sweeps/[id]/cancel">>(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);
}
});
+21
View File
@@ -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<RouteContext<"/api/sweeps/[id]">>(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<RouteContext<"/api/sweeps/[id]">>(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);
}
});
+18
View File
@@ -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);
}
});
+11
View File
@@ -21,6 +21,7 @@
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-series: var(--series);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
@@ -68,6 +69,8 @@
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
/* Single-series data color (benchmark charts); validated reference blue, light surface. */
--series: #2a78d6;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
@@ -103,6 +106,7 @@
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--series: #3987e5;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
@@ -127,4 +131,11 @@
html {
@apply font-sans;
}
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
.dark {
color-scheme: dark;
}
option {
@apply bg-popover text-popover-foreground;
}
}
+10 -3
View File
@@ -1,12 +1,19 @@
"use client";
import { LibraryIcon, SettingsIcon } from "lucide-react";
import { GaugeIcon, LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
const LINKS = [
{ href: "/", label: "Library", icon: LibraryIcon, active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/jobs/") },
{
href: "/",
label: "Library",
icon: LibraryIcon,
active: (p: string) => !["/settings", "/deployments", "/benchmarks"].some((x) => p.startsWith(x)),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
{ href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
@@ -16,7 +23,7 @@ export function AppNav() {
return (
<nav className="flex items-center gap-1 text-sm">
{LINKS.map((l) => {
const active = l.active(pathname) || (l.href === "/" && pathname.startsWith("/jobs/"));
const active = l.active(pathname);
return (
<Link
key={l.href}
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ArgRow } from "@/lib/extra-args";
const GENERIC = { flag: "--flag", value: "value (optional)" };
/** Extra command-line arguments as flag/value rows (controlled). `placeholder` is the first row's example. */
export function ArgsEditor({
rows,
onChange,
placeholder = GENERIC,
addLabel = "Add argument",
}: {
rows: ArgRow[];
onChange: (rows: ArgRow[]) => void;
placeholder?: { flag: string; value: string };
addLabel?: string;
}) {
const set = (i: number, patch: Partial<ArgRow>) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const single = (s: string) => s.replace(/[\r\n]/g, "");
return (
<div className="flex flex-col gap-1.5">
{rows.map((r, i) => (
<div key={i} className="flex items-center gap-1.5">
<Input
value={r.flag}
onChange={(e) => set(i, { flag: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).flag}
spellCheck={false}
aria-label={`Argument ${i + 1} flag`}
className="font-mono text-xs md:text-xs"
/>
<Input
value={r.value}
onChange={(e) => set(i, { value: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).value}
spellCheck={false}
aria-label={`Argument ${i + 1} value`}
className="font-mono text-xs md:text-xs"
/>
<Button type="button" variant="ghost" size="icon-sm" aria-label={`Remove argument ${i + 1}`} onClick={() => onChange(rows.filter((_, j) => j !== i))}>
<XIcon />
</Button>
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={() => onChange([...rows, { flag: "", value: "" }])}>
<PlusIcon />
{addLabel}
</Button>
</div>
);
}
+125
View File
@@ -0,0 +1,125 @@
"use client";
import { useState } from "react";
import { cn } from "@/lib/utils";
export type BarRow = {
label: string;
/** Bar length (mode "bar") or median tick (mode "range"). */
value: number | null;
/** Mode "range": the span, e.g. 1% low → 99% high. */
range?: [number, number] | null;
/** Text at the bar tip. */
valueLabel?: string;
/** Tooltip lines. */
details?: string[];
};
/** Clean axis maximum and ticks (0 / 25 / 50 / 75 / 100 style). */
function niceTicks(max: number): number[] {
if (!(max > 0)) return [0, 1];
const raw = max / 4;
const mag = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;
const ticks: number[] = [];
for (let t = 0; t <= max + step * 0.001; t += step) ticks.push(Number(t.toPrecision(6)));
if (ticks[ticks.length - 1] < max) ticks.push(Number((ticks[ticks.length - 1] + step).toPrecision(6)));
return ticks;
}
const fmtTick = (v: number) => (v >= 1000 ? v.toLocaleString("en-US", { maximumFractionDigits: 0 }) : v.toLocaleString("en-US", { maximumFractionDigits: 2 }));
/**
* Horizontal single-series bars (one hue), value at the tip, a hover tooltip per row, an optional
* reference line (e.g. the weighted combined score). Mode "range" draws a span with a median tick.
*/
export function BarChart({
rows,
axisLabel,
reference,
mode = "bar",
className,
}: {
rows: BarRow[];
axisLabel: string;
reference?: { value: number; label: string } | null;
mode?: "bar" | "range";
className?: string;
}) {
const [hover, setHover] = useState<number | null>(null);
const max = Math.max(...rows.map((r) => (mode === "range" ? (r.range?.[1] ?? r.value ?? 0) : (r.value ?? 0))), reference?.value ?? 0);
const ticks = niceTicks(max);
const top = ticks[ticks.length - 1] || 1;
const pct = (v: number) => `${Math.max(0, Math.min(100, (v / top) * 100))}%`;
return (
<div className={cn("flex flex-col gap-1 text-xs", className)} role="img" aria-label={`${axisLabel} by ${rows.map((r) => r.label).join(", ")}`}>
<div className="relative grid grid-cols-[minmax(5rem,9rem)_1fr] gap-x-3">
{/* gridlines + reference line span the plot column */}
<div />
<div className="pointer-events-none relative">
<div className="absolute inset-0">
{ticks.map((t) => (
<div key={t} className="absolute top-0 bottom-0 w-px bg-border" style={{ left: pct(t), height: `${rows.length * 32}px` }} />
))}
{reference && (
<div className="absolute top-0 w-0.5 bg-foreground/70" style={{ left: pct(reference.value), height: `${rows.length * 32}px` }}>
<span className="absolute -top-4 left-1 whitespace-nowrap text-[11px] text-muted-foreground">{reference.label}</span>
</div>
)}
</div>
</div>
{rows.map((r, i) => (
<div key={r.label} className="contents" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover((h) => (h === i ? null : h))}>
<div className={cn("flex h-8 items-center justify-end truncate text-right", hover === i ? "text-foreground" : "text-muted-foreground")} title={r.label}>
{r.label}
</div>
<div className="relative h-8">
{mode === "bar" && r.value != null && (
<div className="absolute top-1/2 left-0 h-5 -translate-y-1/2 rounded-r-[4px] bg-series" style={{ width: pct(r.value) }} />
)}
{mode === "range" && r.range && (
<>
<div
className="absolute top-1/2 h-3 -translate-y-1/2 rounded-[4px] bg-series/35"
style={{ left: pct(r.range[0]), width: `calc(${pct(r.range[1])} - ${pct(r.range[0])})` }}
/>
{r.value != null && <div className="absolute top-1/2 h-5 w-0.5 -translate-y-1/2 bg-series" style={{ left: pct(r.value) }} />}
</>
)}
{r.valueLabel && (
<span
className="absolute top-1/2 ml-1.5 -translate-y-1/2 whitespace-nowrap text-foreground tabular-nums"
style={{ left: pct(mode === "range" ? (r.range?.[1] ?? r.value ?? 0) : (r.value ?? 0)) }}
>
{r.valueLabel}
</span>
)}
{hover === i && r.details && r.details.length > 0 && (
<div className="absolute top-full left-0 z-20 mt-1 min-w-48 rounded-lg bg-popover px-3 py-2 text-popover-foreground shadow-lg ring-1 ring-foreground/10">
<div className="mb-1 font-medium">{r.label}</div>
{r.details.map((d) => (
<div key={d} className="text-muted-foreground tabular-nums">
{d}
</div>
))}
</div>
)}
</div>
</div>
))}
{/* axis */}
<div />
<div className="relative mt-1 h-4 text-[11px] text-muted-foreground tabular-nums">
{ticks.map((t) => (
<span key={t} className="absolute -translate-x-1/2" style={{ left: pct(t) }}>
{fmtTick(t)}
</span>
))}
</div>
<div />
<div className="mt-1 text-[11px] tracking-wide text-muted-foreground uppercase">{axisLabel}</div>
</div>
</div>
);
}
+58
View File
@@ -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 (
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-lg font-semibold">{value}</span>
{note && <span className="text-[11px] text-muted-foreground">{note}</span>}
</div>
);
}
/** 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 <p className="text-sm text-muted-foreground">No resource samples were recorded.</p>;
const multi = stats.containers.length > 1;
return (
<div className="flex flex-col gap-3">
{stats.containers.map((c) => (
<div key={c.side} className="flex flex-col gap-1.5">
{multi && <span className="text-xs font-medium">{c.side === "a" ? `A · ${names?.a ?? ""}` : `B · ${names?.b ?? ""}`}</span>}
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="CPU, average" value={`${cores(c.cpuAvg)} cores`} note={`peak ${cores(c.cpuPeak)} cores`} />
<Cell
label="RAM, peak"
value={c.memPeakBytes != null ? formatBytes(c.memPeakBytes) : "—"}
note={`average ${c.memAvgBytes != null ? formatBytes(c.memAvgBytes) : "—"}${c.memLimitBytes ? ` · limit ${formatBytes(c.memLimitBytes)}` : ""}`}
/>
{c.memPeakBytes != null && c.memLimitBytes ? (
<Cell label="Of the limit" value={`${Math.round((c.memPeakBytes / c.memLimitBytes) * 100)}%`} note="peak RAM ÷ memory limit" />
) : (
<Cell label="Of the limit" value="—" note="no memory limit set" />
)}
</div>
</div>
))}
{stats.gpus.map((g) => (
<div key={g.index} className="flex flex-col gap-1.5">
<span className="text-xs font-medium">
GPU {g.index} · {g.name}
</span>
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="VRAM, peak" value={formatBytes(g.vramPeakMb * 2 ** 20)} note={`of ${formatBytes(g.vramTotalMb * 2 ** 20)} · average ${formatBytes(g.vramAvgMb * 2 ** 20)}`} />
<Cell label="Utilization" value={`${Math.round(g.utilAvg)}%`} note={`average · peak ${Math.round(g.utilPeak)}%`} />
<Cell label="Power" value={g.powerAvgW != null ? `${Math.round(g.powerAvgW)} W` : "—"} note={g.powerPeakW != null ? `average · peak ${Math.round(g.powerPeakW)} W` : undefined} />
</div>
</div>
))}
<p className="text-[11px] text-muted-foreground">
Sampled every ~2 s over {stats.seconds} s ({stats.samples} samples). RAM is the container&apos;s usage without page cache, like <code>docker stats</code>; GPU
figures are for the whole GPU, so other work on it counts too.
</p>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { LoaderCircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const STYLE: Record<string, string> = {
queued: "border-foreground/15 text-muted-foreground",
running: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
completed: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
failed: "border-destructive/30 bg-destructive/10 text-destructive",
cancelled: "border-foreground/15 text-muted-foreground",
};
export function BenchmarkStateBadge({ state, cancelling, className }: { state: string; cancelling?: boolean; className?: string }) {
const label = state === "running" && cancelling ? "cancelling" : state;
return (
<span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-4xl border px-2 text-xs font-medium whitespace-nowrap", STYLE[state] ?? STYLE.queued, className)}>
{state === "running" && <LoaderCircleIcon className="size-3 animate-spin" />}
{label}
</span>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { LoaderCircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const STYLE: Record<string, { label: string; className: string }> = {
stopped: { label: "stopped", className: "border-foreground/15 text-muted-foreground" },
starting: { label: "starting", className: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300" },
running: { label: "running", className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" },
stopping: { label: "stopping", className: "border-foreground/15 text-muted-foreground" },
failed: { label: "failed", className: "border-destructive/30 bg-destructive/10 text-destructive" },
};
/** Deployment state; shows "starting" as soon as a start was requested. */
export function DeploymentStateBadge({ state, desiredState, className }: { state: string; desiredState: string; className?: string }) {
const effective = desiredState === "running" && (state === "stopped" || state === "failed") ? "starting" : desiredState === "stopped" && (state === "running" || state === "starting") ? "stopping" : state;
const s = STYLE[effective] ?? STYLE.stopped;
return (
<span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-4xl border px-2 text-xs font-medium whitespace-nowrap", s.className, className)}>
{(effective === "starting" || effective === "stopping") && <LoaderCircleIcon className="size-3 animate-spin" />}
{effective === "running" && <span className="size-1.5 rounded-full bg-emerald-500" />}
{s.label}
</span>
);
}
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";
type LogLine = { id: number; ts: number; stream: string; line: string };
/** Polls `url?after=<id>` for new lines and keeps the view pinned to the bottom unless scrolled up. */
export function LiveLog({ url, title = "Log", live = true, className }: { url: string; title?: string; live?: boolean; className?: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`${url}?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
if (!live) return () => void (stopped = true);
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [url, live]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className={cn("min-w-0", className)}>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { ChevronDownIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
/** A native <select> styled like Input; the option list follows the theme via `color-scheme`. */
function NativeSelect({ className, children, ...props }: React.ComponentProps<"select">) {
return (
<div className={cn("relative w-full", className)}>
<select
data-slot="native-select"
className="h-8 w-full min-w-0 appearance-none rounded-lg border border-input bg-transparent py-1 pr-8 pl-2.5 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"
{...props}
>
{children}
</select>
<ChevronDownIcon className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
</div>
);
}
export { NativeSelect };
+5 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { BoxesIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -71,6 +71,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<BoxesIcon />
Runtimes
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
<KeyRoundIcon />
API keys
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
+20
View File
@@ -0,0 +1,20 @@
"use client";
import { useSyncExternalStore } from "react";
/** The browser's host name; null while rendering on the server, so hydration matches. */
export function useHostname(): string | null {
return useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
}
/** llama-server's built-in chat UI, served at / on the published host port. */
export function webUiUrl(
d: { engine: string; hostPort: number | null; options: { webui?: boolean | null } },
hostname: string | null,
): string | null {
return d.engine === "llama.cpp" && d.options.webui !== false && d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/` : null;
}
+56
View File
@@ -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>): 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/);
});
});
+43
View File
@@ -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"}.`;
}
+67
View File
@@ -0,0 +1,67 @@
import "server-only";
import { randomBytes } from "node:crypto";
import { asc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { apiKeys } from "@/lib/db/schema";
export class ApiKeyError extends Error {
constructor(
public code: "invalid" | "not_found" | "conflict",
message: string,
public status: number,
) {
super(message);
}
}
// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
export const ApiKeyBody = z.object({
name: z.string().trim().min(1).max(80),
key: z
.string()
.trim()
.min(16, "at least 16 characters")
.max(256)
.regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
.refine((k) => !k.includes(","), "no commas")
.optional(),
});
export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
const mask = (key: string) => `…${key.slice(-4)}`;
export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
export async function listApiKeys(): Promise<ApiKeyRow[]> {
const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
}
/** Returns the full key once, so the user can copy it. */
export async function createApiKey(input: z.infer<typeof ApiKeyBody>) {
const key = input.key ?? generateApiKey();
const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
}
export async function deleteApiKey(id: string) {
const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
}
/** All key values (for runtime containers and Kaname's own requests to them). */
export async function apiKeyValues(): Promise<string[]> {
return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
}
/** One key's value, for "show key" in Settings. */
export async function revealApiKey(id: string): Promise<string> {
const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
return row.key;
}
+24
View File
@@ -0,0 +1,24 @@
// Where benchmark files live. Shared by the worker (writes) and the web app (serves reports).
import { dirname, join, resolve } from "node:path";
import { coreEnv } from "@/lib/env";
/** BENCHMARKS_DIR, or "benchmarks" next to the SQLite file (e.g. /data/benchmarks). */
export function benchmarksDir(): string {
const env = coreEnv();
if (env.BENCHMARKS_DIR) return resolve(env.BENCHMARKS_DIR);
const db = env.DATABASE_URL.replace(/^file:/, "");
return resolve(dirname(db), "benchmarks");
}
/** Run ids are ULIDs; anything else never becomes a path. */
const RUN_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
export function runDir(runId: string): string {
if (!RUN_ID_RE.test(runId)) throw new Error("invalid run id");
return join(benchmarksDir(), runId);
}
export const RESULTS_FILE = "results.json";
export const REPORT_FILE = "results.html";
export const AB_FILE = "ab.json";
+83
View File
@@ -0,0 +1,83 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { describeHardware, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled } from "./benchmark-report";
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
const snap = {
deploymentName: "bench test",
repoId: "unsloth/Qwen3-0.6B-GGUF",
runtimeName: "llama.cpp (CPU)",
engine: "llama.cpp",
image: "ghcr.io/ggml-org/llama.cpp:server",
imageId: null,
options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, extraArgs: [] },
cpus: 4,
memoryMb: 2640,
command: "",
host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
} as BenchmarkSnapshot;
const summary: BenchmarkSummary = {
v: 2,
combined: { decode: 97.25, ttft_p50: 140, itl_low1: 48.03, update_p50: 10.1, update_p99: 17.5 },
single: [
{ category: "chat", runs: 5, ttft_p50: 150.3, ttft_p99: 165.5, decode_med: 102.8, decode_cv: 0.05, itl_low1: 51.1, tok_per_update: 1.01, batched: false, batched_runs: 0 },
{ category: "code", runs: 5, ttft_p50: 135.7, ttft_p99: 165.7, decode_med: 89.1, decode_cv: 0.1, itl_low1: 40.8, tok_per_update: 1.0, batched: false, batched_runs: 0 },
],
prefill: [
{ target_depth: 2000, skipped: false, pp_med: 600 },
{ target_depth: 8000, skipped: true },
],
concurrency: [
{ level: 1, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 100, ttft_p99: 200, decode_med: 95 },
{ level: 4, ok: 46, requests: 48, aggregate_tps: 210, ttft_p50: 300, ttft_p99: 900, decode_med: 52 },
],
gate: [
{ section: "single_stream", key: "chat", metric: "ttft_p99", n: 5, need: 500 },
{ section: "concurrency", key: 4, metric: "ttft_p99", n: 46, need: 500 },
],
truncated: [3, 10],
failedSingle: 0,
phases: ["decode", "prefill", "concurrency"],
cacheHits: 0,
betterbenchVersion: "0.6.1",
corpusVersion: "1.0",
maxModelLen: 4096,
config: { warmup: 1, runs_per_category: 5, temperature: 0.7, top_p: 0.95, top_k: 20, unique_nonce: true, weights: { code: 0.3, chat: 0 }, concurrency_requests: 48, prefill_runs: 8, prefill_warmup: 2, prefill_max_tokens: 16 },
passes: 5,
quick: true,
};
const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
describe("benchmark report (launch80 conventions)", () => {
it("describes hardware, subtitle and summary", () => {
assert.equal(describeHardware(snap), "4 CPU cores of an AMD Ryzen 7 9850X3D");
assert.equal(describeHardware({ ...snap, gpuNames: ["NVIDIA GeForce RTX 3080", "NVIDIA GeForce RTX 3080"] }), "2× NVIDIA GeForce RTX 3080");
assert.equal(reportSubtitle(run), "4 CPU cores of an AMD Ryzen 7 9850X3D · 5 passes per category · temp 0.7 · quick smoke run");
const s = reportSummary(run);
assert.match(s, /^Quick smoke run, not a publishable measurement\. unsloth\/Qwen3-0\.6B-GGUF \(Q4_K_M, 4,096-token context\)/);
assert.match(s, /5 measured passes per category over 2 categories\. Combined decode 97\.3 t\/s \(weighted median\), TTFT p50 140 ms, ITL 1% low 48\.0 t\/s\./);
assert.match(s, /peaked at 210\.0 t\/s at concurrency 4\. Prefill reached 600 t\/s at ~2,000 prompt tokens\.$/);
});
it("lists caveats in launch80's order", () => {
const c = reportCaveats(run);
assert.match(c[0], /^Quick smoke run: 5 passes per category after 1 warmup/);
assert.match(c[1], /^Under-sampled: TTFT p99 in chat, c4 \(n ≤ 46\)\. A p99 needs 500 samples/);
assert.match(c[2], /^3 of 10 runs stopped at max_tokens \(30%\)/);
assert.match(c[3], /^Concurrency requests failed at level 4: 46\/48 ok/);
assert.match(c[4], /^Prefill depths skipped: 8,000 tokens \(exceed the model context of 4,096\)/);
assert.equal(c.length, 5);
});
it("writes the method from the config and flags gated cells", () => {
const m = reportMethod(summary).join("\n");
assert.match(m, /Single stream: 1 warmup then 5 measured passes per category, temperature 0\.7, top_p 0\.95, top_k 20, prefix cache cold/);
assert.match(m, /Concurrency sweep: 48 requests at levels 1, 4\./);
assert.match(m, /weighted by category: chat 0, code 0\.3/);
assert.ok(undersampled(summary, "single_stream", "chat", "ttft_p99"));
assert.ok(undersampled(summary, "concurrency", 4, "ttft_p99"));
assert.ok(!undersampled(summary, "single_stream", "code", "ttft_p99"));
});
});
+169
View File
@@ -0,0 +1,169 @@
// Text for a benchmark's report page, following launch80's bench.betterbench.v1 conventions
// (L80 CLI, internal/betterbench/payload.go): every figure is one BetterBench reported, quick runs
// say so first, under-sampled percentiles are flagged, truncated and batched runs are called out,
// and no endpoint or host name appears. Pure, for tests.
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
type Run = { label: string | null; snapshot: BenchmarkSnapshot; settings: BenchmarkSettings; summary: BenchmarkSummary | null };
export const f1 = (v: number | null | undefined) => (v == null ? "—" : v.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 }));
export const f0 = (v: number | null | undefined) => (v == null ? "—" : Math.round(v).toLocaleString("en-US"));
const int = (v: number) => v.toLocaleString("en-US");
/** launch80's quick rule: a single-stream run with ≤ 5 passes per category. */
export function isQuick(sum: BenchmarkSummary | null): boolean {
if (!sum) return false;
return sum.quick || (sum.single.length > 0 && sum.passes != null && sum.passes > 0 && sum.passes <= 5);
}
/** Did the server stream several tokens per update (speculative/batched decoding)? */
export function isBatched(sum: BenchmarkSummary | null): boolean {
return !!sum?.single.some((r) => r.batched);
}
/** "RTX 3080" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
export function describeHardware(s: BenchmarkSnapshot): string {
if (s.gpuNames?.length) {
const names = [...new Set(s.gpuNames)];
return s.gpuNames.length > 1 && names.length === 1 ? `${s.gpuNames.length}× ${names[0]}` : names.join(" + ");
}
const cpu = s.host?.cpuModel
?.replace(/\s+\d+-Core Processor$/i, "")
.replace(/\(R\)|\(TM\)/g, "")
.trim();
if (s.cpus) return `${s.cpus} CPU core${s.cpus === 1 ? "" : "s"}${cpu ? ` of an ${cpu}` : ""}`;
return cpu ? `an ${cpu}${s.host?.threads ? ` (${s.host.threads} threads)` : ""}` : "CPU";
}
export function weightsLabel(s: BenchmarkSnapshot): string {
return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
}
/** hardware · N passes per category · temp 0.7 · quick smoke run */
export function reportSubtitle(run: Run): string {
const sum = run.summary;
const parts = [describeHardware(run.snapshot)];
if (sum?.single.length && sum.passes) parts.push(`${sum.passes} passes per category`);
const cfg = sum?.config;
if (cfg?.greedy) parts.push("greedy");
else if (cfg?.temperature != null) parts.push(`temp ${cfg.temperature}`);
if (isQuick(sum)) parts.push("quick smoke run");
return parts.join(" · ");
}
export function reportSummary(run: Run): string {
const s = run.snapshot;
const sum = run.summary;
const out: string[] = [];
if (isQuick(sum)) out.push("Quick smoke run, not a publishable measurement.");
out.push(
`${s.repoId} (${weightsLabel(s)}, ${int(s.options.contextSize)}-token context) on ${s.runtimeName}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
}.`.replace(" ,", ","),
);
const c = sum?.combined;
if (c) {
const bits: string[] = [];
if (c.decode != null) bits.push(`combined decode ${f1(c.decode)} t/s (weighted median)`);
if (c.ttft_p50 != null) bits.push(`TTFT p50 ${f0(c.ttft_p50)} ms`);
if (isBatched(sum) && c.update_p99 != null) bits.push(`stream-update p99 ${f1(c.update_p99)} ms`);
else if (c.itl_low1 != null) bits.push(`ITL 1% low ${f1(c.itl_low1)} t/s`);
if (bits.length) out.push(bits.join(", ").replace(/^./, (x) => x.toUpperCase()) + ".");
}
const peak = sum?.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
if (peak) out.push(`Aggregate throughput peaked at ${f1(peak.aggregate_tps)} t/s at concurrency ${peak.level}.`);
const pre = sum?.prefill.filter((p) => !p.skipped && p.pp_med != null) ?? [];
const best = pre.length ? pre.reduce((a, b) => (b.pp_med! > a.pp_med! ? b : a)) : null;
if (best) out.push(`Prefill reached ${f0(best.pp_med)} t/s at ~${int(best.target_depth)} prompt tokens.`);
return out.join(" ");
}
/** The Method section: how BetterBench measured, from the run's own config. */
export function reportMethod(sum: BenchmarkSummary): string[] {
const p: string[] = [];
const cfg = sum.config ?? {};
const cats = sum.single.map((r) => r.category);
p.push(`BetterBench ${sum.betterbenchVersion}${sum.corpusVersion ? `, corpus v${sum.corpusVersion}` : ""}${cats.length ? ` (${cats.length} categories: ${cats.join(", ")})` : ""}.`);
if (sum.single.length) {
let s = `Single stream: ${cfg.warmup ?? "?"} warmup then ${cfg.runs_per_category ?? sum.passes} measured passes per category`;
if (cfg.greedy) s += ", greedy sampling";
else if (cfg.temperature != null) s += `, temperature ${cfg.temperature}${cfg.top_p != null ? `, top_p ${cfg.top_p}` : ""}${cfg.top_k != null ? `, top_k ${cfg.top_k}` : ""}`;
s += cfg.unique_nonce === false ? ", prefix cache warm" : ", prefix cache cold (unique nonce per request)";
p.push(`${s}.`);
}
if (sum.concurrency.length) {
const n = cfg.concurrency_requests ?? sum.concurrency[0].requests;
p.push(`Concurrency sweep: ${n} requests at levels ${sum.concurrency.map((c) => c.level).join(", ")}.`);
}
if (sum.prefill.length) {
let s = `Prefill sweep at target depths ${sum.prefill.map((d) => d.target_depth).join(", ")} tokens`;
if (cfg.prefill_runs) s += `, ${cfg.prefill_runs} runs after ${cfg.prefill_warmup ?? 0} warmup`;
if (cfg.prefill_max_tokens) s += `, ${cfg.prefill_max_tokens}-token decode`;
p.push(`${s}, cold prefix cache. Prefill throughput is prompt tokens divided by TTFT.`);
}
p.push(
isBatched(sum)
? "Units: TTFT in ms; decode and prefill throughput in tokens per second; update p50/p99 is the wall-clock gap between stream updates in ms, and tok/update how many tokens each update carried."
: "Units: TTFT in ms; decode, ITL and prefill throughput in tokens per second; ITL columns are instantaneous tokens per second (1% low = slowest tokens, 99% high = fastest).",
);
const w = cfg.weights;
if (w && Object.keys(w).length && sum.single.length) {
const ws = sum.single.filter((r) => w[r.category] != null).map((r) => `${r.category} ${w[r.category]}`);
if (ws.length) p.push(`Combined figures are weighted by category: ${ws.join(", ")}. Categories without a weight are excluded from the combined figures.`);
} else if (sum.single.length > 1) {
p.push("Combined figures weight every category equally.");
}
p.push("Undersampled cells (†) carry a percentile that rests on fewer samples than n · tail ≥ 5 requires; read them as roughly the worst observed, not as percentiles.");
return p;
}
const METRIC_LABEL: Record<string, string> = {
ttft_p99: "TTFT p99",
itl_high99: "ITL 99% high",
update_p99: "update p99",
pp_p99: "prefill p99",
};
/** "Read these first": the same rules as launch80's buildCaveats, plus prefix-cache hits. */
export function reportCaveats(run: Run): string[] {
const sum = run.summary;
if (!sum) return [];
const out: string[] = [];
if (isQuick(sum)) {
out.push(`Quick smoke run: ${sum.passes ?? 5} passes per category after ${sum.config?.warmup ?? 1} warmup. Too few passes for any percentile to hold; treat every figure as indicative, not as a result.`);
}
const gate = sum.gate ?? [];
if (gate.length) {
const by = new Map<string, string[]>();
for (const g of gate) {
const label = `${METRIC_LABEL[g.metric] ?? g.metric}`;
by.set(label, [...(by.get(label) ?? []), String(g.section === "prefill" ? `${int(Number(g.key))} tok` : g.section === "concurrency" ? `c${g.key}` : g.key)]);
}
const list = [...by].map(([m, keys]) => `${m} in ${keys.slice(0, 4).join(", ")}${keys.length > 4 ? ` +${keys.length - 4}` : ""}`).join("; ");
const need = Math.max(...gate.map((g) => g.need));
out.push(`Under-sampled: ${list} (n ≤ ${Math.max(...gate.map((g) => g.n))}). A p99 needs ${int(need)} samples; the daggered cells are roughly the worst observed, not percentiles.`);
}
const [trunc, tot] = sum.truncated ?? [0, 0];
if (tot > 0 && trunc > 0) {
out.push(`${trunc} of ${tot} runs stopped at max_tokens (${Math.round((trunc / tot) * 100)}%). On a thinking model a truncated run measures the thinking phase, not a complete answer.`);
}
const batchedRuns = sum.single.reduce((s, r) => s + (r.batched_runs ?? 0), 0);
if (batchedRuns > 0) {
const runs = sum.single.reduce((s, r) => s + r.runs, 0);
out.push(`${batchedRuns} of ${runs} runs streamed several tokens per update (speculative or batched decoding), so per-token ITL is not reported; update p50/p99 and tok/update are shown instead.`);
}
if (sum.failedSingle) out.push(`${sum.failedSingle} single-stream request(s) failed and are excluded from every figure.`);
const concFail = sum.concurrency.filter((c) => c.ok < c.requests).map((c) => `level ${c.level}: ${c.ok}/${c.requests} ok`);
if (concFail.length) out.push(`Concurrency requests failed at ${concFail.join("; ")}. Aggregate throughput counts only completed requests.`);
const skipped = sum.prefill.filter((p) => p.skipped).map((p) => int(p.target_depth));
if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context of ${int(sum.maxModelLen ?? run.snapshot.options.contextSize)}).`);
if (sum.cacheHits > 0) out.push(`${sum.cacheHits} request(s) were partly served from the server's prefix cache although the run asked for a cold cache; those prefill figures may be cache lookups.`);
return out.slice(0, 8);
}
/** Did this percentile cell fail the sample gate? */
export function undersampled(sum: BenchmarkSummary, section: string, key: string | number, metric: string): boolean {
return !!sum.gate?.some((g) => g.section === section && String(g.key) === String(key) && g.metric === metric);
}
+62
View File
@@ -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(" "),
},
};
}
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { configChips, deltaPct, describeSettings, headline } from "./benchmark-view";
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
const summary: BenchmarkSummary = {
combined: { decode: 42.5, ttft_p50: 180, itl_low1: null, update_p50: null, update_p99: null },
single: [],
prefill: [
{ target_depth: 2048, skipped: false, pp_med: 900 },
{ target_depth: 8192, skipped: false, pp_med: 700 },
{ target_depth: 65536, skipped: true },
],
concurrency: [
{ level: 1, ok: 48, requests: 48, aggregate_tps: 40, ttft_p50: 100, ttft_p99: 200, decode_med: 40 },
{ level: 4, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 300, ttft_p99: 900, decode_med: 25 },
{ level: 8, ok: 48, requests: 48, aggregate_tps: 90, ttft_p50: 700, ttft_p99: 2000, decode_med: 12 },
],
phases: ["decode", "prefill", "concurrency"],
cacheHits: 0,
betterbenchVersion: "0.6.1",
corpusVersion: "1.0",
passes: 20,
quick: false,
};
describe("benchmark view", () => {
it("picks the headline numbers", () => {
assert.deepEqual(headline(summary), { decode: 42.5, ttftMs: 180, prefill: { tps: 700, depth: 8192 }, peak: { tps: 95, level: 4 } });
assert.deepEqual(headline(null), { decode: null, ttftMs: null, prefill: null, peak: null });
});
it("lists set options as chips", () => {
const snap = {
options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, threads: 8, cacheTypeK: "q8_0", extraArgs: [] },
cpus: 8,
memoryMb: null,
} as unknown as BenchmarkSnapshot;
assert.deepEqual(configChips(snap), ["Q4_K_M", "context 4096", "threads 8", "kv cache k / v q8_0 / f16", "cpu limit 8 cores"]);
});
it("describes settings and deltas", () => {
assert.equal(describeSettings({ quick: true, passes: null, warmup: null, phases: [] }), "quick, 5 passes · all phases");
assert.equal(describeSettings({ quick: false, passes: 10, warmup: null, phases: ["decode"] }), "10 passes · decode");
assert.equal(deltaPct(110, 100), 10);
assert.equal(deltaPct(null, 100), null);
});
});
+81
View File
@@ -0,0 +1,81 @@
// Display helpers for benchmark runs. Pure; shared by list, detail and compare pages.
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
export type Headline = {
/** Weighted single-stream decode t/s (BetterBench's combined score). */
decode: number | null;
ttftMs: number | null;
/** Prefill t/s at the deepest measured depth. */
prefill: { tps: number; depth: number } | null;
/** Highest aggregate t/s in the concurrency sweep. */
peak: { tps: number; level: number } | null;
};
export function headline(s: BenchmarkSummary | null): Headline {
if (!s) return { decode: null, ttftMs: null, prefill: null, peak: null };
const pre = s.prefill.filter((p) => !p.skipped && p.pp_med != null).sort((a, b) => b.target_depth - a.target_depth)[0];
const peak = [...s.concurrency].sort((a, b) => b.aggregate_tps - a.aggregate_tps)[0];
return {
decode: s.combined?.decode ?? null,
ttftMs: s.combined?.ttft_p50 ?? null,
prefill: pre ? { tps: pre.pp_med!, depth: pre.target_depth } : null,
peak: peak ? { tps: peak.aggregate_tps, level: peak.level } : null,
};
}
export type ConfigRow = { key: string; label: string; value: (s: BenchmarkSnapshot) => string | null };
const n = (v: number | null | undefined, unit = "") => (v != null ? `${v}${unit}` : null);
/** Launch settings worth comparing between runs, in display order. */
export const CONFIG_ROWS: ConfigRow[] = [
{ key: "runtime", label: "Runtime", value: (s) => s.runtimeName },
{ key: "image", label: "Image", value: (s) => s.image },
{ key: "accel", label: "Runs on", value: (s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null) },
{ key: "gpus", label: "GPUs", value: (s) => (s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
{ key: "ngl", label: "GPU layers", value: (s) => s.options.gpuLayers ?? null },
{ key: "sm", label: "Split mode", value: (s) => s.options.splitMode ?? null },
{ key: "ts", label: "Tensor split", value: (s) => s.options.tensorSplit ?? null },
{ key: "moe", label: "MoE experts in RAM", value: (s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null) },
{ key: "tp", label: "Tensor parallel", value: (s) => n(s.options.tensorParallel) },
{ key: "gmu", label: "GPU memory share", value: (s) => n(s.options.gpuMemoryUtilization) },
{ key: "cram", label: "Prompt cache (MiB)", value: (s) => n(s.options.cacheRamMb) },
{ key: "file", label: "Weights", value: (s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors") },
{ key: "ctx", label: "Context", value: (s) => n(s.options.contextSize) },
{ key: "threads", label: "Threads", value: (s) => n(s.options.threads) },
{ key: "parallel", label: "Parallel slots", value: (s) => n(s.options.parallel) },
{ key: "batch", label: "Batch / micro-batch", value: (s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null) },
{ key: "kv", label: "KV cache K / V", value: (s) => (s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
{ key: "fa", label: "Flash attention", value: (s) => s.options.flashAttn ?? null },
{ key: "draft", label: "Speculative", value: (s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null) },
{ key: "dtype", label: "Data type", value: (s) => s.options.dtype ?? null },
{ key: "seqs", label: "Max sequences", value: (s) => n(s.options.maxNumSeqs) },
{ key: "kvgb", label: "KV cache (GiB)", value: (s) => n(s.options.kvCacheGb) },
{ key: "cpus", label: "CPU limit", value: (s) => n(s.cpus, " cores") },
{ key: "mem", label: "Memory limit", value: (s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null) },
{ key: "args", label: "Extra arguments", value: (s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null) },
];
/** Short chips for a list row: the settings that are set. */
export function configChips(s: BenchmarkSnapshot): string[] {
const skip = new Set(["runtime", "image", "args"]);
return CONFIG_ROWS.filter((r) => !skip.has(r.key))
.map((r) => {
const v = r.value(s);
return v == null ? null : r.key === "file" ? v : `${r.label.toLowerCase()} ${v}`;
})
.filter((v): v is string => v != null);
}
export function describeSettings(st: BenchmarkSettings): string {
const passes = st.passes ?? (st.quick ? 5 : 20);
const phases = st.phases.length ? st.phases.join(", ") : "all phases";
return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
}
/** Relative difference of `v` against `base` in percent (null if either is missing). */
export function deltaPct(v: number | null | undefined, base: number | null | undefined): number | null {
return v != null && base != null && base !== 0 ? ((v - base) / base) * 100 : null;
}
+170
View File
@@ -0,0 +1,170 @@
import "server-only";
import { rm } from "node:fs/promises";
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 } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
export const BenchmarkBody = z.object({
deploymentId: z.string().min(1),
label: z.string().trim().max(120).nullable().optional(),
quick: z.boolean().default(false),
passes: z.number().int().min(1).max(200).nullable().optional(),
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<typeof BenchmarkBody>;
/** 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, 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 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({
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,
...(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;
}
const listColumns = {
id: benchmarkRuns.id,
deploymentId: benchmarkRuns.deploymentId,
modelId: benchmarkRuns.modelId,
tool: benchmarkRuns.tool,
label: benchmarkRuns.label,
settings: benchmarkRuns.settings,
snapshot: benchmarkRuns.snapshot,
state: benchmarkRuns.state,
phase: benchmarkRuns.phase,
cancelRequestedAt: benchmarkRuns.cancelRequestedAt,
startedAt: benchmarkRuns.startedAt,
finishedAt: benchmarkRuns.finishedAt,
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,
};
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
return db()
.select(listColumns)
.from(benchmarkRuns)
.where(
and(
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
),
)
.orderBy(desc(benchmarkRuns.createdAt));
}
export async function getBenchmark(id: string) {
const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
return row ?? null;
}
export async function getBenchmarks(ids: string[]) {
if (ids.length === 0) return [];
const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
}
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
export async function cancelBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "queued") {
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "queued")));
} else if (run.state === "running") {
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
}
}
export async function updateBenchmarkLabel(id: string, label: string | null) {
const res = await db().update(benchmarkRuns).set({ label: label?.trim() || null }).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
}
/** Deletes the run, its log and its files. Cancel a running one first. */
export async function deleteBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "running") throw new BenchmarkError("busy", "Cancel the run before deleting it.", 409);
await db().delete(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
await db().delete(benchmarkRuns).where(eq(benchmarkRuns.id, id));
await rm(runDir(id), { recursive: true, force: true });
}
export async function listBenchmarkLogs(id: string, afterId: number, tail = 500) {
const rows =
afterId > 0
? await db()
.select()
.from(benchmarkLogs)
.where(and(eq(benchmarkLogs.runId, id), gt(benchmarkLogs.id, afterId)))
.orderBy(asc(benchmarkLogs.id))
.limit(2000)
: (await db().select().from(benchmarkLogs).where(eq(benchmarkLogs.runId, id)).orderBy(desc(benchmarkLogs.id)).limit(tail)).reverse();
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
}
+436
View File
@@ -3,6 +3,7 @@ import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
@@ -361,9 +362,17 @@ export type DockerHostInfo = {
network: string | null;
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
modelsSource: { type: "bind" | "volume"; source: string } | null;
/** Docker has the NVIDIA runtime / CDI devices, so GPUs can be requested. */
nvidia?: boolean;
/** GPUs found by a probe container (nvidia-smi); empty when none or not probed. */
gpus?: HostGpu[];
gpuError?: string | null;
gpuCheckedAt?: string | null;
checkedAt: string;
};
export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
// ---------------------------------------------------------------------------
@@ -372,6 +381,13 @@ export type DockerHostInfo = {
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
/**
* What the image computes on. nvidia: GPUs requested through Docker (NVIDIA Container Toolkit);
* dri: Intel/AMD GPUs via /dev/dri (Vulkan, SYCL, XPU); rocm: AMD via /dev/kfd + /dev/dri.
*/
export const RUNTIME_ACCELERATORS = ["cpu", "nvidia", "dri", "rocm"] as const;
export type RuntimeAccelerator = (typeof RUNTIME_ACCELERATORS)[number];
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
export type ImageState = (typeof IMAGE_STATES)[number];
@@ -379,6 +395,7 @@ export const runtimes = sqliteTable("runtimes", {
id: id(),
name: text("name").notNull(),
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
accelerator: text("accelerator", { enum: RUNTIME_ACCELERATORS }).notNull().default("cpu"),
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
image: text("image").notNull(),
description: text("description"),
@@ -422,3 +439,422 @@ export const localFolders = sqliteTable("local_folders", {
commit: text("commit"),
scannedAt: ts("scanned_at").notNull(),
});
// ---------------------------------------------------------------------------
// Deployments: a model served by a runtime container
// ---------------------------------------------------------------------------
/** What the worker is doing with the container. */
export const DEPLOYMENT_STATES = ["stopped", "starting", "running", "stopping", "failed"] as const;
export type DeploymentState = (typeof DEPLOYMENT_STATES)[number];
/** Launch options. Engine-specific fields are ignored by the other engine. */
export type DeploymentOptions = {
/** Model file (llama.cpp: the GGUF, first part of a split) or "" for the repo folder (vLLM). */
modelFile: string;
/** llama.cpp: multimodal projector. */
mmproj?: string | null;
/** llama.cpp: draft model (MTP head or a small draft model) for speculative decoding. */
draftFile?: string | null;
draftType?: "draft-mtp" | "draft-simple" | null;
contextSize: number;
threads?: number | null;
batchSize?: number | null;
ubatchSize?: number | null;
parallel?: number | null;
cacheTypeK?: string | null;
cacheTypeV?: string | null;
flashAttn?: "auto" | "on" | "off" | null;
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
webui?: boolean | null;
/** llama.cpp -cram: prompt cache in RAM, MiB (llama-server default 8192; 0 off, -1 unlimited). */
cacheRamMb?: number | null;
/** NVIDIA: GPU UUIDs to use (null: all). */
gpus?: string[] | null;
/** llama.cpp -ngl: "auto" (default), "all" or a number of layers. */
gpuLayers?: string | null;
/** llama.cpp -sm across several GPUs. */
splitMode?: "none" | "layer" | "row" | "tensor" | null;
/** llama.cpp -ts, e.g. "3,1". */
tensorSplit?: string | null;
/** llama.cpp: keep all MoE expert weights in RAM (-cmoe) or those of the first N layers (-ncmoe). */
cpuMoe?: boolean | null;
nCpuMoe?: number | null;
/** vLLM --tensor-parallel-size and --gpu-memory-utilization. */
tensorParallel?: number | null;
gpuMemoryUtilization?: number | null;
/** Only accept requests with one of the API keys from Settings → API keys. */
requireApiKey?: boolean | null;
/** vLLM */
dtype?: string | null;
maxNumSeqs?: number | null;
kvCacheGb?: number | null;
extraArgs: string[];
};
export type DeploymentStats = { cpuPercent: number; memoryBytes: number; memoryLimitBytes: number; at: string };
export const deployments = sqliteTable("deployments", {
id: id(),
name: text("name").notNull(),
runtimeId: text("runtime_id")
.notNull()
.references(() => runtimes.id),
modelId: text("model_id")
.notNull()
.references(() => models.id),
options: text("options", { mode: "json" }).$type<DeploymentOptions>().notNull(),
/** CPU limit in cores (fractions allowed) and memory limit; null = no limit. */
cpus: real("cpus"),
memoryMb: integer("memory_mb"),
/** Publish the API on this host port (optional; Kaname itself uses the Docker network). */
hostPort: integer("host_port"),
/** Set by the web app; the worker starts/stops the container to match. */
desiredState: text("desired_state", { enum: ["running", "stopped"] }).notNull().default("stopped"),
state: text("state", { enum: DEPLOYMENT_STATES }).notNull().default("stopped"),
/** Delete requested: the worker removes the container, then the row. */
deleteRequestedAt: ts("delete_requested_at"),
containerId: text("container_id"),
containerName: text("container_name"),
/** Command line the container was started with (for display and reproducibility). */
command: text("command", { mode: "json" }).$type<string[]>(),
imageId: text("image_id"),
startedAt: ts("started_at"),
readyAt: ts("ready_at"),
stoppedAt: ts("stopped_at"),
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
export const deploymentLogs = sqliteTable(
"deployment_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
deploymentId: text("deployment_id")
.notNull()
.references(() => deployments.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
/**
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
* hands them to the runtime container; never logged or written into a stored command line.
*/
export const apiKeys = sqliteTable("api_keys", {
id: id(),
name: text("name").notNull(),
key: text("key").notNull().unique(),
createdAt: createdAt(),
});
// ---------------------------------------------------------------------------
// Benchmarks (BetterBench runs against a running deployment)
// ---------------------------------------------------------------------------
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
/** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */
export type BenchmarkSettings = {
quick: boolean;
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. */
export type BenchmarkSnapshot = {
deploymentName: string;
repoId: string;
runtimeName: string;
engine: RuntimeEngine;
accelerator?: RuntimeAccelerator;
/** Names of the GPUs used (NVIDIA), for comparisons. */
gpuNames?: string[];
/** The Docker host when the run started. */
host?: { cpuModel: string | null; threads: number | null; memoryBytes: number | null; os: string | null };
image: string;
imageId: string | null;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
/** Rendered command (API keys masked). */
command: string;
};
/**
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
* or fills in a number; `null` means BetterBench didn't report it. The endpoint and host are never
* stored. `v` 2; older summaries (no `v`) are recomputed by the worker from results.json.
*/
export type BenchmarkSummary = {
v?: number;
combined: { decode: number | null; ttft_p50: number | null; itl_low1: number | null; update_p50: number | null; update_p99: number | null } | null;
single: {
category: string;
runs: number;
tokens?: number;
ttft_n?: number;
gap_n?: number;
ttft_p99_ok?: boolean;
tail_ok?: boolean;
ttft_p50: number | null;
ttft_p99: number | null;
update_p50?: number | null;
update_p99?: number | null;
tok_per_update: number | null;
batched?: boolean;
batched_runs?: number;
decode_med: number | null;
decode_iqr?: number | null;
decode_cv: number | null;
itl_low1: number | null;
itl_med?: number | null;
itl_high99?: number | null;
}[];
prefill: {
target_depth: number;
skipped: boolean;
prompt_tokens_med?: number | null;
ttft_p50?: number | null;
pp_low1?: number | null;
pp_med?: number | null;
pp_p99?: number | null;
pp_n?: number;
pp_tail_ok?: boolean;
}[];
concurrency: {
level: number;
ok: number;
requests: number;
aggregate_tps: number;
ttft_p50: number | null;
ttft_p99: number | null;
decode_med: number | null;
ttft_n?: number;
ttft_p99_ok?: boolean;
}[];
/** Thinking models: share of reasoning tokens and time to first answer token, where detectable. */
reasoning?: { category: string; runs: number; known: number; answered: number; never_answered: number; reasoning_share: number | null; ttfa_p50: number | null }[];
/** Percentiles resting on fewer samples than n · tail ≥ 5 requires (BetterBench's sample gate). */
gate?: { section: string; key: string | number; metric: string; n: number; need: number }[];
/** [runs stopped at max_tokens, ok runs] in the single-stream set. */
truncated?: [number, number];
failedSingle?: number;
phases: string[];
cacheHits: number;
betterbenchVersion: string;
corpusVersion: string;
corpusHash?: string | null;
timestamp?: string | null;
maxModelLen?: number | null;
config?: {
warmup?: number | null;
runs_per_category?: number | null;
temperature?: number | null;
top_p?: number | null;
top_k?: number | null;
greedy?: boolean | null;
unique_nonce?: boolean | null;
weights?: Record<string, number> | null;
concurrency_levels?: number[] | null;
concurrency_requests?: number | null;
prefill_runs?: number | null;
prefill_warmup?: number | null;
prefill_max_tokens?: number | null;
};
passes: number | null;
quick: boolean;
};
export const benchmarkRuns = sqliteTable(
"benchmark_runs",
{
id: id(),
/** Null once the deployment is deleted; the snapshot keeps what was measured. */
deploymentId: text("deployment_id"),
modelId: text("model_id"),
tool: text("tool").notNull().default("betterbench"),
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
snapshot: text("snapshot", { mode: "json" }).$type<BenchmarkSnapshot>().notNull(),
/** Free-form label, e.g. "q8 KV cache". */
label: text("label"),
state: text("state", { enum: BENCHMARK_STATES }).notNull().default("queued"),
phase: text("phase"),
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
error: text("error"),
summary: text("summary", { mode: "json" }).$type<BenchmarkSummary>(),
/** Files under BENCHMARKS_DIR/<id>/: 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<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
);
export const benchmarkLogs = sqliteTable(
"benchmark_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
runId: text("run_id").notNull(),
ts: integer("ts", { mode: "timestamp_ms" }).notNull(),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("benchmark_logs_idx").on(t.runId, t.id)],
);
// ---------------------------------------------------------------------------
// launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation)
// ---------------------------------------------------------------------------
/**
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
* published / failed.
*/
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
export type PublicationState = (typeof PUBLICATION_STATES)[number];
export const benchmarkPublications = sqliteTable(
"benchmark_publications",
{
id: id(),
runId: text("run_id").notNull(),
state: text("state", { enum: PUBLICATION_STATES }).notNull().default("preview"),
template: text("template").notNull().default("bench.betterbench.v1"),
title: text("title"),
summary: text("summary"),
/** Size of the exact payload from the dry run; the payload itself is a file next to the run. */
payloadBytes: integer("payload_bytes"),
previewedAt: ts("previewed_at"),
/** Who confirmed publishing (the second opt-in), and when. */
confirmedBy: text("confirmed_by"),
confirmedAt: ts("confirmed_at"),
url: text("url"),
guid: text("guid"),
publishedAt: ts("published_at"),
error: text("error"),
createdAt: createdAt(),
},
(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<string, unknown>;
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<SweepParam[]>().notNull(),
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
variants: text("variants", { mode: "json" }).$type<SweepVariant[]>().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(),
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { modelCandidates, servableBy } from "./deploy-candidates";
const f = (path: string, size = 10) => ({ path, size });
describe("modelCandidates", () => {
it("lists GGUF weights (split as first part), mmproj and MTP/draft files", () => {
const c = modelCandidates([
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
f("BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf"),
f("BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf"),
f("mmproj-F16.gguf"),
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"),
f("imatrix_unsloth.gguf"),
f("config.json"),
]);
assert.deepEqual(
c.gguf.map((g) => [g.path, g.parts]),
[
["Qwen3.8-27B-UD-Q4_K_XL.gguf", 1],
["BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", 2],
],
);
assert.deepEqual(c.mmproj.map((m) => m.path), ["mmproj-F16.gguf"]);
assert.deepEqual(c.drafts.map((d) => [d.path, d.type]), [["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "draft-mtp"]]);
assert.equal(c.vllm, null);
assert.ok(servableBy(c, "llama.cpp") && !servableBy(c, "vllm"));
});
it("recognizes a safetensors repo for vLLM", () => {
const c = modelCandidates([f("config.json", 1), f("model.safetensors", 100), f("tokenizer.json", 5)]);
assert.deepEqual(c.vllm, { size: 106 });
assert.equal(c.gguf.length, 0);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Which downloaded files a runtime can serve. Pure; shared by the server and the deployment form.
import type { RuntimeEngine } from "@/lib/db/schema";
import { groupSplitFiles } from "@/lib/file-groups";
import { fileRole } from "@/lib/file-roles";
export type LocalFile = { path: string; size: number };
export type CandidateFile = { path: string; size: number; parts: number };
export type DraftFile = CandidateFile & { type: "draft-mtp" | "draft-simple" };
export type ModelCandidates = {
/** llama.cpp: loadable GGUF weights (split files as their first part), plus optional extras. */
gguf: CandidateFile[];
mmproj: CandidateFile[];
drafts: DraftFile[];
/** vLLM: the repo folder has a config.json and safetensors weights. */
vllm: { size: number } | null;
};
const isGguf = (p: string) => p.toLowerCase().endsWith(".gguf");
/** `files`: the model's files that are on disk (present or verified). */
export function modelCandidates(files: LocalFile[]): ModelCandidates {
const entries = (pred: (p: string) => boolean) =>
groupSplitFiles(files.filter((f) => pred(f.path))).map((g) => ({ path: g.parts[0].path, size: g.size, parts: g.totalParts }));
const gguf = entries((p) => isGguf(p) && fileRole(p) === "model");
const mmproj = entries((p) => isGguf(p) && fileRole(p) === "vision");
const drafts: DraftFile[] = [
...entries((p) => isGguf(p) && fileRole(p) === "mtp").map((f) => ({ ...f, type: "draft-mtp" as const })),
...entries((p) => isGguf(p) && fileRole(p) === "draft").map((f) => ({ ...f, type: "draft-simple" as const })),
];
const hasConfig = files.some((f) => f.path === "config.json");
const safetensors = files.filter((f) => f.path.endsWith(".safetensors") && fileRole(f.path) === "model");
const vllm = hasConfig && safetensors.length > 0 ? { size: files.reduce((s, f) => s + f.size, 0) } : null;
return { gguf, mmproj, drafts, vllm };
}
export function servableBy(c: ModelCandidates, engine: RuntimeEngine): boolean {
return engine === "llama.cpp" ? c.gguf.length > 0 : c.vllm !== null;
}
+116
View File
@@ -0,0 +1,116 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildCommand, estimateMemoryMb, redactCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
describe("buildCommand", () => {
it("builds llama-server arguments with mmproj and MTP draft", () => {
const cmd = buildCommand({
engine: "llama.cpp",
model,
runtime: { env: {}, extraArgs: ["--jinja"] },
options: {
modelFile: "Qwen3-0.6B-Q4_K_M.gguf",
mmproj: "mmproj-F16.gguf",
draftFile: "MTP/mtp-Q4_0.gguf",
draftType: "draft-mtp",
contextSize: 4096,
threads: 8,
parallel: 1,
cacheTypeK: "q8_0",
extraArgs: ["--temp", "0.7"],
},
});
assert.equal(cmd.port, 8080);
assert.deepEqual(cmd.args.slice(0, 2), ["-m", "/models/unsloth/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q4_K_M.gguf"]);
const s = cmd.args.join(" ");
assert.match(s, /-c 4096 -t 8 -tb 8 -np 1 -ctk q8_0/);
assert.match(s, /--mmproj \/models\/unsloth\/Qwen3-0\.6B-GGUF\/mmproj-F16\.gguf/);
assert.match(s, /-md \/models\/unsloth\/Qwen3-0\.6B-GGUF\/MTP\/mtp-Q4_0\.gguf --spec-type draft-mtp/);
assert.ok(s.endsWith("--metrics --jinja --temp 0.7"));
assert.ok(!s.includes("-b "), "unset options are left out");
});
it("builds vllm serve arguments; deployment dtype and KV cache override the runtime", () => {
const cmd = buildCommand({
engine: "vllm",
model: { repoId: "HuggingFaceTB/SmolLM2-135M-Instruct", localPath: "HuggingFaceTB/SmolLM2-135M-Instruct" },
runtime: { env: { VLLM_CPU_KVCACHE_SPACE: "4" }, extraArgs: ["--dtype=bfloat16", "--enforce-eager"] },
options: { modelFile: "", contextSize: 2048, maxNumSeqs: 4, dtype: "float32", kvCacheGb: 2, extraArgs: [] },
});
assert.equal(cmd.port, 8000);
assert.equal(cmd.args[0], "/models/HuggingFaceTB/SmolLM2-135M-Instruct");
assert.equal(cmd.env.VLLM_CPU_KVCACHE_SPACE, "2");
const s = cmd.args.join(" ");
assert.ok(!s.includes("bfloat16") && s.includes("--dtype float32") && s.includes("--enforce-eager"));
assert.match(renderCommand("vllm/vllm-openai-cpu:v0.31.0", cmd), /^docker run -e VLLM_CPU_KVCACHE_SPACE=2 /);
const keep = buildCommand({
engine: "vllm",
model: { repoId: "a/b", localPath: "a/b" },
runtime: { env: {}, extraArgs: ["--dtype", "bfloat16"] },
options: { modelFile: "", contextSize: 2048, extraArgs: [] },
});
assert.ok(keep.args.join(" ").includes("--dtype bfloat16"));
});
it("turns llama.cpp's web UI off only when asked", () => {
const args = (webui?: boolean | null) =>
buildCommand({
engine: "llama.cpp",
model: { repoId: "a/b", localPath: "a/b" },
runtime: { env: {}, extraArgs: [] },
options: { modelFile: "m.gguf", contextSize: 2048, webui, extraArgs: [] },
}).args;
assert.ok(!args().includes("--no-webui") && !args(true).includes("--no-webui"));
assert.ok(args(false).includes("--no-webui"));
});
it("passes API keys via the environment and redacts them", () => {
const base = { model: { repoId: "a/b", localPath: "a/b" }, runtime: { env: {}, extraArgs: [] } };
const opts = { modelFile: "m.gguf", contextSize: 2048, requireApiKey: true, extraArgs: [] };
const llama = buildCommand({ ...base, engine: "llama.cpp", options: opts, apiKeys: ["sk-one-1234567890", "sk-two-1234567890"] });
assert.equal(llama.env.LLAMA_API_KEY, "sk-one-1234567890,sk-two-1234567890");
assert.ok(!llama.args.join(" ").includes("sk-"));
const shown = renderCommand("img", redactCommand(llama, ["sk-one-1234567890", "sk-two-1234567890"]));
assert.ok(!shown.includes("sk-") && shown.includes("<api-key>,<api-key>"));
const one = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["sk-one-1234567890"] });
assert.equal(one.env.VLLM_API_KEY, "sk-one-1234567890");
const two = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["k1-1234567890123456", "k2-1234567890123456"] });
assert.deepEqual(two.args.slice(two.args.indexOf("--api-key"), two.args.indexOf("--api-key") + 3), ["--api-key", "k1-1234567890123456", "k2-1234567890123456"]);
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
assert.equal(off.env.LLAMA_API_KEY, undefined);
});
it("adds GPU flags only on GPU runtimes", () => {
const model = { repoId: "a/b", localPath: "a/b" };
const options = { modelFile: "m.gguf", contextSize: 4096, gpuLayers: "all", splitMode: "layer" as const, nCpuMoe: 8, cacheRamMb: 1024, extraArgs: [] };
const gpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } }).args.join(" ");
assert.match(gpu, /-cram 1024 -ngl all -sm layer -ncmoe 8 --metrics/);
const cpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [] } }).args.join(" ");
assert.ok(cpu.includes("-cram 1024") && !cpu.includes("-ngl") && !cpu.includes("-ncmoe"));
const auto = buildCommand({ engine: "llama.cpp", model, options: { ...options, gpuLayers: "auto" }, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } });
assert.ok(!auto.args.includes("-ngl"));
const vllm = buildCommand({
engine: "vllm",
model,
options: { modelFile: "", contextSize: 4096, tensorParallel: 2, gpuMemoryUtilization: 0.85, kvCacheGb: 4, extraArgs: [] },
runtime: { env: {}, extraArgs: [], accelerator: "nvidia" },
});
assert.match(vllm.args.join(" "), /--tensor-parallel-size 2 --gpu-memory-utilization 0.85/);
assert.equal(vllm.env.VLLM_CPU_KVCACHE_SPACE, undefined);
});
it("counts the prompt cache and KV cache in the llama.cpp memory estimate", () => {
const file = 400 * 2 ** 20;
const small = estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024 });
const unset = estimateMemoryMb(file, 4096, "llama.cpp", {});
assert.ok(small > 2048 && small < 3072, String(small));
assert.equal(unset - small, 8192 - 1024);
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }) < small);
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, accelerator: "nvidia" }) < small);
});
});
+153
View File
@@ -0,0 +1,153 @@
// Container command lines for deployments, per engine type. Pure: used by the worker to start
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
/** Where the models folder is mounted inside every runtime container (read-only). */
export const CONTAINER_MODELS_DIR = "/models";
export const ENGINE_PORT: Record<RuntimeEngine, number> = { "llama.cpp": 8080, vllm: 8000 };
export type CommandInput = {
engine: RuntimeEngine;
options: DeploymentOptions;
model: { repoId: string; localPath: string };
/** `accelerator` unset: CPU. */
runtime: { env: Record<string, string>; extraArgs: string[]; accelerator?: RuntimeAccelerator };
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
apiKeys?: string[];
};
/** Stands in for key values in everything Kaname shows or stores. */
export const API_KEY_PLACEHOLDER = "<api-key>";
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
const inModels = (localPath: string, file?: string | null) =>
[CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/");
const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []);
const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []);
/** `args` without `flag` ("--flag value" or "--flag=value"). */
function withoutFlag(args: string[], flag: string): string[] {
const out: string[] = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === flag) i++;
else if (!args[i].startsWith(`${flag}=`)) out.push(args[i]);
}
return out;
}
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
const keys = o.requireApiKey ? apiKeys : [];
const gpu = !!runtime.accelerator && runtime.accelerator !== "cpu";
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
"-m",
inModels(model.localPath, o.modelFile),
"--host",
"0.0.0.0",
"--port",
String(port),
"-a",
model.repoId,
...num("-c", o.contextSize),
...num("-t", o.threads),
...num("-tb", o.threads),
...num("-b", o.batchSize),
...num("-ub", o.ubatchSize),
...num("-np", o.parallel),
...str("-ctk", o.cacheTypeK),
...str("-ctv", o.cacheTypeV),
...str("-fa", o.flashAttn),
...num("-cram", o.cacheRamMb),
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
...(o.webui === false ? ["--no-webui"] : []),
// GPU offload (-ngl defaults to "auto", which fits layers into free VRAM).
...(gpu ? str("-ngl", o.gpuLayers && o.gpuLayers !== "auto" ? o.gpuLayers : null) : []),
...(gpu ? str("-sm", o.splitMode) : []),
...(gpu ? str("-ts", o.tensorSplit) : []),
...(gpu && o.cpuMoe ? ["-cmoe"] : []),
...(gpu && !o.cpuMoe ? num("-ncmoe", o.nCpuMoe) : []),
"--metrics",
...runtime.extraArgs,
...o.extraArgs,
];
// Via the environment, not the command line; several keys as one comma-separated list.
const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) };
return { args, env, port };
}
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
const env = { ...runtime.env };
if (!gpu && o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
// VLLM_API_KEY holds a single key; more than one needs --api-key.
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
const args = [
inModels(model.localPath, o.modelFile || null),
"--host",
"0.0.0.0",
"--port",
String(port),
"--served-model-name",
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
...(gpu ? num("--tensor-parallel-size", o.tensorParallel) : []),
...(gpu ? num("--gpu-memory-utilization", o.gpuMemoryUtilization) : []),
...(keys.length > 1 ? ["--api-key", ...keys] : []),
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
...str("--dtype", o.dtype),
...o.extraArgs,
];
return { args, env, port };
}
/** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */
export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand {
const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v);
return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) };
}
/** Shell-style rendering for display ("docker run … image args"). */
export function renderCommand(image: string, cmd: ContainerCommand): string {
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`);
return ["docker run", ...env, `-v <models>:${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" ");
}
/** Rough memory need: model files plus KV cache and runtime overhead. */
/** llama-server's default --cache-ram (MiB): prompts kept in RAM for reuse. */
export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
const KV_TYPE_FACTOR: Record<string, number> = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 };
/**
* Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size
* per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA.
* Measured (llama.cpp b11429, Qwen3-0.6B Q4_K_M, ctx 4096): ~1.2 GiB without the prompt cache.
*/
export function estimateMemoryMb(
fileBytes: number,
contextSize: number,
engine: RuntimeEngine,
o: Pick<DeploymentOptions, "kvCacheGb" | "cacheRamMb" | "cacheTypeK" | "cacheTypeV"> & { accelerator?: RuntimeAccelerator } = {},
): number {
const model = fileBytes / 2 ** 20;
const gpu = !!o.accelerator && o.accelerator !== "cpu";
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
// On a GPU the weights and KV cache live in VRAM; RAM holds the processes.
if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072);
const perTokenKiB = 96 + 24 * Math.sqrt(model / 1024);
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
const kv = (contextSize * perTokenKiB * kvFactor) / 1024;
const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb;
// The memory-mapped model counts against the container's limit (page cache), even when offloaded.
return Math.ceil(model + (gpu ? 0 : kv) + cache + 768);
}
+328
View File
@@ -0,0 +1,328 @@
import "server-only";
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
import { quantGroup } from "@/lib/selection";
export class DeploymentError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
const int = (min: number, max: number) => z.number().int().min(min).max(max);
export const DeploymentBody = z.object({
name: z.string().trim().min(1).max(80),
runtimeId: z.string().min(1),
modelId: z.string().min(1),
options: z.object({
modelFile: z.string().max(1024),
mmproj: z.string().max(1024).nullable().optional(),
draftFile: z.string().max(1024).nullable().optional(),
draftType: z.enum(["draft-mtp", "draft-simple"]).nullable().optional(),
contextSize: int(128, 1_048_576),
threads: int(1, 1024).nullable().optional(),
batchSize: int(1, 65_536).nullable().optional(),
ubatchSize: int(1, 65_536).nullable().optional(),
parallel: int(1, 256).nullable().optional(),
cacheTypeK: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
webui: z.boolean().nullable().optional(),
requireApiKey: z.boolean().nullable().optional(),
cacheRamMb: int(-1, 1_048_576).nullable().optional(),
gpus: z.array(z.string().regex(/^GPU-[0-9a-f-]{36}$/i, "a GPU UUID")).max(64).nullable().optional(),
gpuLayers: z
.string()
.regex(/^(auto|all|\d{1,4})$/, "auto, all or a number")
.nullable()
.optional(),
splitMode: z.enum(["none", "layer", "row", "tensor"]).nullable().optional(),
tensorSplit: z
.string()
.regex(/^\d+(\.\d+)?(,\d+(\.\d+)?)*$/, "proportions like 3,1")
.nullable()
.optional(),
cpuMoe: z.boolean().nullable().optional(),
nCpuMoe: int(0, 1000).nullable().optional(),
tensorParallel: int(1, 64).nullable().optional(),
gpuMemoryUtilization: z.number().min(0.05).max(1).nullable().optional(),
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
maxNumSeqs: int(1, 1024).nullable().optional(),
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
extraArgs: z.array(z.string().max(4000).refine((a) => !/[\r\n\0]/.test(a), "single line")).max(100),
}),
cpus: z.number().min(0.1).max(1024).nullable().optional(),
memoryMb: int(256, 4_194_304).nullable().optional(),
hostPort: int(1024, 65_535).nullable().optional(),
});
export type DeploymentInput = z.infer<typeof DeploymentBody>;
/** Downloaded files of a model (selected and on disk). */
async function localFiles(modelId: string) {
return db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
}
export type DeployableModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
/** Library models with something a runtime can serve. */
export async function listDeployableModels(): Promise<DeployableModel[]> {
const rows = await db().select({ id: models.id, repoId: models.repoId, localPath: models.localPath }).from(models).orderBy(asc(models.repoId));
const files = await db()
.select({ modelId: modelFiles.modelId, path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
const byModel = new Map<string, { path: string; size: number }[]>();
for (const f of files) byModel.set(f.modelId, [...(byModel.get(f.modelId) ?? []), f]);
return rows
.map((m) => ({ ...m, candidates: modelCandidates(byModel.get(m.id) ?? []) }))
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
}
/** Check that runtime, model and files fit together; returns normalized options. */
async function validate(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
const runtime = await db().query.runtimes.findFirst({ where: eq(runtimes.id, input.runtimeId) });
if (!runtime) throw new DeploymentError("invalid", "Runtime not found.", 400);
const model = await db().query.models.findFirst({ where: eq(models.id, input.modelId) });
if (!model) throw new DeploymentError("invalid", "Model not found.", 400);
const c = modelCandidates(await localFiles(model.id));
if (!servableBy(c, runtime.engine)) {
throw new DeploymentError("invalid", `${model.repoId} has no downloaded files ${runtime.name} can serve.`, 400);
}
const o = input.options;
const options: DeploymentOptions = { ...o, extraArgs: o.extraArgs.map((a) => a.trim()).filter(Boolean) };
if (runtime.engine === "llama.cpp") {
if (!c.gguf.some((g) => g.path === o.modelFile)) throw new DeploymentError("invalid", "Pick one of the model's downloaded GGUF files.", 400);
if (o.mmproj && !c.mmproj.some((m) => m.path === o.mmproj)) throw new DeploymentError("invalid", "Unknown mmproj file.", 400);
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
options.draftType = draft?.type ?? null;
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null, tensorParallel: null, gpuMemoryUtilization: null });
} else {
Object.assign(options, {
modelFile: "",
mmproj: null,
draftFile: null,
draftType: null,
batchSize: null,
ubatchSize: null,
cacheTypeK: null,
cacheTypeV: null,
flashAttn: null,
webui: null,
cacheRamMb: null,
gpuLayers: null,
splitMode: null,
tensorSplit: null,
cpuMoe: null,
nCpuMoe: null,
});
}
// GPU settings only mean something on a GPU runtime; GPU picking only on NVIDIA.
if (runtime.accelerator === "cpu") {
Object.assign(options, { gpus: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, tensorParallel: null, gpuMemoryUtilization: null });
} else {
if (runtime.accelerator !== "nvidia") options.gpus = null;
options.kvCacheGb = null;
}
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
}
if (input.hostPort) {
const clash = await db().query.deployments.findFirst({
columns: { name: true },
where: and(eq(deployments.hostPort, input.hostPort), selfId ? ne(deployments.id, selfId) : undefined, isNull(deployments.deleteRequestedAt)),
});
if (clash) throw new DeploymentError("invalid", `Port ${input.hostPort} is already used by "${clash.name}".`, 409);
}
return options;
}
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
const options = await validate(input);
const [row] = await db()
.insert(deployments)
.values({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
desiredState: startNow ? "running" : "stopped",
})
.returning({ id: deployments.id });
return row;
}
async function get(id: string) {
const d = await db().query.deployments.findFirst({ where: and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)) });
if (!d) throw new DeploymentError("not_found", "Deployment not found.", 404);
return d;
}
/** Change launch options; only while stopped (a running container keeps its command). */
export async function updateDeployment(id: string, input: DeploymentInput) {
const d = await get(id);
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment before changing it.", 409);
const options = await validate(input, id);
await db()
.update(deployments)
.set({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
})
.where(eq(deployments.id, id));
}
export async function setDesiredState(id: string, desired: "running" | "stopped") {
const d = await get(id);
if (d.desiredState === desired) return;
await db()
.update(deployments)
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
.where(eq(deployments.id, id));
}
/** The worker stops the container and deletes the row. */
export async function requestDelete(id: string) {
await get(id);
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
}
const listColumns = {
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
hostPort: deployments.hostPort,
containerName: deployments.containerName,
command: deployments.command,
startedAt: deployments.startedAt,
readyAt: deployments.readyAt,
stoppedAt: deployments.stoppedAt,
exitCode: deployments.exitCode,
error: deployments.error,
stats: deployments.stats,
createdAt: deployments.createdAt,
runtimeId: deployments.runtimeId,
runtimeName: runtimes.name,
runtimeImage: runtimes.image,
accelerator: runtimes.accelerator,
sweepId: deployments.sweepId,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
};
export type DeploymentRow = Awaited<ReturnType<typeof listDeployments>>[number];
export async function listDeployments() {
return db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(desc(deployments.createdAt));
}
export async function getDeployment(id: string) {
const [row] = await db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)));
return row ?? null;
}
export async function listDeploymentLogs(id: string, afterId: number, tail = 500) {
const rows =
afterId > 0
? await db()
.select()
.from(deploymentLogs)
.where(and(eq(deploymentLogs.deploymentId, id), gt(deploymentLogs.id, afterId)))
.orderBy(asc(deploymentLogs.id))
.limit(2000)
: (
await db().select().from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(tail)
).reverse();
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
}
/** Deployments that use a model or runtime (deleting those is refused while any exist). */
export async function deploymentsUsing(by: { modelId?: string; runtimeId?: string }) {
return db()
.select({ id: deployments.id, name: deployments.name })
.from(deployments)
.where(
and(
isNull(deployments.deleteRequestedAt),
by.modelId ? eq(deployments.modelId, by.modelId) : undefined,
by.runtimeId ? eq(deployments.runtimeId, by.runtimeId) : undefined,
),
);
}
export type ModelDeployment = { id: string; name: string; state: DeploymentRow["state"]; desiredState: DeploymentRow["desiredState"]; runtimeName: string };
/** Deployments per model id (for links from the library and model pages). */
export async function deploymentsByModel(): Promise<Map<string, ModelDeployment[]>> {
const rows = await db()
.select({
modelId: deployments.modelId,
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
runtimeName: runtimes.name,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(asc(deployments.name));
const out = new Map<string, ModelDeployment[]>();
for (const { modelId, ...d } of rows) out.set(modelId, [...(out.get(modelId) ?? []), d]);
return out;
}
/** Form defaults for "Deploy" from the library: the first runtime with a pulled image that can serve the model. */
export async function deployPreset(modelId: string) {
const model = (await listDeployableModels()).find((m) => m.id === modelId);
if (!model) return null;
const rts = await db().select({ id: runtimes.id, engine: runtimes.engine }).from(runtimes).where(eq(runtimes.imageState, "present")).orderBy(asc(runtimes.createdAt));
const runtime = rts.find((r) => servableBy(model.candidates, r.engine));
if (!runtime) return null;
const gguf = runtime.engine === "llama.cpp" ? model.candidates.gguf[0] : undefined;
const quant = gguf ? quantGroup(gguf.path) : null;
return {
name: `${model.repoId.split("/")[1]}${quant ? ` ${quant}` : ""}`,
runtimeId: runtime.id,
modelId: model.id,
options: { modelFile: gguf?.path ?? "", mmproj: gguf ? (model.candidates.mmproj[0]?.path ?? null) : null, contextSize: 4096, extraArgs: [] },
cpus: null,
memoryMb: null,
hostPort: null,
};
}
+10
View File
@@ -0,0 +1,10 @@
// Download speed limit (Settings → Downloads). Shared by the settings API and the worker.
export const SPEED_LIMIT_KEY = "downloads.maxBytesPerSecond";
/** Smallest limit accepted (0.1 MB/s); below that hf's own timeouts start to bite. */
export const MIN_SPEED_LIMIT = 100_000;
/** The stored value as bytes per second, or null for no limit. */
export function parseSpeedLimit(v: unknown): number | null {
return typeof v === "number" && Number.isFinite(v) && v >= MIN_SPEED_LIMIT ? v : null;
}
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more