Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
276108932d | ||
|
|
1d2f908b75 | ||
|
|
4f05ee165c | ||
|
|
22a54f731d | ||
|
|
6b67c653b5 | ||
|
|
716bd8f2f0 | ||
|
|
e007a35143 | ||
|
|
ee6c623e2a | ||
|
|
981c4170fc | ||
|
|
93edb198d8 | ||
|
|
7b1c8070b3 |
No files matched your search
+283
-1
@@ -4,7 +4,289 @@ All notable changes to this project are documented here.
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
|
||||
step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
## [0.15.0] - 2026-10-26
|
||||
|
||||
Kaname is back to two jobs: downloading models, and benchmarking the servers that run them. It no
|
||||
longer starts servers itself. Benchmarks run against **endpoints**, any OpenAI-compatible server you
|
||||
add by URL (llama.cpp, vLLM, SGLang, Ollama, …), wherever it runs. The state before this release is
|
||||
kept in the branch `backup` and the tag `backup-0.14.3`.
|
||||
|
||||
**Upgrading:** replace `compose.yaml` with the new one from `deploy/` (the `docker-proxy` service and
|
||||
`DOCKER_HOST` are gone; a `sandbox` service and its volume are new) and run `docker compose up -d
|
||||
--remove-orphans`. Containers Kaname started for deployments keep running; stop them yourself if
|
||||
you don't need them. The database migrates on start: runtimes, deployments, sweeps, API tokens and
|
||||
their settings are deleted; benchmark runs, models and downloads stay.
|
||||
|
||||
### Added
|
||||
|
||||
- **Endpoints** (new top-level page): name, URL, optional API key, the model to benchmark, and
|
||||
**hardware notes** (GPUs, VRAM, PCIe link, P2P, ReBAR, driver, CPU, RAM, OS, virtualization,
|
||||
engine name/version, image, quant, KV cache, context, parallel slots, free text). **Test
|
||||
connection** lists the models the server serves and detects llama.cpp, vLLM, SGLang and Ollama
|
||||
with their version, context and slots where the server tells. The API key never reaches the
|
||||
browser, logs or runs; it goes to BetterBench only through its environment.
|
||||
- Runs against endpoints: BetterBench speed runs, paired A/B between two endpoints serving the same
|
||||
model (each with its own API key), and the quality eval. Kaname asks the server before queuing and
|
||||
again when the run starts; what it reports and the hardware notes are recorded with the run and
|
||||
go into BetterBench's notes and launch80 previews (never the URL or the endpoint's name).
|
||||
- A **sandbox** container for the quality eval's coding section: no network, read-only, no
|
||||
capabilities, memory/CPU/process limits, and only an exchange folder shared with the worker
|
||||
(replaces the throwaway containers the worker used to start through Docker).
|
||||
- Model pages list the benchmark runs of that model (when the endpoint serves it under its repo id).
|
||||
|
||||
### Removed
|
||||
|
||||
- Runtimes, deployments (and their logs, chat, stats), sweeps, the llama.cpp/vLLM presets and the
|
||||
resource/GPU telemetry sampled from deployment containers.
|
||||
- Hardware detection (Settings → Hardware, the probe containers, `pci.ids` in the image): Kaname
|
||||
can't see the machine behind an endpoint; describe it in the endpoint's hardware notes instead.
|
||||
- The API for programs and agents (`/api/v1`, API tokens, guardrails, approvals, the activity log,
|
||||
the agent skills and `docs/api.md`). Every route now requires the login.
|
||||
- Docker access: `DOCKER_HOST`, `KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` and the
|
||||
`docker-proxy` service.
|
||||
|
||||
### Changed
|
||||
|
||||
- Runs from before this release stay readable (with the deployment they measured), but can't be
|
||||
run again.
|
||||
|
||||
## [0.14.3] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads over Xet (any download with a file over 50 GB, or all of them with
|
||||
`HF_HUB_DISABLE_XET=false`) showed little or no progress. Xet keeps downloaded data in memory and
|
||||
writes the file in large chunks, sometimes minutes apart, so the bytes on disk don't show what has
|
||||
arrived. For Xet downloads the worker now turns on `hf`'s progress bars and reads its running
|
||||
byte count; the bars stay out of the job log. Ordinary downloads still measure the files on disk.
|
||||
|
||||
## [0.14.2] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- A running download's progress could jump back and forth between the real value and 0 B while
|
||||
`hf` kept downloading. A single progress reading that missed the partial file (a folder changing
|
||||
while the worker listed it, or a stale size on a network share) counted as nothing downloaded.
|
||||
Folders that vanish mid-listing are now skipped instead of failing the whole listing, and a file's
|
||||
progress no longer goes backwards during a run.
|
||||
|
||||
## [0.14.1] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads with a file over 50 GB failed with "The file is too large to be downloaded using the
|
||||
regular download method". `hf` (huggingface_hub 2.1.1) only downloads such files over Xet, which
|
||||
Kaname turns off by default for steady progress; a download that includes one now uses Xet (noted
|
||||
in the job log; its progress grows in bursts).
|
||||
|
||||
## [0.14.0] - 2026-10-21
|
||||
|
||||
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
|
||||
long-context retrieval, so a launch option that makes a model faster but worse shows up.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new column is added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
|
||||
with greedy decoding, a fixed seed and thinking turned off:
|
||||
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
|
||||
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
|
||||
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
|
||||
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
|
||||
context, sized with the server's own tokenizer.
|
||||
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
|
||||
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
|
||||
result records its version (`kaname-eval-1`).
|
||||
- The run page shows the score, each section and every item with the reason it failed. Compare views
|
||||
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
|
||||
("Also run the quality eval") and show it as a column.
|
||||
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
|
||||
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
|
||||
- The tuning skill checks quality after speed and reports both.
|
||||
|
||||
## [0.13.0] - 2026-10-21
|
||||
|
||||
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
|
||||
hardware: within guardrails you set, only on deployments its own token created, and by default only
|
||||
after you approve each start, run and sweep.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns and table are added on start. Existing
|
||||
tokens keep their scopes; grant the new ones with **Scopes** in Settings → API tokens.
|
||||
|
||||
### Added
|
||||
|
||||
- **Token scopes** `deployments:read`, `deployments:write`, `benchmarks:read`, `benchmarks:run`, and
|
||||
editing an existing token's scopes.
|
||||
- **`/api/v1` for deployments** ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1/runtimes`: pulled runtimes, what they serve, whether agents may use them and which
|
||||
extra arguments; the host's GPUs.
|
||||
- `GET /api/v1/deployments`, `GET /api/v1/deployments/{id}`: state, endpoint, options, the engine
|
||||
version and slots, live CPU/RAM; the log with `?log=N`.
|
||||
- `POST /api/v1/deployments` with the same validation, memory/VRAM estimate and `docker run`
|
||||
command as the form (returned in the answer); `dryRun: true` only checks. Unknown fields are
|
||||
refused instead of ignored.
|
||||
- `PATCH`, `POST …/start`, `POST …/stop`, `DELETE` for the token's own deployments.
|
||||
- **`/api/v1` for benchmarks**: `POST /api/v1/benchmarks` (run or A/B, quick or full, phases,
|
||||
description), `GET /api/v1/benchmarks/{id}` with a compact result (headline numbers, the run's
|
||||
hardware/runtime/model setup, GPU and RAM use; the full summary with `?full=1`), cancel, a list,
|
||||
`GET /api/v1/benchmarks/compare?ids=` (what differs, what's the same), and sweeps
|
||||
(`POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}`, cancel).
|
||||
- **`?wait=<seconds>`** (max 900) on the job, deployment, run and sweep status endpoints: the request
|
||||
returns once the state settles, so agents make one call instead of polling. Things that wait for
|
||||
approval answer right away.
|
||||
- **Guardrails for API deployments and benchmarks** (Settings → API tokens): approval (default: ask
|
||||
me), agent deployments at once (1), one agent run or sweep at a time and no agent start while one
|
||||
runs, time limits per run and sweep (30 min / 3 h, enforced by the worker), max sweep variants (8),
|
||||
a runtime allowlist, an allowlist of extra argument flags per engine (values can't be paths or
|
||||
URLs; the error names the argument), host ports only within a range (none by default), and caps
|
||||
for memory and CPUs (agent deployments always get a memory limit).
|
||||
- **Protected deployments**: the Protect button on a deployment's page. Agents can't edit, stop,
|
||||
delete or benchmark it, nor start anything on the same GPUs that would crowd it out of VRAM
|
||||
(estimated).
|
||||
- **Approval** for agent starts, runs and sweeps on the deployment, run and sweep pages; "awaiting
|
||||
approval" in the lists.
|
||||
- Everything an agent creates shows **requested by <token>**, with a filter in the deployment
|
||||
and benchmark lists; an **activity log** per token (Settings → API tokens) lists every request,
|
||||
including refusals with their error code.
|
||||
- **Agent skill for tuning** ([docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md)): check the
|
||||
limits, pick a runtime, deploy (dry run first), wait until ready, benchmark, change one variable at a
|
||||
time (or sweep), compare, report a compact table, stop the deployment; no polling loops, stop when
|
||||
something needs approval, never work around a guardrail.
|
||||
|
||||
### Changed
|
||||
|
||||
- The download skill and messages use `?wait=` instead of "check again later".
|
||||
|
||||
## [0.12.0] - 2026-10-21
|
||||
|
||||
Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group
|
||||
handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page
|
||||
"Intel GPUs".
|
||||
|
||||
No changes to `compose.yaml` or `.env`.
|
||||
|
||||
### Added
|
||||
|
||||
- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as
|
||||
NVIDIA (VRAM in use, utilization, power, temperature):
|
||||
- power and temperature from the GPU's hwmon sensors (energy counter or power reading);
|
||||
- AMD: VRAM in use and busy percent from sysfs;
|
||||
- Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the
|
||||
`xe`/`i915` drivers report them), read by a probe container that runs only during the run: host
|
||||
PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the
|
||||
end. Utilization is the busiest engine class, like `intel_gpu_top`.
|
||||
- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as
|
||||
sweep table columns.
|
||||
- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute
|
||||
buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs'
|
||||
VRAM, with a hint when it doesn't fit.
|
||||
- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render,
|
||||
video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the
|
||||
GPU.
|
||||
- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected.
|
||||
|
||||
### Changed
|
||||
|
||||
- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed
|
||||
by `-ngl auto`). Preset descriptions mention the B-series.
|
||||
- GPU figures a source doesn't report are now shown as "—" instead of 0.
|
||||
|
||||
## [0.11.0] - 2026-10-20
|
||||
|
||||
Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the
|
||||
runtime image and the engine version the server reports, model, quant and KV cache type, context and
|
||||
concurrency, plus a system summary and your own description. All of it is shown on the run page, in
|
||||
compare views and sweep tables, and goes to BetterBench and the launch80 preview.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns are added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Run metadata**, recorded when a run starts (single runs, A/B and sweep variants):
|
||||
- GPU count, name and VRAM; PCIe link, current and maximum (e.g. "Gen4 x8 of Gen5 x16"), read
|
||||
from sysfs at the card's upstream port (behind on-card switches like Intel's Arc B-series) or
|
||||
from `nvidia-smi`; peer-to-peer between GPUs (`nvidia-smi topo -p2p`, "n/a" with one GPU);
|
||||
Resizable BAR (on when a BAR covers the VRAM).
|
||||
- GPUs slow their link down when idle, so the current link is sampled during the run and the
|
||||
fastest one seen under load is recorded ("at idle" when it couldn't be sampled).
|
||||
- Runtime image, tag and registry digest, and the engine version the server reports once it's
|
||||
ready (llama.cpp `/props` build, vLLM `/version`, falling back to the startup log). Runtimes have
|
||||
an optional **engine name** for forks (e.g. `vllm-radiance`).
|
||||
- Model, quant and KV cache type (e.g. "Q4_K_M with q8_0 KV cache"), context length and
|
||||
concurrency (llama.cpp slots as reported by the server, vLLM max sequences).
|
||||
- **System summary** per run: CPU model, cores and threads, RAM, the disk holding the models
|
||||
folder, OS and kernel, GPU driver versions, VM or bare metal with GPU passthrough, Kaname version.
|
||||
Only these whitelisted facts; never the hostname, IP addresses, users or paths.
|
||||
- **Description** per run: set it when starting a run or edit it on the run page.
|
||||
- Everything goes to BetterBench as `--note`s (in `results.json` and its report) and into the
|
||||
launch80 dry-run preview as page sections (description, hardware and runtime, system), visible in
|
||||
the preview before anything is sent.
|
||||
- **Settings → Hardware**: what was detected, with manual values for what detection can't see (in a
|
||||
VM the PCIe link is the one the VM sees; new GPUs missing from the PCI ID list). New runs use them.
|
||||
- The run page shows the metadata; compare views get a "Hardware & runtime" section and a prefill
|
||||
row in the headline; sweep tables list the setup shared by all variants and show what differs as
|
||||
columns.
|
||||
- `scripts/intel-probe.sh`: read-only diagnostics for Intel GPU hosts (link, BARs, hwmon, DRM
|
||||
fdinfo, `/dev/dri` groups), for the upcoming Intel GPU support.
|
||||
|
||||
### Changed
|
||||
|
||||
- The image includes the PCI ID database (`pci.ids`) for GPU names.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A run or sweep with both "quick" and an explicit number of passes failed (BetterBench refuses
|
||||
`--quick` with `--passes`); the passes now win.
|
||||
- Agent skill (`docs/agent/SKILL.md`) works with how Hermes Agent runs commands: a `kaname` helper
|
||||
script (`docs/agent/kaname`) instead of a shell function that didn't survive between commands,
|
||||
`KANAME_URL`/`KANAME_TOKEN` declared in the frontmatter, and far less polling (none while a
|
||||
request waits for approval, one check around the ETA while downloading).
|
||||
|
||||
## [0.10.0] - 2026-10-20
|
||||
|
||||
An API for AI agents: a token-authenticated `/api/v1` lets a program look up models, request
|
||||
downloads and follow them, within guardrails you set and, by default, only after you approve each
|
||||
request.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/`
|
||||
through without forward auth (example in [docs/api.md](docs/api.md)). The new table is created on
|
||||
start.
|
||||
|
||||
### Added
|
||||
|
||||
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), name,
|
||||
scopes `models:read` and `downloads:create`, last used, revoke. Sent as
|
||||
`Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts nothing else (the rest of
|
||||
Kaname stays OIDC-only). No token can delete models or files, change settings, or manage runtimes
|
||||
or tokens.
|
||||
- **`/api/v1`**, compact JSON with actionable error messages ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1`: the token's name, scopes and the guardrails.
|
||||
- `GET /api/v1/hub/lookup?repo=`: commit SHA, quants and files with sizes (the Add model lookup).
|
||||
- `GET /api/v1/models`: the library with its search and filters (author, family, quant, tag,
|
||||
status, requested by) and the size on disk; `GET /api/v1/models/{id}`.
|
||||
- `POST /api/v1/downloads`: repo + pinned commit + a quant (weights plus the recommended companion
|
||||
files, as in Add model) or include globs, optional tags. Uses the same add-model and queue code
|
||||
as the UI. Repeating a request returns the existing model and job instead of queueing a
|
||||
duplicate; for a model already in the library it adds the missing files.
|
||||
- `GET /api/v1/jobs/{id}`: state, per-file progress, error; the `hf` log only with `?log=N`.
|
||||
- `GET /api/v1/disk`: free, used and reserved space on the models folder.
|
||||
- **Guardrails for API downloads** (Settings → API tokens): approval mode (default: requests wait
|
||||
as *pending approval* until you approve or reject them on the model or job page), max size per
|
||||
request (60 GB), free space that must remain after the download, counting what other open
|
||||
downloads still need (100 GB), API jobs at once (2), and an optional author allowlist. Rejecting a
|
||||
request removes a model it added, or restores the previous file selection.
|
||||
- Everything requested with a token shows **requested by <token name>** in the library, on the
|
||||
model and job pages, with a "Requested by" filter (and "awaiting approval" under Status).
|
||||
- **Agent skill** for Hermes Agent and similar ([docs/agent/SKILL.md](docs/agent/SKILL.md)): how to
|
||||
search, look up, request and monitor a download with `curl`, the guardrails, and to wait for
|
||||
approval instead of retrying.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings → API keys is now **Runtime API keys** (the keys deployments require), to keep it apart
|
||||
from API tokens.
|
||||
- Tests can now use the database: `npm test` runs with `--conditions=react-server`.
|
||||
|
||||
## [0.9.0] - 2026-10-13
|
||||
|
||||
|
||||
+6
-5
@@ -1,5 +1,6 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
|
||||
# One image for all services; the first argument picks the role: `web` (default), `worker` or
|
||||
# `sandbox` (runs the quality eval's coding answers, see compose.yaml).
|
||||
|
||||
FROM node:24-trixie-slim AS node
|
||||
|
||||
@@ -16,14 +17,14 @@ RUN npm run build \
|
||||
|
||||
# --- runtime -----------------------------------------------------------------
|
||||
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
|
||||
# has CA certificates and libstdc++, so no apt is needed.
|
||||
# has CA certificates and libstdc++, so no apt.
|
||||
FROM python:3.13-slim-trixie AS runtime
|
||||
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
|
||||
# BetterBench (Apache-2.0), the benchmark run against endpoints. 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 \
|
||||
@@ -46,8 +47,8 @@ RUN python -m venv /opt/hf \
|
||||
&& /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
|
||||
&& mkdir -p /data /models /sandbox \
|
||||
&& chown app:app /data /models /sandbox
|
||||
|
||||
ARG APP_VERSION=dev
|
||||
ENV PATH=/opt/hf/bin:$PATH \
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
<img src="docs/banner.png" alt="Kaname: self-hosted model manager for Hugging Face" width="100%" />
|
||||
</p>
|
||||
|
||||
**Kaname** (要, "the pivot") is a self-hosted web app for downloading and managing local LLMs from
|
||||
Hugging Face. Look up a repo, pick the quant you want, and Kaname downloads exactly those files with
|
||||
the official `hf` CLI, pinned to a specific commit so every download is reproducible.
|
||||
**Kaname** (要, "the pivot") is a self-hosted web app for downloading local LLMs from Hugging Face
|
||||
and benchmarking the servers that run them. Look up a repo, pick the quant you want, and Kaname
|
||||
downloads exactly those files with the official `hf` CLI, pinned to a specific commit so every
|
||||
download is reproducible. Point it at your llama.cpp, vLLM, SGLang or Ollama servers and it measures
|
||||
their speed and answer quality with [BetterBench](https://github.com/GGZ14/BetterBench).
|
||||
|
||||
- **Pick files, not whole repos:** one-click quant selection for GGUF repos, or include/exclude globs.
|
||||
- **Pinned and reproducible:** every model is pinned to the exact commit SHA you reviewed.
|
||||
@@ -12,8 +14,11 @@ the official `hf` CLI, pinned to a specific commit so every download is reproduc
|
||||
the browser; cancel any time.
|
||||
- **Find things again:** search and filter by author, model family (e.g. Qwen, Gemma), quant, status
|
||||
and your own tags like `roleplay` or `security`.
|
||||
- **Homelab-friendly:** two containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any
|
||||
folder or NAS share.
|
||||
- **Benchmark your endpoints:** speed runs, paired A/B tests and a quality eval against any
|
||||
OpenAI-compatible server, with the hardware you describe recorded next to every number; publish
|
||||
results to [launch80](https://launch80.com) if you like.
|
||||
- **Homelab-friendly:** a few containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any
|
||||
folder or NAS share. Kaname needs no access to Docker.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -82,25 +87,38 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
|
||||
model is flagged and your local copy is kept.
|
||||
- **Delete:** removes the model and, if you want, its files from disk.
|
||||
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
|
||||
(groundwork for testing model configs). See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
- **Endpoints:** add the URL (and API key, if any) of an OpenAI-compatible server under Endpoints.
|
||||
**Test connection** shows the models it serves and, where it tells, the engine, version and context.
|
||||
Describe the machine behind it (GPUs, PCIe link, CPU, RAM, OS, engine build, quant, KV cache):
|
||||
Kaname can't see it, and these notes go into every run so results stay comparable. The API key
|
||||
stays on the server.
|
||||
- **Benchmarks:** from an endpoint's page, start a BetterBench **speed** run (generation, prompt
|
||||
processing, parallel requests), a paired **A/B** against another endpoint serving the same model,
|
||||
or the **quality** eval (tool calling, coding, long-context retrieval; deterministic). Runs go one
|
||||
at a time. Select runs on the Benchmarks page to compare them; publish a run to launch80 after a
|
||||
preview and an explicit confirmation (needs `L80_TOKEN`). No host names or addresses are published.
|
||||
|
||||
## How it works
|
||||
|
||||
Two containers from the same image share one SQLite database:
|
||||
Three containers from the same image; web and worker share one SQLite database:
|
||||
|
||||
- **web:** Next.js UI and API, OIDC login (Auth.js); live updates via Server-Sent Events.
|
||||
- **worker:** runs the download queue, spawns `hf download --revision <sha> --include <files>`, and
|
||||
measures progress from bytes on disk. Only one worker runs at a time.
|
||||
measures progress from bytes on disk; runs benchmarks against endpoints (BetterBench, the quality
|
||||
eval). Only one worker runs at a time.
|
||||
- **sandbox:** runs the quality eval's coding answers (Python written by the model under test) with
|
||||
no network, a read-only filesystem, no capabilities and small limits. It shares only an exchange
|
||||
folder with the worker. Optional: without it the eval skips the coding section.
|
||||
|
||||
Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
|
||||
|
||||
- Interrupted files are **not resumed**: a re-run skips finished files and restarts unfinished ones.
|
||||
Kaname cleans up the leftover partial files.
|
||||
- With Xet transfers the partial file only grows in large bursts, so Kaname disables Xet by default
|
||||
to show accurate progress.
|
||||
to show accurate progress. Files over 50 GB can only be downloaded with Xet, so a download that
|
||||
includes one uses Xet anyway; its progress then comes from `hf`'s own byte counter (the file on
|
||||
disk can sit still for minutes while Xet holds the data in memory).
|
||||
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
|
||||
metadata after each download.
|
||||
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
|
||||
@@ -124,7 +142,7 @@ the image locally.
|
||||
| `npm test` | unit tests |
|
||||
| `npm run typecheck`, `npm run lint` | checks |
|
||||
| `npm run db:generate` | new migration after changing `src/lib/db/schema.ts` |
|
||||
| `npm run build:worker` | bundle worker + migrate script into `dist/` (used by the image) |
|
||||
| `npm run build:worker` | bundle worker, sandbox and migrate script into `dist/` (used by the image) |
|
||||
|
||||
**Releases:** bump `version` in `package.json`, add a `## [X.Y.Z]` section to
|
||||
[`CHANGELOG.md`](CHANGELOG.md), commit and push a `vX.Y.Z` tag. Gitea Actions
|
||||
|
||||
+18
-17
@@ -20,31 +20,32 @@ services:
|
||||
DATABASE_URL: file:/data/app.db
|
||||
MODELS_DIR: /models
|
||||
HF_HOME: /data/hf-home
|
||||
DOCKER_HOST: tcp://docker-proxy:2375
|
||||
volumes: [data:/data, models:/models]
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes: [data:/data, models:/models, sandbox:/sandbox]
|
||||
|
||||
web:
|
||||
<<: *app
|
||||
ports: ["${WEB_PORT:-3000}:3000"]
|
||||
volumes: [data:/data]
|
||||
|
||||
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
|
||||
# containers, images, networks, info. Not reachable from outside the compose network.
|
||||
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
|
||||
docker-proxy:
|
||||
image: tecnativa/docker-socket-proxy:v0.5.0
|
||||
environment:
|
||||
CONTAINERS: 1
|
||||
IMAGES: 1
|
||||
INFO: 1
|
||||
NETWORKS: 1
|
||||
POST: 1
|
||||
ALLOW_START: 1
|
||||
ALLOW_STOP: 1
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
sandbox:
|
||||
image: kaname:local
|
||||
command: sandbox
|
||||
network_mode: none
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 512m
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
volumes: [sandbox:/sandbox]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
data:
|
||||
models:
|
||||
sandbox:
|
||||
+20
-16
@@ -9,10 +9,11 @@ services:
|
||||
command: worker
|
||||
env_file: .env
|
||||
environment:
|
||||
DOCKER_HOST: tcp://docker-proxy:2375
|
||||
SANDBOX_DIR: /sandbox
|
||||
volumes:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
|
||||
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
|
||||
- sandbox:/sandbox # exchange folder with the code sandbox
|
||||
restart: unless-stopped
|
||||
|
||||
web:
|
||||
@@ -23,19 +24,22 @@ services:
|
||||
- ${KANAME_DATA_DIR:-./data}:/data
|
||||
restart: unless-stopped
|
||||
|
||||
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
|
||||
# containers, images, networks, info. Not reachable from outside the compose network.
|
||||
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
|
||||
docker-proxy:
|
||||
image: tecnativa/docker-socket-proxy:v0.5.0
|
||||
environment:
|
||||
CONTAINERS: 1
|
||||
IMAGES: 1
|
||||
INFO: 1
|
||||
NETWORKS: 1
|
||||
POST: 1
|
||||
ALLOW_START: 1
|
||||
ALLOW_STOP: 1
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
# Runs the quality eval's coding answers (Python written by the model under test) with no
|
||||
# network, a read-only root, no capabilities and small limits. It shares only the exchange folder
|
||||
# with the worker. Optional: without it the quality eval skips the coding section.
|
||||
sandbox:
|
||||
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
|
||||
command: sandbox
|
||||
network_mode: none
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=64m,mode=1777"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 512m
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
volumes: [sandbox:/sandbox]
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
sandbox:
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Usage: docker run <image> [web|worker|<any command>] (default: web)
|
||||
# Usage: docker run <image> [web|worker|sandbox|<any command>] (default: web)
|
||||
set -e
|
||||
|
||||
role="${1:-web}"
|
||||
@@ -25,5 +25,10 @@ esac
|
||||
case "$role" in
|
||||
web) exec node_modules/.bin/next start ;;
|
||||
worker) exec node dist/worker.mjs ;;
|
||||
sandbox)
|
||||
echo sandbox > /tmp/kaname-role
|
||||
require_writable "${SANDBOX_DIR:-/sandbox}"
|
||||
exec node dist/sandbox.mjs
|
||||
;;
|
||||
*) exec "$@" ;;
|
||||
esac
|
||||
@@ -3,6 +3,8 @@
|
||||
case "$(cat /tmp/kaname-role 2>/dev/null)" in
|
||||
# The worker touches this file on every heartbeat (every 5s).
|
||||
worker) find /tmp/kaname-worker-alive -mmin -1 | grep -q . ;;
|
||||
# The sandbox touches this every 2s.
|
||||
sandbox) find "${SANDBOX_DIR:-/sandbox}/.alive" -mmin -1 | grep -q . ;;
|
||||
web) node -e 'fetch("http://127.0.0.1:" + (process.env.PORT || 3000) + "/login").then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))' ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE `api_tokens` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`prefix` text NOT NULL,
|
||||
`hash` text NOT NULL,
|
||||
`scopes` text NOT NULL,
|
||||
`last_used_at` integer,
|
||||
`revoked_at` integer,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_tokens_hash_unique` ON `api_tokens` (`hash`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_tokens_name_uq` ON `api_tokens` (`name`);--> statement-breakpoint
|
||||
ALTER TABLE `jobs` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `models` ADD `requested_by` text;
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE `benchmark_runs` ADD `meta` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `meta_b` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `system` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `description` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `engine_info` text;--> statement-breakpoint
|
||||
ALTER TABLE `runtimes` ADD `image_digest` text;--> statement-breakpoint
|
||||
ALTER TABLE `runtimes` ADD `engine_name` text;
|
||||
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE `agent_activity` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`token_id` text NOT NULL,
|
||||
`token_name` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`target_type` text,
|
||||
`target_id` text,
|
||||
`outcome` text NOT NULL,
|
||||
`code` text,
|
||||
`message` text,
|
||||
`created_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `agent_activity_token_idx` ON `agent_activity` (`token_id`,`created_at`);--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `run_time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `protected` integer DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `start_requested_at` integer;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `benchmark_runs` ADD `quality` text;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Approvals were for API requests, which are gone; anything still waiting is cancelled.
|
||||
UPDATE `jobs` SET `state` = 'cancelled', `finished_at` = unixepoch() * 1000 WHERE `state` = 'pending_approval';--> statement-breakpoint
|
||||
UPDATE `benchmark_runs` SET `state` = 'cancelled', `finished_at` = unixepoch() * 1000 WHERE `state` = 'pending_approval';--> statement-breakpoint
|
||||
DELETE FROM `settings` WHERE `key` IN ('agent.guardrails', 'agent.tuning', 'hardware.overrides', 'runtimes.presetsSeeded', 'runtimes.cudaPresetSeeded', 'runtimes.intelPresetSeeded');--> statement-breakpoint
|
||||
DROP TABLE `agent_activity`;--> statement-breakpoint
|
||||
DROP TABLE `api_keys`;--> statement-breakpoint
|
||||
DROP TABLE `api_tokens`;--> statement-breakpoint
|
||||
DROP TABLE `benchmark_sweeps`;--> statement-breakpoint
|
||||
DROP TABLE `deployment_logs`;--> statement-breakpoint
|
||||
DROP TABLE `deployments`;--> statement-breakpoint
|
||||
DROP TABLE `runtimes`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `deployment_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `deployment_b_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `resources`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `sweep_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` DROP COLUMN `time_limit_s`;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `jobs` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `models` DROP COLUMN `requested_by_token_id`;--> statement-breakpoint
|
||||
ALTER TABLE `models` DROP COLUMN `requested_by`;--> statement-breakpoint
|
||||
ALTER TABLE `worker_state` DROP COLUMN `docker`;
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE `endpoints` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`base_url` text NOT NULL,
|
||||
`api_key` text,
|
||||
`model` text,
|
||||
`engine` text,
|
||||
`hardware` text DEFAULT '{}' NOT NULL,
|
||||
`probe` text,
|
||||
`created_at` integer NOT NULL,
|
||||
`updated_at` integer NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `endpoints_name_uq` ON `endpoints` (`name`);--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `endpoint_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `endpoint_b_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
@@ -120,6 +120,48 @@
|
||||
"when": 1791658947930,
|
||||
"tag": "0016_ab_resources_sweeps",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 17,
|
||||
"version": "6",
|
||||
"when": 1792504668583,
|
||||
"tag": "0017_api_tokens",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 18,
|
||||
"version": "6",
|
||||
"when": 1792513935880,
|
||||
"tag": "0018_benchmark_metadata",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 19,
|
||||
"version": "6",
|
||||
"when": 1792587768766,
|
||||
"tag": "0019_agent_tuning",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 20,
|
||||
"version": "6",
|
||||
"when": 1792588720328,
|
||||
"tag": "0020_quality_eval",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 21,
|
||||
"version": "6",
|
||||
"when": 1793045191010,
|
||||
"tag": "0021_slim_down",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 22,
|
||||
"version": "6",
|
||||
"when": 1793045228739,
|
||||
"tag": "0022_endpoints",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.15.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.15.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.15.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
@@ -13,8 +13,8 @@
|
||||
"typecheck": "next typegen && tsc --noEmit",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
|
||||
"test": "tsx --test \"src/**/*.test.ts\"",
|
||||
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs"
|
||||
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
|
||||
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/sandbox.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
|
||||
@@ -9,8 +9,7 @@ import {
|
||||
LanguagesIcon,
|
||||
ListChecksIcon,
|
||||
MessagesSquareIcon,
|
||||
PlusIcon,
|
||||
RocketIcon,
|
||||
GaugeIcon,
|
||||
ScaleIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -19,14 +18,15 @@ 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 { BenchmarkStateBadge } from "@/components/benchmark-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 { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { headline, targetName } from "@/lib/benchmark-view";
|
||||
import { fetchModelCard } from "@/lib/hub/client";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { listModelJobs } from "@/lib/jobs";
|
||||
@@ -101,17 +101,14 @@ 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, byModel, deployable] = await Promise.all([
|
||||
const [tags, related, card, worker, recentJobs, runs] = 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(),
|
||||
listBenchmarks({ modelId: model.id }),
|
||||
]);
|
||||
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
|
||||
@@ -151,15 +148,6 @@ 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}
|
||||
@@ -304,28 +292,26 @@ 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">
|
||||
{runs.length > 0 && (
|
||||
<SideCard title="Benchmarks" icon={GaugeIcon}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{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-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 className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
|
||||
</span>
|
||||
</span>
|
||||
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
</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>
|
||||
)}
|
||||
);
|
||||
})}
|
||||
<Link href={`/benchmarks?model=${model.id}`} className="self-start px-2 text-xs text-muted-foreground hover:text-foreground">
|
||||
All runs of this model →
|
||||
</Link>
|
||||
</div>
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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 { CONFIG_ROWS, targetName } from "@/lib/benchmark-view";
|
||||
import type { PairedResult } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
@@ -75,8 +74,8 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
<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>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${targetName(a)} vs ${targetName(b)}`}</h2>
|
||||
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, targetName(a), targetName(b))}</p>
|
||||
</header>
|
||||
|
||||
<section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
@@ -99,8 +98,8 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
</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" />
|
||||
<Side label="A · decode, mean" name={targetName(a)} value={d.mean_a} unit="t/s" />
|
||||
<Side label="B · decode, mean" name={targetName(b)} 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>
|
||||
@@ -136,8 +135,8 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
<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>
|
||||
<th className="px-3 py-2 font-medium">A · {targetName(a)}</th>
|
||||
<th className="px-3 py-2 font-medium">B · {targetName(b)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -161,13 +160,6 @@ export function AbReport({ run }: { run: ListRow }) {
|
||||
{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">
|
||||
|
||||
@@ -31,10 +31,12 @@ 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 { CONFIG_ROWS, describeSettings, engineName, isEndpointSnapshot, modelName, targetName } from "@/lib/benchmark-view";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import { cancelBenchmark, deleteBenchmark, renameBenchmark } from "../actions";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
|
||||
import { AbReport } from "./ab-report";
|
||||
import { QualityReport } from "./quality-report";
|
||||
import { BenchmarkReport } from "./benchmark-report";
|
||||
import { PublishCard } from "./publish-card";
|
||||
|
||||
@@ -58,6 +60,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
const [r, setR] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [label, setLabel] = useState(initial.label ?? "");
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const active = r.state === "queued" || r.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
@@ -73,14 +76,17 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
}, [active, r.id]);
|
||||
|
||||
async function again() {
|
||||
if (!r.deploymentId) return;
|
||||
if (!r.endpointId) 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,
|
||||
endpointId: r.endpointId,
|
||||
endpointBId: r.kind === "ab" ? r.endpointBId : null,
|
||||
model: modelName(r.snapshot),
|
||||
kind: r.kind,
|
||||
label: r.label,
|
||||
description: r.description,
|
||||
...r.settings,
|
||||
}),
|
||||
});
|
||||
@@ -93,7 +99,18 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
}
|
||||
|
||||
const s = r.snapshot;
|
||||
const sB = r.snapshotB;
|
||||
const sum = r.summary;
|
||||
// Runs from before 0.15 measured a deployment (gone now); newer ones an endpoint.
|
||||
const legacy = !isEndpointSnapshot(s);
|
||||
const endpointLink = (id: string | null, name: string) =>
|
||||
legacy ? name : id ? (
|
||||
<Link href={`/endpoints/${id}`} className="hover:underline">
|
||||
{name}
|
||||
</Link>
|
||||
) : (
|
||||
`${name} (deleted)`
|
||||
);
|
||||
const took = duration(r.startedAt, r.finishedAt, now);
|
||||
|
||||
return (
|
||||
@@ -103,10 +120,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
<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)}
|
||||
{r.label ?? (r.kind === "ab" && sB ? `${targetName(s)} vs ${targetName(sB)}` : targetName(s))}
|
||||
</h1>
|
||||
{r.kind === "ab" && (
|
||||
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
|
||||
@@ -119,56 +133,24 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{r.deploymentId ? (
|
||||
<Link
|
||||
href={`/deployments/${r.deploymentId}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{s.deploymentName}
|
||||
</Link>
|
||||
) : (
|
||||
`${s.deploymentName} (deleted)`
|
||||
)}{" "}
|
||||
·{" "}
|
||||
{endpointLink(r.endpointId, targetName(s))} ·{" "}
|
||||
{r.modelId ? (
|
||||
<Link href={`/${s.repoId}`} className="hover:underline">
|
||||
{s.repoId}
|
||||
<Link href={`/models/${r.modelId}`} className="hover:underline">
|
||||
{modelName(s)}
|
||||
</Link>
|
||||
) : (
|
||||
s.repoId
|
||||
modelName(s)
|
||||
)}{" "}
|
||||
· {s.runtimeName}
|
||||
{r.kind === "ab" && r.snapshotB && (
|
||||
· {engineName(s)}
|
||||
{r.kind === "ab" && sB && (
|
||||
<>
|
||||
{" "}
|
||||
· 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>
|
||||
· B: {endpointLink(r.endpointBId, targetName(sB))} ({engineName(sB)})
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
BetterBench ·{" "}
|
||||
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
|
||||
{r.kind === "ab"
|
||||
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
|
||||
: describeSettings(r.settings)}{" "}
|
||||
@@ -210,12 +192,12 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
Cancel
|
||||
</Button>
|
||||
) : (
|
||||
r.deploymentId &&
|
||||
!r.sweepId && (
|
||||
r.endpointId &&
|
||||
(r.kind !== "ab" || r.endpointBId) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={again}
|
||||
title="Queue a new run with the same settings (the deployment must be running)"
|
||||
title="Queue a new run with the same settings against the same endpoint"
|
||||
>
|
||||
<RotateCcwIcon />
|
||||
Run again
|
||||
@@ -281,7 +263,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
|
||||
{r.kind === "ab" ? <AbReport run={r} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
|
||||
<LiveLog
|
||||
url={`/api/benchmarks/${r.id}/logs`}
|
||||
title="BetterBench output"
|
||||
@@ -293,7 +275,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
{r.kind === "run" && r.state === "completed" && r.summary && (
|
||||
<PublishCard
|
||||
runId={r.id}
|
||||
defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`}
|
||||
defaultTitle={r.label ?? `${modelName(s).split("/").pop()} ${weightsLabel(s)}`}
|
||||
defaultSummary={reportSummary(r)}
|
||||
/>
|
||||
)}
|
||||
@@ -318,10 +300,34 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{r.kind === "run" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Description</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-1.5">
|
||||
<textarea
|
||||
value={description}
|
||||
maxLength={4000}
|
||||
rows={3}
|
||||
placeholder="What this run tries out, e.g. q8_0 KV cache to fit 64k context"
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onBlur={async () =>
|
||||
description !== (r.description ?? "") &&
|
||||
(await describeBenchmark(r.id, description || null)) &&
|
||||
setR({ ...r, description: description.trim() || null })
|
||||
}
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Passed to BetterBench (when set before the run starts) and to the launch80 preview, together with the system summary.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
|
||||
{r.kind !== "ab" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Settings measured</CardTitle>
|
||||
<CardTitle>{legacy ? "Settings measured" : "Setup"}</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">
|
||||
@@ -335,15 +341,20 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
);
|
||||
})}
|
||||
</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" />
|
||||
{!isEndpointSnapshot(s) && (
|
||||
<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>
|
||||
<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>
|
||||
)}
|
||||
{isEndpointSnapshot(s) && s.hardware.description && (
|
||||
<p className="text-xs whitespace-pre-wrap text-muted-foreground">{s.hardware.description}</p>
|
||||
)}
|
||||
{sum && (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
BetterBench {sum.betterbenchVersion} · corpus v
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
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 { configChips, engineName, modelName } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
@@ -79,7 +78,7 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
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>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${modelName(s)} ${weightsLabel(s) !== "safetensors" && !modelName(s).includes(weightsLabel(s)) ? weightsLabel(s) : ""}`.trim()}</h2>
|
||||
<p className="text-sm text-muted-foreground">{reportSubtitle(run)}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
@@ -88,7 +87,7 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
{x}
|
||||
</span>
|
||||
))}
|
||||
<span className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">{s.runtimeName}</span>
|
||||
<span className="rounded-md border px-2 py-0.5 font-mono text-[11px] text-muted-foreground">{engineName(s)}</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}
|
||||
@@ -200,12 +199,6 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
|
||||
</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">
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getBenchmark } from "@/lib/benchmarks";
|
||||
import { targetName } from "@/lib/benchmark-view";
|
||||
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" };
|
||||
return { title: run ? `${run.label ?? targetName(run.snapshot)} · Benchmark` : "Benchmark" };
|
||||
}
|
||||
|
||||
export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
|
||||
|
||||
@@ -190,6 +190,12 @@ export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: st
|
||||
</span>
|
||||
))}
|
||||
</dd>
|
||||
{p.sections.map((s) => (
|
||||
<div key={s.heading} className="contents">
|
||||
<dt className="text-muted-foreground">{s.heading}</dt>
|
||||
<dd className="whitespace-pre-line">{s.body}</dd>
|
||||
</div>
|
||||
))}
|
||||
<dt className="text-muted-foreground">Data</dt>
|
||||
<dd>{p.phases.join(", ")} · every raw sample</dd>
|
||||
<dt className="text-muted-foreground">Removed</dt>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import type { QualityResult } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** A quality eval's result: the score, each section's pass rate and every item. */
|
||||
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
|
||||
if (!quality) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quality</CardTitle>
|
||||
<CardDescription>
|
||||
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
|
||||
{quality.config.thinking ? "on" : "off"}
|
||||
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
|
||||
only results of the same eval set compare.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
|
||||
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Section</TableHead>
|
||||
<TableHead className="text-right">Passed</TableHead>
|
||||
<TableHead className="text-right">Score</TableHead>
|
||||
<TableHead className="text-right">Time</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{quality.sections.map((s) => (
|
||||
<TableRow key={s.section}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
|
||||
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
|
||||
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<ul className="flex flex-col gap-1 text-xs">
|
||||
{quality.items.map((i) => (
|
||||
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
|
||||
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
|
||||
<span className="font-mono">{i.id}</span>
|
||||
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -13,3 +13,4 @@ async function call(url: string, method: string, body?: unknown): Promise<boolea
|
||||
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 });
|
||||
export const describeBenchmark = (id: string, description: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { description });
|
||||
@@ -4,16 +4,27 @@ import { GaugeIcon, GitCompareIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
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 {
|
||||
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 { configChips, describeSettings, engineName, headline, modelName, targetName } from "@/lib/benchmark-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
|
||||
export type ListRow = Omit<
|
||||
BenchmarkRow,
|
||||
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
|
||||
> & {
|
||||
createdAt: string;
|
||||
startedAt: string | null;
|
||||
finishedAt: string | null;
|
||||
@@ -21,31 +32,47 @@ export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt
|
||||
};
|
||||
|
||||
const MAX_COMPARE = 16;
|
||||
const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
|
||||
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 }) {
|
||||
export function BenchmarkList({
|
||||
rows: initial,
|
||||
compact,
|
||||
filter,
|
||||
}: {
|
||||
rows: ListRow[];
|
||||
compact?: boolean;
|
||||
/** The list's filter, kept when polling: an endpoint's or a model's runs. */
|
||||
filter?: { endpoint?: string; model?: string };
|
||||
}) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
// "" = every endpoint, else an endpoint's name.
|
||||
const [by, setBy] = useState("");
|
||||
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
|
||||
const targets = [...new Set(rows.map((r) => targetName(r.snapshot)))].sort();
|
||||
const shown = rows.filter((r) => !by || targetName(r.snapshot) === by);
|
||||
|
||||
const query = new URLSearchParams(Object.entries(filter ?? {}).filter((e): e is [string, string] => !!e[1])).toString();
|
||||
|
||||
useEffect(() => {
|
||||
if (!busy || compact) return;
|
||||
const t = setInterval(async () => {
|
||||
const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(() => null);
|
||||
const res = await fetch(`/api/benchmarks${query ? `?${query}` : ""}`, { cache: "no-store" }).catch(() => null);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}, 3_000);
|
||||
return () => clearInterval(t);
|
||||
}, [busy, compact]);
|
||||
}, [busy, compact, query]);
|
||||
|
||||
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
|
||||
No benchmarks yet. Open an{" "}
|
||||
<Link href="/endpoints" className="underline">
|
||||
endpoint
|
||||
</Link>{" "}
|
||||
and start one there.
|
||||
</p>
|
||||
@@ -53,22 +80,53 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
);
|
||||
}
|
||||
|
||||
const toggle = (id: string) => setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : s.length < MAX_COMPARE ? [...s, id] : s));
|
||||
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>
|
||||
{!compact && (comparable.length > 1 || targets.length > 1) && (
|
||||
<div className="flex flex-wrap 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>
|
||||
<span className="flex items-center gap-2">
|
||||
{targets.length > 1 && (
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
aria-label="Endpoint"
|
||||
>
|
||||
<option value="">All endpoints</option>
|
||||
{targets.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<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>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Card className="py-0">
|
||||
@@ -78,67 +136,111 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
{!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">
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Weighted single-stream decode speed"
|
||||
>
|
||||
Decode t/s
|
||||
</TableHead>
|
||||
<TableHead className="text-right" title="Median time to first token">
|
||||
<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">
|
||||
<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">
|
||||
<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) => {
|
||||
{shown.map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const s = r.snapshot;
|
||||
return (
|
||||
<TableRow key={r.id} data-state={selected.includes(r.id) ? "selected" : undefined}>
|
||||
<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`}
|
||||
aria-label={`Select ${r.label ?? targetName(s)} for comparison`}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/benchmarks/${r.id}`} className="font-medium hover:underline">
|
||||
{r.label ?? s.deploymentName}
|
||||
<Link
|
||||
href={`/benchmarks/${r.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{r.label ?? targetName(s)}
|
||||
</Link>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{r.label && `${s.deploymentName} · `}
|
||||
{s.repoId} · <LocalTime value={r.createdAt} />
|
||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{r.label && `${targetName(s)} · `}
|
||||
{modelName(s)} · <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>
|
||||
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">
|
||||
{engineName(s)}
|
||||
</span>
|
||||
{configChips(s).map((c) => (
|
||||
<span key={c} className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<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>
|
||||
<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}>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{r.kind === "eval" ? (
|
||||
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
|
||||
) : (
|
||||
fmt(h.decode)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
|
||||
</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}>
|
||||
<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} />
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@@ -4,14 +4,16 @@ 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 { metaRows } from "@/lib/benchmark-meta";
|
||||
import { SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { CONFIG_ROWS, deltaPct, describeSettings, headline, targetName } 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 };
|
||||
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
|
||||
|
||||
/** Differences smaller than this are shown without color: below what a single run can resolve. */
|
||||
const NOISE_PCT = 2;
|
||||
@@ -62,6 +64,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
{
|
||||
group: "Headline",
|
||||
rows: [
|
||||
{ label: "Prefill (deepest prompt)", unit: "t/s", higherIsBetter: true, digits: 0, get: (s) => headline(s).prefill?.tps ?? null },
|
||||
{ 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 },
|
||||
],
|
||||
@@ -85,8 +88,30 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
|
||||
},
|
||||
];
|
||||
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
|
||||
const quality = runs.map((r) => r.quality);
|
||||
if (quality.some(Boolean)) {
|
||||
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
|
||||
groups.push({
|
||||
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
|
||||
rows: [
|
||||
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
|
||||
...sections.map((sec) => ({
|
||||
label: SECTION_LABEL[sec],
|
||||
unit: "%",
|
||||
higherIsBetter: true,
|
||||
digits: 1,
|
||||
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
|
||||
})),
|
||||
],
|
||||
});
|
||||
}
|
||||
const metrics = groups.filter((g) => g.rows.length > 0);
|
||||
|
||||
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
|
||||
const metaByRun = runs.map((r) => (r.meta ? metaRows(r.meta) : null));
|
||||
const metaKeys = [...new Map(metaByRun.flatMap((rows) => rows ?? []).map((x) => [x.key, x.label])).entries()];
|
||||
const metaTable = metaKeys.map(([key, label]) => ({ key, label, values: metaByRun.map((rows) => (rows ? (rows.find((x) => x.key === key)?.value ?? null) : null)) }));
|
||||
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);
|
||||
@@ -110,7 +135,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
{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}
|
||||
{r.label ?? targetName(r.snapshot)}
|
||||
</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>}
|
||||
@@ -122,6 +147,28 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{metaTable.length > 0 && (
|
||||
<>
|
||||
<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">
|
||||
Hardware & runtime
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{metaTable.map(({ key, label, values }) => {
|
||||
const differs = new Set(values.map((v) => v ?? "")).size > 1;
|
||||
return (
|
||||
<TableRow key={`meta-${key}`} className={cn(differs && "bg-amber-500/5")}>
|
||||
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{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">not recorded</span>}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
<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
|
||||
@@ -159,7 +206,7 @@ function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{rows.map((m) => {
|
||||
const vals = sums.map((s) => m.get(s));
|
||||
const vals = sums.map((s, i) => m.get(s, i));
|
||||
const present = vals.filter((v): v is number => v != null);
|
||||
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
|
||||
return (
|
||||
|
||||
@@ -1,21 +1,44 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getModel } from "@/lib/library";
|
||||
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();
|
||||
export default async function BenchmarksPage({ searchParams }: PageProps<"/benchmarks">) {
|
||||
const modelId = (await searchParams).model;
|
||||
const model = typeof modelId === "string" ? await getModel(modelId) : null;
|
||||
const rows = await listBenchmarks({ modelId: model?.model.id });
|
||||
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.
|
||||
{model ? (
|
||||
<>
|
||||
Runs of{" "}
|
||||
<Link href={`/${model.model.repoId}`} className="underline">
|
||||
{model.model.repoId}
|
||||
</Link>
|
||||
.{" "}
|
||||
<Link href="/benchmarks" className="underline">
|
||||
Show all
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Speed (BetterBench), A/B and quality runs against your{" "}
|
||||
<Link href="/endpoints" className="underline">
|
||||
endpoints
|
||||
</Link>
|
||||
. Start one from an endpoint; select runs to compare their settings and numbers.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} />
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(rows))} filter={{ model: model?.model.id }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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))} />;
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
"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'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>
|
||||
);
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
"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'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'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>
|
||||
);
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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))} />;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
"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
@@ -1,107 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
"use client";
|
||||
|
||||
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Loader2Icon } 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, 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 { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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" | "quality";
|
||||
type Peer = { id: string; name: string; model: string | null; models: string[] };
|
||||
|
||||
/** Benchmark an endpoint: a BetterBench run, a paired A/B against another endpoint, or the quality eval. */
|
||||
export function BenchmarkStart({ endpoint, peers }: { endpoint: { id: string; name: string; model: string | null; models: string[] }; peers: Peer[] }) {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<Mode>("run");
|
||||
const [model, setModel] = useState(endpoint.model ?? "");
|
||||
const [mode, setMode] = useState("quick");
|
||||
const [passes, setPasses] = useState("10");
|
||||
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [peerId, setPeerId] = useState("");
|
||||
const [mde, setMde] = useState("1");
|
||||
const [maxPairs, setMaxPairs] = useState("200");
|
||||
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
|
||||
|
||||
// The model a run requests: the one picked here, the endpoint's, or the only one it serves.
|
||||
const runModel = model || (endpoint.models.length === 1 ? endpoint.models[0] : "");
|
||||
const peer = peers.find((p) => p.id === peerId);
|
||||
const peerServes = !peer || !runModel || peer.models.length === 0 || peer.models.includes(runModel);
|
||||
|
||||
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({ endpointId: endpoint.id, model: runModel || null, label: label.trim() || null, description: description.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 TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
|
||||
{ id: "run", label: "Speed", icon: GaugeIcon },
|
||||
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
|
||||
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
|
||||
];
|
||||
|
||||
const labelInputs = (
|
||||
<>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
|
||||
{tab !== "quality" && (
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="What this run tries out (optional; published with it, default: the endpoint's notes)" />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
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="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="inline-flex 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>
|
||||
{endpoint.models.length > 1 && (
|
||||
<NativeSelect value={model} onChange={(e) => setModel(e.target.value)} className="h-8 max-w-72 text-xs" aria-label="Model">
|
||||
<option value="">Choose a model…</option>
|
||||
{endpoint.models.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
</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>
|
||||
{labelInputs}
|
||||
<Button
|
||||
onClick={() => start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })}
|
||||
disabled={busy || phases.length === 0}
|
||||
>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <GaugeIcon />}
|
||||
Run benchmark
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">Kaname checks the server first. Keep other load off it while the run lasts; on a CPU a full run can take hours.</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "ab" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Paired A/B: the same prompts go to this endpoint (A) and another one serving the same model (B), alternating, until the difference is known to ±the target.
|
||||
</p>
|
||||
{peers.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">Add a second endpoint serving the same model (e.g. with another KV cache type or engine build) to compare.</p>
|
||||
) : (
|
||||
<>
|
||||
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Endpoint B">
|
||||
<option value="">Choose B…</option>
|
||||
{peers.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
{runModel && p.models.length > 0 && !p.models.includes(runModel) ? " (doesn't serve this model)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
{!peerServes && <p className="text-xs text-amber-700 dark:text-amber-300">{peer?.name} doesn't list {runModel}. Both sides get the same model name.</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>
|
||||
{labelInputs}
|
||||
<Button onClick={() => start({ endpointBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })} disabled={busy || !peer || !peerServes}>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <GitCompareArrowsIcon />}
|
||||
Start A/B
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "quality" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality, next to
|
||||
the speed numbers.
|
||||
</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{QUALITY_SECTIONS.map((s) => (
|
||||
<label key={s} className="flex cursor-pointer items-start gap-2">
|
||||
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
|
||||
<span className="flex flex-col">
|
||||
<span>{SECTION_LABEL[s]}</span>
|
||||
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{labelInputs}
|
||||
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={busy || sections.length === 0}>
|
||||
{busy ? <Loader2Icon className="animate-spin" /> : <BadgeCheckIcon />}
|
||||
Run quality eval
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getEndpoint } from "@/lib/endpoints";
|
||||
import { EndpointForm } from "../../endpoint-form";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Edit endpoint" };
|
||||
|
||||
export default async function EditEndpointPage({ params }: PageProps<"/endpoints/[id]/edit">) {
|
||||
const endpoint = await getEndpoint((await params).id);
|
||||
if (!endpoint) notFound();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">Edit {endpoint.name}</h1>
|
||||
<EndpointForm initial={endpoint} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2Icon, PencilIcon, PlugZapIcon, Trash2Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
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 } from "@/components/ui/card";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
import { ProbeResult } from "../endpoint-form";
|
||||
import { EndpointStatus } from "../endpoint-status";
|
||||
|
||||
/** Name, URL, connection test, edit and delete. */
|
||||
export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView; runCount: number }) {
|
||||
const router = useRouter();
|
||||
const [probe, setProbe] = useState(endpoint.probe);
|
||||
const [testing, setTesting] = useState(false);
|
||||
|
||||
async function test() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}/test`, { method: "POST" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
|
||||
setProbe(json);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const res = await fetch(`/api/endpoints/${endpoint.id}`, { method: "DELETE" });
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch(() => ({}));
|
||||
return toast.error(json.error?.message ?? `Could not delete (${res.status})`);
|
||||
}
|
||||
router.push("/endpoints");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">{endpoint.name}</h1>
|
||||
<p className="text-sm break-all text-muted-foreground">
|
||||
{endpoint.baseUrl}
|
||||
{endpoint.hasApiKey ? " · API key set" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EndpointStatus probe={probe} />
|
||||
<Button variant="outline" onClick={test} disabled={testing}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
Test connection
|
||||
</Button>
|
||||
<Link href={`/endpoints/${endpoint.id}/edit`} className={buttonVariants({ variant: "outline" })}>
|
||||
<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 {endpoint.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The endpoint and its stored API key are removed.{runCount > 0 ? ` Its ${runCount} run${runCount === 1 ? "" : "s"} stay, with what they recorded.` : ""}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={remove}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import { endpointRunMeta, endpointSystem } from "@/lib/benchmark-meta";
|
||||
import { kanameVersion } from "@/lib/benchmark-snapshot";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { getEndpoint, listEndpoints } from "@/lib/endpoints";
|
||||
import { BenchmarkList } from "../../benchmarks/benchmark-list";
|
||||
import { BenchmarkStart } from "./benchmark-start";
|
||||
import { EndpointHeader } from "./endpoint-header";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata({ params }: PageProps<"/endpoints/[id]">): Promise<Metadata> {
|
||||
const e = await getEndpoint((await params).id);
|
||||
return { title: e ? `${e.name} · Endpoint` : "Endpoint" };
|
||||
}
|
||||
|
||||
export default async function EndpointPage({ params }: PageProps<"/endpoints/[id]">) {
|
||||
const { id } = await params;
|
||||
const endpoint = await getEndpoint(id);
|
||||
if (!endpoint) notFound();
|
||||
const [runs, all] = await Promise.all([listBenchmarks({ endpointId: id }), listEndpoints()]);
|
||||
const model = endpoint.model ?? (endpoint.probe?.models.length === 1 ? endpoint.probe.models[0] : null);
|
||||
// What a run would record now (the worker asks the server again when it starts).
|
||||
const preview = endpointRunMeta({
|
||||
type: "endpoint",
|
||||
endpointName: endpoint.name,
|
||||
model: model ?? "(model)",
|
||||
engine: endpoint.engine ?? endpoint.probe?.engine ?? null,
|
||||
engineVersion: endpoint.probe?.engineVersion ?? null,
|
||||
contextSize: endpoint.probe?.contextSize ?? null,
|
||||
slots: endpoint.probe?.slots ?? null,
|
||||
hardware: endpoint.hardware,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<EndpointHeader endpoint={endpoint} runCount={runs.length} />
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<BenchmarkStart
|
||||
endpoint={{ id: endpoint.id, name: endpoint.name, model, models: endpoint.probe?.models ?? [] }}
|
||||
peers={all.filter((e) => e.id !== id).map((e) => ({ id: e.id, name: e.name, models: e.probe?.models ?? [], model: e.model }))}
|
||||
/>
|
||||
<BenchmarkList rows={JSON.parse(JSON.stringify(runs))} filter={{ endpoint: id }} />
|
||||
</div>
|
||||
<aside className="flex flex-col gap-4">
|
||||
<RunMetaCard meta={preview} system={endpointSystem(endpoint.hardware, kanameVersion())} />
|
||||
{endpoint.hardware.description && (
|
||||
<p className="rounded-xl bg-card px-4 py-3 text-xs whitespace-pre-wrap text-muted-foreground ring-1 ring-foreground/10">{endpoint.hardware.description}</p>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
"use client";
|
||||
|
||||
import { CheckCircle2Icon, Loader2Icon, PlugZapIcon, SaveIcon, XCircleIcon } 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 { NativeSelect } from "@/components/ui/native-select";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema";
|
||||
import type { EndpointView } from "@/lib/endpoints";
|
||||
|
||||
type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
|
||||
|
||||
const GROUPS: { title: string; hint: string; fields: Field[] }[] = [
|
||||
{
|
||||
title: "GPU",
|
||||
hint: "Leave empty for a CPU-only server.",
|
||||
fields: [
|
||||
{ key: "gpuName", label: "GPU", placeholder: "NVIDIA GeForce RTX 4090" },
|
||||
{ key: "gpuCount", label: "Count", placeholder: "1", kind: "int" },
|
||||
{ key: "vramGb", label: "VRAM per GPU (GB)", placeholder: "24", kind: "number" },
|
||||
{ key: "pcie", label: "PCIe link", placeholder: "Gen4 x16" },
|
||||
{ key: "gpuDriver", label: "Driver", placeholder: "nvidia 580.82" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Machine",
|
||||
hint: "Only facts like these are published, never host names or addresses.",
|
||||
fields: [
|
||||
{ key: "cpu", label: "CPU", placeholder: "AMD EPYC 7282" },
|
||||
{ key: "memoryGb", label: "RAM (GB)", placeholder: "128", kind: "number" },
|
||||
{ key: "os", label: "OS", placeholder: "Debian 13" },
|
||||
{ key: "virtualization", label: "Virtualization", placeholder: "Proxmox VM with GPU passthrough, or bare metal" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Server",
|
||||
hint: "What the server runs. Empty fields are taken from what it reports where it can.",
|
||||
fields: [
|
||||
{ key: "engineName", label: "Engine name", placeholder: "ik_llama.cpp (default: detected)" },
|
||||
{ key: "engineVersion", label: "Engine version", placeholder: "default: detected" },
|
||||
{ key: "image", label: "Container image", placeholder: "ghcr.io/ggml-org/llama.cpp:server-cuda" },
|
||||
{ key: "quant", label: "Quant", placeholder: "Q4_K_M (default: from the model name)" },
|
||||
{ key: "kvCache", label: "KV cache type", placeholder: "q8_0" },
|
||||
{ key: "contextSize", label: "Context (tokens)", placeholder: "default: reported", kind: "int" },
|
||||
{ key: "concurrency", label: "Parallel slots", placeholder: "4", kind: "int" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const toText = (v: unknown) => (v == null ? "" : String(v));
|
||||
|
||||
/** Create or edit an endpoint. The API key is never sent to the browser: on edit it can be kept, replaced or removed. */
|
||||
export function EndpointForm({ initial }: { initial?: EndpointView }) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [baseUrl, setBaseUrl] = useState(initial?.baseUrl ?? "");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [removeKey, setRemoveKey] = useState(false);
|
||||
const [model, setModel] = useState(initial?.model ?? "");
|
||||
const [engine, setEngine] = useState<string>(initial?.engine ?? "");
|
||||
const [hw, setHw] = useState<Record<string, string>>(() =>
|
||||
Object.fromEntries(Object.entries(initial?.hardware ?? {}).map(([k, v]) => [k, typeof v === "boolean" ? (v ? "on" : "off") : toText(v)])),
|
||||
);
|
||||
const [probe, setProbe] = useState<EndpointProbe | null>(initial?.probe ?? null);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const fields = GROUPS.flatMap((g) => g.fields);
|
||||
function body() {
|
||||
const hardware: Record<string, unknown> = {};
|
||||
for (const f of fields) {
|
||||
const v = (hw[f.key] ?? "").trim();
|
||||
if (!v) continue;
|
||||
hardware[f.key] = f.kind ? Number(v.replace(",", ".")) : v;
|
||||
}
|
||||
if (hw.p2p) hardware.p2p = hw.p2p;
|
||||
if (hw.rebar) hardware.rebar = hw.rebar === "on";
|
||||
if (hw.description?.trim()) hardware.description = hw.description.trim();
|
||||
return {
|
||||
name,
|
||||
baseUrl,
|
||||
// Left out: keep the stored key. "": remove it.
|
||||
...(apiKey.trim() ? { apiKey: apiKey.trim() } : removeKey || !initial ? { apiKey: "" } : {}),
|
||||
model: model.trim() || null,
|
||||
engine: engine || null,
|
||||
hardware,
|
||||
};
|
||||
}
|
||||
|
||||
async function test() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await fetch(initial ? `/api/endpoints/${initial.id}/test` : "/api/endpoints/test", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body()),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
|
||||
setProbe(json);
|
||||
if (json.ok && !model && json.models.length === 1) setModel(json.models[0]);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(initial ? `/api/endpoints/${initial.id}` : "/api/endpoints", {
|
||||
method: initial ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body()),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
router.push(`/endpoints/${json.id}`);
|
||||
router.refresh();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const set = (key: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setHw((cur) => ({ ...cur, [key]: e.target.value }));
|
||||
const models = probe?.ok ? probe.models : [];
|
||||
|
||||
return (
|
||||
<form onSubmit={save} className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Connection</CardTitle>
|
||||
<CardDescription>Any OpenAI-compatible server: llama.cpp, vLLM, SGLang, Ollama, … Kaname talks to it from its own server.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Name</span>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="4090 llama.cpp" required />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">URL</span>
|
||||
<Input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="http://192.168.1.20:8080" required />
|
||||
<span className="text-xs text-muted-foreground">The server's root; /v1 is added by Kaname.</span>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">API key</span>
|
||||
<Input
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder={initial?.hasApiKey ? "stored; type to replace" : "optional"}
|
||||
disabled={removeKey}
|
||||
/>
|
||||
{initial?.hasApiKey && (
|
||||
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Checkbox checked={removeKey} onCheckedChange={(v) => setRemoveKey(!!v)} />
|
||||
Remove the stored key
|
||||
</label>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">Stays on the server: never shown again, logged or put into a run.</span>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Engine</span>
|
||||
<NativeSelect value={engine} onChange={(e) => setEngine(e.target.value)}>
|
||||
<option value="">Detect</option>
|
||||
{ENDPOINT_ENGINES.map((e) => (
|
||||
<option key={e} value={e}>
|
||||
{ENGINE_LABEL[e]}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">Model</span>
|
||||
{models.length > 1 ? (
|
||||
<NativeSelect value={model} onChange={(e) => setModel(e.target.value)}>
|
||||
<option value="">Choose…</option>
|
||||
{models.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
) : (
|
||||
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={models[0] ?? "the only one it serves"} />
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={test} disabled={testing || !baseUrl.trim()}>
|
||||
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
|
||||
Test connection
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
<SaveIcon />
|
||||
{initial ? "Save" : "Add endpoint"}
|
||||
</Button>
|
||||
</div>
|
||||
{probe && <ProbeResult probe={probe} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware notes</CardTitle>
|
||||
<CardDescription>
|
||||
Kaname can't see the machine behind an endpoint. What you enter here goes into every run, its BetterBench notes and launch80 reports, so results stay
|
||||
comparable.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4 text-sm">
|
||||
{GROUPS.map((g) => (
|
||||
<fieldset key={g.title} className="flex flex-col gap-2">
|
||||
<legend className="mb-1 font-medium">{g.title}</legend>
|
||||
<p className="-mt-1 text-xs text-muted-foreground">{g.hint}</p>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{g.fields.map((f) => (
|
||||
<label key={f.key} className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">{f.label}</span>
|
||||
<Input value={hw[f.key] ?? ""} onChange={set(f.key)} placeholder={f.placeholder} inputMode={f.kind ? "decimal" : undefined} />
|
||||
</label>
|
||||
))}
|
||||
{g.title === "GPU" && (
|
||||
<>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">P2P between GPUs</span>
|
||||
<NativeSelect value={hw.p2p ?? ""} onChange={set("p2p")}>
|
||||
<option value="">unknown</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
<option value="partial">partial</option>
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">Resizable BAR</span>
|
||||
<NativeSelect value={hw.rebar ?? ""} onChange={set("rebar")}>
|
||||
<option value="">unknown</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
))}
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-medium">Notes</span>
|
||||
<textarea
|
||||
value={hw.description ?? ""}
|
||||
onChange={set("description")}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="Launch flags, power limit, anything worth knowing. Published with the runs."
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
/>
|
||||
</label>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** What "Test connection" found. */
|
||||
export function ProbeResult({ probe }: { probe: EndpointProbe }) {
|
||||
if (!probe.ok) {
|
||||
return (
|
||||
<div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs">
|
||||
<XCircleIcon className="size-4 shrink-0 text-destructive" />
|
||||
<span>{probe.error}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs">
|
||||
<CheckCircle2Icon className="size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<span>
|
||||
Reachable{probe.latencyMs != null ? ` (${probe.latencyMs} ms)` : ""}
|
||||
{probe.engine ? ` · ${ENGINE_LABEL[probe.engine]}${probe.engineVersion ? ` ${probe.engineVersion}` : ""}` : " · engine not detected"}
|
||||
{probe.contextSize ? ` · ${probe.contextSize.toLocaleString("en-US")} tokens context` : ""}
|
||||
{probe.slots ? ` · ${probe.slots} slots` : ""}
|
||||
</span>
|
||||
<span className="break-all text-muted-foreground">
|
||||
{probe.models.length ? `Serves: ${probe.models.slice(0, 6).join(", ")}${probe.models.length > 6 ? ", …" : ""}` : "Lists no models."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import type { EndpointProbe } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Reachable / unreachable / untested, from the last connection test. */
|
||||
export function EndpointStatus({ probe }: { probe: EndpointProbe | null }) {
|
||||
const state = !probe ? "untested" : probe.ok ? "reachable" : "unreachable";
|
||||
return (
|
||||
<span className="flex flex-col gap-0.5" title={probe?.error ?? undefined}>
|
||||
<span className="flex items-center gap-1.5 text-sm">
|
||||
<span className={cn("size-2 rounded-full", state === "reachable" ? "bg-emerald-500" : state === "unreachable" ? "bg-destructive" : "bg-foreground/25")} />
|
||||
{state}
|
||||
</span>
|
||||
{probe && (
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
<LocalTime value={probe.at} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { EndpointForm } from "../endpoint-form";
|
||||
|
||||
export const metadata: Metadata = { title: "New endpoint" };
|
||||
|
||||
export default function NewEndpointPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<h1 className="text-xl font-semibold">New endpoint</h1>
|
||||
<EndpointForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { PlusIcon, ServerIcon } from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { listBenchmarks } from "@/lib/benchmarks";
|
||||
import { listEndpoints } from "@/lib/endpoints";
|
||||
import { EndpointStatus } from "./endpoint-status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Endpoints" };
|
||||
|
||||
export default async function EndpointsPage() {
|
||||
const [endpoints, runs] = await Promise.all([listEndpoints(), listBenchmarks()]);
|
||||
// Newest completed speed run and quality score per endpoint.
|
||||
const latest = new Map<string, { decode: number | null; quality: number | null }>();
|
||||
for (const r of runs) {
|
||||
if (!r.endpointId || r.state !== "completed") continue;
|
||||
const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
|
||||
if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode;
|
||||
if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null;
|
||||
latest.set(r.endpointId, cur);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-end justify-between gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold">Endpoints</h1>
|
||||
<p className="text-sm text-muted-foreground">OpenAI-compatible servers to benchmark. They run elsewhere; Kaname only sends them requests.</p>
|
||||
</div>
|
||||
<Link href="/endpoints/new" className={buttonVariants()}>
|
||||
<PlusIcon />
|
||||
Add endpoint
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{endpoints.length === 0 ? (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
<ServerIcon className="size-8 text-muted-foreground" />
|
||||
<p className="max-w-md text-sm text-muted-foreground">
|
||||
No endpoints yet. Add the URL of a llama.cpp, vLLM, SGLang or Ollama server, describe its hardware, and benchmark it.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="py-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Endpoint</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Model</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Hardware</TableHead>
|
||||
<TableHead className="text-right">Decode t/s</TableHead>
|
||||
<TableHead className="hidden text-right sm:table-cell">Quality</TableHead>
|
||||
<TableHead className="w-32">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{endpoints.map((e) => {
|
||||
const l = latest.get(e.id);
|
||||
const engine = e.hardware.engineName || (e.engine ?? e.probe?.engine ? ENGINE_LABEL[(e.engine ?? e.probe?.engine)!] : null);
|
||||
return (
|
||||
<TableRow key={e.id}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/endpoints/${e.id}`} className="font-medium hover:underline">
|
||||
{e.name}
|
||||
</Link>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{e.baseUrl}
|
||||
{engine && ` · ${engine}${e.probe?.engineVersion ? ` ${e.probe.engineVersion}` : ""}`}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden max-w-64 truncate text-sm md:table-cell">{e.model ?? (e.probe?.models.length === 1 ? e.probe.models[0] : "–")}</TableCell>
|
||||
<TableCell className="hidden text-sm text-muted-foreground lg:table-cell">
|
||||
{e.hardware.gpuName ? `${e.hardware.gpuCount ?? 1}× ${e.hardware.gpuName}` : (e.hardware.cpu ?? "–")}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{l?.decode != null ? l.decode.toFixed(1) : "–"}</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums sm:table-cell">{l?.quality != null ? `${l.quality}%` : "–"}</TableCell>
|
||||
<TableCell>
|
||||
<EndpointStatus probe={e.probe} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
|
||||
import { 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, buttonVariants } from "@/components/ui/button";
|
||||
import { Button } 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,7 +19,6 @@ 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,
|
||||
@@ -32,7 +31,7 @@ import {
|
||||
} from "@/lib/search";
|
||||
import { FacetFilter } from "./facet-filter";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
|
||||
|
||||
const FACET_LABEL: Record<Facet, string> = {
|
||||
author: "Author",
|
||||
@@ -181,9 +180,6 @@ 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>
|
||||
@@ -199,23 +195,6 @@ 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}
|
||||
@@ -257,19 +236,6 @@ 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>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
"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 “Require an API key” accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer <key></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 “{created.name}” 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 “{apiKey.name}”?</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>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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()} />;
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
const SECTIONS = [
|
||||
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
|
||||
{ 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 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
import { RuntimesView } from "./runtimes-view";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Runtimes · Settings" };
|
||||
|
||||
export default async function RuntimesPage() {
|
||||
const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
|
||||
return <RuntimesView runtimes={runtimes} docker={docker} workerOnline={worker.online} />;
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
"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 { 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 }[] = [
|
||||
{ id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
|
||||
{ id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
|
||||
];
|
||||
|
||||
const textareaClass =
|
||||
"min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
|
||||
|
||||
/** Create/edit a runtime. Validates locally with the same rules as the server. */
|
||||
export function RuntimeForm({
|
||||
initial,
|
||||
submitLabel,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: {
|
||||
initial: RuntimeInput;
|
||||
submitLabel: string;
|
||||
onSubmit: (value: RuntimeInput) => Promise<boolean>;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
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 [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);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
let value: RuntimeInput;
|
||||
try {
|
||||
value = validateRuntime({
|
||||
name,
|
||||
engine,
|
||||
accelerator,
|
||||
image,
|
||||
description,
|
||||
env: parseEnvLines(envText),
|
||||
extraArgs: rowsToArgs(argRows),
|
||||
devices: devicesText.split(/[,\s]+/),
|
||||
shmSizeMb: shm.trim() ? Number(shm) : null,
|
||||
numaTuning: numa,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof RuntimeValidationError ? err.message : String(err));
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSubmit(value);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="flex flex-col gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-name">Name</Label>
|
||||
<Input id="rt-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="vLLM XPU (Arc patches)" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-image">Image</Label>
|
||||
<Input
|
||||
id="rt-image"
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
placeholder="registry.example.com/org/image:tag"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Engine type</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{ENGINES.map((e) => (
|
||||
<button
|
||||
key={e.id}
|
||||
type="button"
|
||||
onClick={() => setEngine(e.id)}
|
||||
className={cn(
|
||||
"flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
|
||||
engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<span className="font-medium">{e.label}</span>
|
||||
<span className="text-xs text-muted-foreground">{e.hint}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
|
||||
</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="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's command; a deployment can override them.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-shm">Shared memory (MiB)</Label>
|
||||
<Input id="rt-shm" value={shm} onChange={(e) => setShm(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" placeholder="Docker default (64)" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-devices">Devices</Label>
|
||||
<Input
|
||||
id="rt-devices"
|
||||
value={devicesText}
|
||||
onChange={(e) => setDevicesText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
placeholder="/dev/dri, /dev/kfd"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-muted/50 px-3 py-2.5 text-sm">
|
||||
<Checkbox checked={numa} onCheckedChange={(v) => setNuma(v === true)} className="mt-0.5" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span>NUMA tuning</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Adds <code>CAP_SYS_NICE</code> and <code>seccomp=unconfined</code>, as vLLM recommends for its CPU build. This relaxes
|
||||
the container's isolation; leave it off unless you need the extra speed.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{error && <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? "Saving…" : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,374 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
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, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
|
||||
import { formatBytes, percent } from "@/lib/format";
|
||||
import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { RuntimeForm } from "./runtime-form";
|
||||
|
||||
type Runtime = typeof runtimes.$inferSelect;
|
||||
|
||||
const FEATURE_LABEL: Record<string, string> = {
|
||||
avx2: "AVX2",
|
||||
avx512f: "AVX-512",
|
||||
avx512_bf16: "AVX-512 BF16",
|
||||
avx512_vnni: "AVX-512 VNNI",
|
||||
avx512bw: "AVX-512 BW",
|
||||
amx_bf16: "AMX BF16",
|
||||
amx_int8: "AMX INT8",
|
||||
f16c: "F16C",
|
||||
fma: "FMA",
|
||||
};
|
||||
|
||||
async function send(url: string, method: string, body?: unknown): Promise<boolean> {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: body ? { "Content-Type": "application/json" } : undefined,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (res.ok) return true;
|
||||
const json = await res.json().catch(() => ({}));
|
||||
toast.error(json.error?.message ?? `Request failed (${res.status})`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const toInput = (r: Runtime): RuntimeInput => ({
|
||||
name: r.name,
|
||||
engine: r.engine,
|
||||
accelerator: r.accelerator,
|
||||
image: r.image,
|
||||
description: r.description,
|
||||
env: r.env,
|
||||
extraArgs: r.extraArgs,
|
||||
devices: r.devices,
|
||||
shmSizeMb: r.shmSizeMb,
|
||||
numaTuning: r.numaTuning,
|
||||
});
|
||||
|
||||
export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
|
||||
const router = useRouter();
|
||||
const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
|
||||
|
||||
// While a pull runs, refresh the server data every 2 s for its progress.
|
||||
useEffect(() => {
|
||||
if (!anyPulling) return;
|
||||
const t = setInterval(() => router.refresh(), 2_000);
|
||||
return () => clearInterval(t);
|
||||
}, [anyPulling, router]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<HostCard docker={docker} workerOnline={workerOnline} />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Runtimes</CardTitle>
|
||||
<CardDescription>
|
||||
Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
|
||||
only starts images registered here, with the models mounted read-only.
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button size="sm" />}>
|
||||
<PlusIcon />
|
||||
Add runtime
|
||||
<ChevronDownIcon className="opacity-70" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-72">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>From a preset</DropdownMenuLabel>
|
||||
{RUNTIME_PRESETS.map((p) => (
|
||||
<DropdownMenuItem key={p.id} onClick={() => setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
|
||||
<span>{p.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{p.summary}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
{creating && (
|
||||
<div className="rounded-lg p-4 ring-1 ring-primary/40">
|
||||
<RuntimeForm
|
||||
initial={creating}
|
||||
submitLabel="Add runtime"
|
||||
onCancel={() => setCreating(null)}
|
||||
onSubmit={async (value) => {
|
||||
const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
|
||||
if (ok) {
|
||||
toast.success(`Runtime "${value.name}" added`);
|
||||
setCreating(null);
|
||||
router.refresh();
|
||||
}
|
||||
return ok;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{runtimes.length === 0 && !creating && <p className="text-sm text-muted-foreground">No runtimes yet. Add one from a preset.</p>}
|
||||
{runtimes.map((r) =>
|
||||
editing === r.id ? (
|
||||
<div key={r.id} className="rounded-lg p-4 ring-1 ring-primary/40">
|
||||
<RuntimeForm
|
||||
initial={toInput(r)}
|
||||
submitLabel="Save"
|
||||
onCancel={() => setEditing(null)}
|
||||
onSubmit={async (value) => {
|
||||
const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
|
||||
if (ok) {
|
||||
setEditing(null);
|
||||
router.refresh();
|
||||
}
|
||||
return ok;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<RuntimeRow
|
||||
key={r.id}
|
||||
runtime={r}
|
||||
dockerReady={!!docker?.connected}
|
||||
onEdit={() => setEditing(r.id)}
|
||||
onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ServerIcon className="size-4 text-muted-foreground" />
|
||||
Docker host
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{!workerOnline
|
||||
? "The worker is offline; these facts may be outdated."
|
||||
: !docker
|
||||
? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
|
||||
: docker.connected
|
||||
? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
|
||||
: `Can't reach Docker: ${docker.error}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
{docker && (
|
||||
<CardContent>
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1.5 text-sm">
|
||||
<dt className="text-muted-foreground">CPU</dt>
|
||||
<dd>
|
||||
{docker.cpuModel ?? "unknown"}
|
||||
{docker.cpus != null && <span className="text-muted-foreground"> · {docker.cpus} threads</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Features</dt>
|
||||
<dd className="flex flex-wrap gap-1">
|
||||
{docker.cpuFeatures.length === 0 ? (
|
||||
<span className="text-muted-foreground">unknown</span>
|
||||
) : (
|
||||
docker.cpuFeatures.map((f) => (
|
||||
<span
|
||||
key={f}
|
||||
className={cn(
|
||||
"rounded border px-1.5 text-xs",
|
||||
f.startsWith("avx512") || f.startsWith("amx") ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{FEATURE_LABEL[f] ?? f}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</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'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)"}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Models</dt>
|
||||
<dd className={cn("font-mono text-xs break-all", !docker.modelsSource && "text-amber-700 dark:text-amber-300")}>
|
||||
{docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Checked</dt>
|
||||
<dd>
|
||||
<LocalTime value={docker.checkedAt} />
|
||||
</dd>
|
||||
</dl>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageState({ r }: { r: Runtime }) {
|
||||
const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
|
||||
if (r.imageState === "pulling" || requested) {
|
||||
const p = r.pullProgress;
|
||||
return (
|
||||
<div className="flex min-w-48 flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
|
||||
</span>
|
||||
<Progress value={p && p.totalBytes ? percent(p.doneBytes, p.totalBytes) : 0} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (r.imageState === "present") {
|
||||
return (
|
||||
<span className="text-xs text-emerald-700 dark:text-emerald-400">
|
||||
Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
|
||||
{r.imageCreated && (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· built <LocalTime value={r.imageCreated} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (r.imageState === "failed") return <span className="text-xs break-all text-destructive">Pull failed: {r.pullError}</span>;
|
||||
if (r.imageState === "missing") return <span className="text-xs text-muted-foreground">Not pulled yet</span>;
|
||||
return <span className="text-xs text-muted-foreground">Not checked yet</span>;
|
||||
}
|
||||
|
||||
function RuntimeRow({
|
||||
runtime: r,
|
||||
dockerReady,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
}: {
|
||||
runtime: Runtime;
|
||||
dockerReady: boolean;
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const pulling = r.imageState === "pulling";
|
||||
const envCount = Object.keys(r.env).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-lg px-4 py-3 ring-1 ring-foreground/10">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<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>
|
||||
{r.description && <p className="text-xs text-muted-foreground">{r.description}</p>}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant={r.imageState === "present" ? "ghost" : "outline"}
|
||||
disabled={!dockerReady || pulling}
|
||||
title={!dockerReady ? "Docker isn't connected" : r.imageState === "present" ? "Pull again to update the tag" : undefined}
|
||||
onClick={async () => {
|
||||
if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
|
||||
}}
|
||||
>
|
||||
<DownloadCloudIcon />
|
||||
{r.imageState === "present" ? "Update" : "Pull"}
|
||||
</Button>
|
||||
<Button size="icon-sm" variant="ghost" onClick={onEdit} aria-label={`Edit ${r.name}`}>
|
||||
<PencilIcon />
|
||||
</Button>
|
||||
<Button size="icon-sm" variant="ghost" onClick={onDuplicate} aria-label={`Duplicate ${r.name}`}>
|
||||
<CopyIcon />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button size="icon-sm" variant="ghost" aria-label={`Delete ${r.name}`} />}>
|
||||
<Trash2Icon />
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete runtime “{r.name}”?</AlertDialogTitle>
|
||||
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
|
||||
<ImageState r={r} />
|
||||
<span>
|
||||
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
|
||||
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
|
||||
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
|
||||
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
import { modelName } from "@/lib/benchmark-view";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -24,6 +25,6 @@ export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/results">>(async
|
||||
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`;
|
||||
const name = `betterbench-${ab ? "ab-" : ""}${modelName(run.snapshot).split("/").pop()!.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
|
||||
return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
|
||||
});
|
||||
@@ -2,7 +2,7 @@ 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";
|
||||
import { BenchmarkError, DESCRIPTION_MAX, deleteBenchmark, getBenchmark, updateBenchmark } from "@/lib/benchmarks";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -11,12 +11,12 @@ export const GET = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, {
|
||||
return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
|
||||
});
|
||||
|
||||
const Patch = z.object({ label: z.string().max(120).nullable() });
|
||||
const Patch = z.object({ label: z.string().max(120).nullable().optional(), description: z.string().max(DESCRIPTION_MAX).nullable().optional() });
|
||||
|
||||
/** Rename (label) a run. */
|
||||
/** Rename (label) a run or change its description. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (req, { params }) => {
|
||||
try {
|
||||
await updateBenchmarkLabel((await params).id, Patch.parse(await req.json()).label);
|
||||
await updateBenchmark((await params).id, Patch.parse(await req.json()));
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
|
||||
|
||||
@@ -5,13 +5,13 @@ import { BenchmarkBody, BenchmarkError, createBenchmark, listBenchmarks } from "
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** All runs, newest first; `?deployment=<id>` or `?model=<id>` narrows them. */
|
||||
/** All runs, newest first; `?endpoint=<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 }));
|
||||
return NextResponse.json(await listBenchmarks({ endpointId: sp.get("endpoint") ?? undefined, modelId: sp.get("model") ?? undefined }));
|
||||
});
|
||||
|
||||
/** Queue a BetterBench run against a running deployment. */
|
||||
/** Queue a benchmark run against an endpoint. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await createBenchmark(BenchmarkBody.parse(await req.json())), { status: 201 });
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
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));
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { deleteEndpoint, EndpointError, getEndpoint, updateEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fail = (err: unknown) => (err instanceof EndpointError ? apiError(err.status, err.code, err.message) : handleApiError(err));
|
||||
|
||||
export const GET = withAuth<RouteContext<"/api/endpoints/[id]">>(async (_req, { params }) => {
|
||||
const e = await getEndpoint((await params).id);
|
||||
return e ? NextResponse.json(e) : apiError(404, "not_found", "Endpoint not found.");
|
||||
});
|
||||
|
||||
/** Change an endpoint; leave `apiKey` out to keep the stored key, send "" to remove it. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/endpoints/[id]">>(async (req, { params }) => {
|
||||
try {
|
||||
return NextResponse.json(await updateEndpoint((await params).id, await req.json()));
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Delete an endpoint; its runs stay (with their snapshot). */
|
||||
export const DELETE = withAuth<RouteContext<"/api/endpoints/[id]">>(async (_req, { params }) => {
|
||||
try {
|
||||
await deleteEndpoint((await params).id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { EndpointError, testEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Test a saved endpoint (stores the result), or, with a body, the form's unsaved values for it. */
|
||||
export const POST = withAuth<RouteContext<"/api/endpoints/[id]/test">>(async (req, { params }) => {
|
||||
try {
|
||||
const text = await req.text();
|
||||
return NextResponse.json(await testEndpoint((await params).id, text ? JSON.parse(text) : undefined));
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { createEndpoint, EndpointError, listEndpoints } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** All endpoints (never their API keys). */
|
||||
export const GET = withAuth(async () => NextResponse.json(await listEndpoints()));
|
||||
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await createEndpoint(await req.json()), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { EndpointError, testEndpoint } from "@/lib/endpoints";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Test a new endpoint's form values before saving. */
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await testEndpoint(null, await req.json()));
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { requestPull, RuntimeError } from "@/lib/runtimes";
|
||||
|
||||
/** Ask the worker to pull the image (again; updates moving tags like :server). */
|
||||
export const POST = withAuth<RouteContext<"/api/runtimes/[id]/pull">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await requestPull(id);
|
||||
return new NextResponse(null, { status: 202 });
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { deleteRuntime, RuntimeBody, RuntimeError, updateRuntime } from "@/lib/runtimes";
|
||||
|
||||
export const PUT = withAuth<RouteContext<"/api/runtimes/[id]">>(async (req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
return NextResponse.json(await updateRuntime(id, RuntimeBody.parse(await req.json())));
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
|
||||
export const DELETE = withAuth<RouteContext<"/api/runtimes/[id]">>(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
try {
|
||||
await deleteRuntime(id);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { createRuntime, getDockerInfo, listRuntimes, RuntimeBody, RuntimeError } from "@/lib/runtimes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
|
||||
/** Runtimes plus the Docker facts the worker reported. */
|
||||
export const GET = withAuth(async () => NextResponse.json({ runtimes: await listRuntimes(), docker: await getDockerInfo() }));
|
||||
|
||||
export const POST = withAuth(async (req) => {
|
||||
try {
|
||||
const body = RuntimeBody.extend({ preset: z.string().optional() }).parse(await req.json());
|
||||
return NextResponse.json(await createRuntime(body), { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { GaugeIcon, LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
|
||||
import { GaugeIcon, LibraryIcon, ServerIcon, SettingsIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -10,9 +10,9 @@ const LINKS = [
|
||||
href: "/",
|
||||
label: "Library",
|
||||
icon: LibraryIcon,
|
||||
active: (p: string) => !["/settings", "/deployments", "/benchmarks"].some((x) => p.startsWith(x)),
|
||||
active: (p: string) => !["/settings", "/endpoints", "/benchmarks"].some((x) => p.startsWith(x)),
|
||||
},
|
||||
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
|
||||
{ href: "/endpoints", label: "Endpoints", icon: ServerIcon, active: (p: string) => p.startsWith("/endpoints") },
|
||||
{ href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
|
||||
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
|
||||
];
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
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'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>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { LoaderCircleIcon } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const STYLE: Record<string, string> = {
|
||||
pending_approval: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
|
||||
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",
|
||||
@@ -10,7 +11,7 @@ const STYLE: Record<string, string> = {
|
||||
};
|
||||
|
||||
export function BenchmarkStateBadge({ state, cancelling, className }: { state: string; cancelling?: boolean; className?: string }) {
|
||||
const label = state === "running" && cancelling ? "cancelling" : state;
|
||||
const label = state === "running" && cancelling ? "cancelling" : state === "pending_approval" ? "awaiting approval" : 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" />}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -31,3 +31,21 @@ export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
if (ok) toast.success("Update queued");
|
||||
return ok;
|
||||
}
|
||||
|
||||
export async function approveJob(jobId: string): Promise<boolean> {
|
||||
const ok = await post(`/api/jobs/${jobId}/approve`);
|
||||
if (ok) toast.success("Approved; the download is queued");
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Returns whether the model left the library (it was only added by this request), or null on error. */
|
||||
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> {
|
||||
const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return null;
|
||||
}
|
||||
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
|
||||
return body;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { formatBytes, formatDuration, formatSpeed, percent } from "@/lib/format"
|
||||
import type { JobSnapshot } from "@/lib/jobs";
|
||||
|
||||
const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
pending_approval: "outline",
|
||||
queued: "outline",
|
||||
downloading: "secondary",
|
||||
verifying: "secondary",
|
||||
@@ -14,7 +15,12 @@ const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "o
|
||||
};
|
||||
|
||||
export function JobStateBadge({ job }: { job: Pick<JobSnapshot, "state" | "cancelRequested"> }) {
|
||||
const label = job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state) ? "cancelling" : job.state;
|
||||
const label =
|
||||
job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state)
|
||||
? "cancelling"
|
||||
: job.state === "pending_approval"
|
||||
? "awaiting approval"
|
||||
: job.state;
|
||||
return <Badge variant={STATE_VARIANT[job.state] ?? "outline"}>{label}</Badge>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import type { RunMeta, SystemSummary } from "@/lib/db/schema";
|
||||
import { systemSummaryLines } from "@/lib/hardware";
|
||||
|
||||
/** Hardware, runtime and model a run measured (A and B side by side for an A/B), plus the system summary. */
|
||||
export function RunMetaCard({ meta, metaB, system }: { meta: RunMeta | null; metaB?: RunMeta | null; system: SystemSummary | null }) {
|
||||
if (!meta && !system) return null;
|
||||
const a = meta ? metaRows(meta) : [];
|
||||
const b = metaB ? metaRows(metaB) : null;
|
||||
const keys = [...new Set([...a, ...(b ?? [])].map((r) => r.key))];
|
||||
const label = (k: string) => (a.find((r) => r.key === k) ?? b?.find((r) => r.key === k))!.label;
|
||||
const value = (rows: typeof a | null, k: string) => rows?.find((r) => r.key === k)?.value ?? "–";
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware & runtime</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
{meta && (
|
||||
<dl className={`grid gap-x-4 gap-y-1 text-xs ${b ? "grid-cols-[max-content_1fr_1fr]" : "grid-cols-[max-content_1fr]"}`}>
|
||||
{b && (
|
||||
<>
|
||||
<span />
|
||||
<span className="font-medium">A</span>
|
||||
<span className="font-medium">B</span>
|
||||
</>
|
||||
)}
|
||||
{keys.map((k) => (
|
||||
<div key={k} className="contents">
|
||||
<dt className="text-muted-foreground">{label(k)}</dt>
|
||||
<dd className="min-w-0 font-mono break-all">{value(a, k)}</dd>
|
||||
{b && <dd className="min-w-0 font-mono break-all">{value(b, k)}</dd>}
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{meta && meta.overridden.length > 0 && <p className="text-[11px] text-muted-foreground">From Settings → Hardware: {meta.overridden.join(", ")}.</p>}
|
||||
{system && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">System</span>
|
||||
<ul className="flex flex-col gap-0.5 text-xs">
|
||||
{systemSummaryLines(system).map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useTransition } from "react";
|
||||
@@ -67,13 +67,9 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
||||
<TagsIcon />
|
||||
Tags
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/runtimes" />}>
|
||||
<BoxesIcon />
|
||||
Runtimes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
|
||||
<KeyRoundIcon />
|
||||
API keys
|
||||
<DropdownMenuItem render={<Link href="/settings/downloads" />}>
|
||||
<DownloadIcon />
|
||||
Downloads
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"instructions": "Write the Python 3 function described below. Use only the standard library. Reply with the complete function definition, starting with def, in a single ```python code block and nothing else.",
|
||||
"items": [
|
||||
{
|
||||
"id": "is-palindrome",
|
||||
"prompt": "is_palindrome(s: str) -> bool: True if s reads the same forwards and backwards, ignoring case and every character that isn't a letter or a digit.",
|
||||
"tests": [
|
||||
"assert is_palindrome('A man, a plan, a canal: Panama') is True",
|
||||
"assert is_palindrome('race a car') is False",
|
||||
"assert is_palindrome('') is True",
|
||||
"assert is_palindrome('No lemon, no melon') is True",
|
||||
"assert is_palindrome('ab2a') is False"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "fizzbuzz",
|
||||
"prompt": "fizzbuzz(n: int) -> list[str]: for 1..n, 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, 'FizzBuzz' for multiples of both, else the number as a string.",
|
||||
"tests": [
|
||||
"assert fizzbuzz(5) == ['1', '2', 'Fizz', '4', 'Buzz']",
|
||||
"assert fizzbuzz(15)[-1] == 'FizzBuzz'",
|
||||
"assert fizzbuzz(0) == []",
|
||||
"assert len(fizzbuzz(100)) == 100"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "merge-intervals",
|
||||
"prompt": "merge_intervals(intervals: list[list[int]]) -> list[list[int]]: merge overlapping or touching [start, end] intervals and return them sorted by start.",
|
||||
"tests": [
|
||||
"assert merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]",
|
||||
"assert merge_intervals([[1, 4], [4, 5]]) == [[1, 5]]",
|
||||
"assert merge_intervals([]) == []",
|
||||
"assert merge_intervals([[5, 7], [1, 2]]) == [[1, 2], [5, 7]]",
|
||||
"assert merge_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "word-count",
|
||||
"prompt": "word_count(text: str) -> dict[str, int]: count words, lowercased, where a word is a run of letters (anything else separates words).",
|
||||
"tests": [
|
||||
"assert word_count('Hello, hello world!') == {'hello': 2, 'world': 1}",
|
||||
"assert word_count('') == {}",
|
||||
"assert word_count('one-two three') == {'one': 1, 'two': 1, 'three': 1}",
|
||||
"assert word_count('A a A b') == {'a': 3, 'b': 1}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "roman-to-int",
|
||||
"prompt": "roman_to_int(s: str) -> int: convert a Roman numeral (I, V, X, L, C, D, M, with subtractive forms like IV and CM) to an integer.",
|
||||
"tests": [
|
||||
"assert roman_to_int('III') == 3",
|
||||
"assert roman_to_int('LVIII') == 58",
|
||||
"assert roman_to_int('MCMXCIV') == 1994",
|
||||
"assert roman_to_int('XLIX') == 49",
|
||||
"assert roman_to_int('MMXXVI') == 2026"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "flatten",
|
||||
"prompt": "flatten(nested: list) -> list: return all non-list items of an arbitrarily nested list, in order.",
|
||||
"tests": [
|
||||
"assert flatten([1, [2, [3, [4]], 5]]) == [1, 2, 3, 4, 5]",
|
||||
"assert flatten([]) == []",
|
||||
"assert flatten([[], [[]], [1]]) == [1]",
|
||||
"assert flatten(['a', ['b', ['c']]]) == ['a', 'b', 'c']"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "second-largest",
|
||||
"prompt": "second_largest(nums: list[int]) -> int | None: the second largest distinct value, or None if there isn't one.",
|
||||
"tests": [
|
||||
"assert second_largest([3, 1, 4, 1, 5, 9, 2, 6]) == 6",
|
||||
"assert second_largest([7, 7, 7]) is None",
|
||||
"assert second_largest([]) is None",
|
||||
"assert second_largest([-2, -5, -1]) == -2",
|
||||
"assert second_largest([10, 9]) == 9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "rle-encode",
|
||||
"prompt": "rle_encode(s: str) -> str: run-length encode a string as each character followed by its run length, e.g. 'aaabcc' -> 'a3b1c2'.",
|
||||
"tests": [
|
||||
"assert rle_encode('aaabcc') == 'a3b1c2'",
|
||||
"assert rle_encode('') == ''",
|
||||
"assert rle_encode('abc') == 'a1b1c1'",
|
||||
"assert rle_encode('zzzzzzzzzzzz') == 'z12'"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"lengths": [0.25, 0.5, 1.0],
|
||||
"positions": [0.1, 0.5, 0.9],
|
||||
"reserveTokens": 384,
|
||||
"seed": 20261021,
|
||||
"needle": "Note for later: the access code for the {color} vault is {code}.",
|
||||
"question": "In the text above there is one note with an access code for the {color} vault. What is that access code? Answer with the six-digit number only.",
|
||||
"colors": ["amber", "cobalt", "crimson", "jade", "silver", "violet", "ochre", "teal", "scarlet"],
|
||||
"filler": [
|
||||
"The river bends twice before it reaches the old mill at the edge of the valley.",
|
||||
"Most of the orchard was planted after the long winter, when the soil had recovered.",
|
||||
"A narrow path leads from the station to the market square, lined with plane trees.",
|
||||
"In spring the meadows fill with clover and the bees return to the wooden hives.",
|
||||
"The library keeps its oldest maps in a cool room behind the reading hall.",
|
||||
"Fishing boats leave the harbour before dawn and come back around midday.",
|
||||
"The bakery on the corner opens at six and is usually sold out by ten.",
|
||||
"Snow rarely stays on the lower slopes for more than a few days at a time.",
|
||||
"An old stone bridge crosses the stream where the two footpaths meet.",
|
||||
"The town hall clock was repaired last year and now runs a minute fast.",
|
||||
"Every autumn the vineyards hire extra hands for the harvest weeks.",
|
||||
"The lighthouse has been automated, but a keeper still checks it each week.",
|
||||
"A small museum by the church shows tools that farmers used a century ago.",
|
||||
"The tram line was extended to the university campus in the north.",
|
||||
"Wild garlic grows along the shaded banks of the brook in early May.",
|
||||
"The guesthouse serves breakfast in a garden room that faces the hills.",
|
||||
"Cyclists often stop at the fountain to refill their bottles before the climb.",
|
||||
"The weekly market sells cheese from three farms in the neighbouring villages.",
|
||||
"On clear nights the observatory opens its dome to visitors after nine.",
|
||||
"The ferry runs every hour in summer and twice a day in the colder months.",
|
||||
"A row of chestnut trees marks the old boundary of the monastery grounds.",
|
||||
"The pottery workshop fires its kiln on Thursdays and sells seconds on Fridays.",
|
||||
"Fog settles in the valley on most mornings and lifts by late morning.",
|
||||
"The cooperative store stocks seeds, rope, lamp oil and tinned food.",
|
||||
"Herons nest in the reeds at the far end of the lake each year.",
|
||||
"The school bus takes the long way round when the pass is closed.",
|
||||
"A painter rents the attic above the bookshop for the summer months.",
|
||||
"The old railway embankment is now a walking trail through the woods.",
|
||||
"Shepherds move the flocks to the high pastures in the first week of June.",
|
||||
"The smithy still repairs gates and hinges for the farms nearby."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
{
|
||||
"tools": {
|
||||
"get_weather": {
|
||||
"description": "Current weather for a city.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": { "type": "string", "description": "City name, e.g. Berlin" },
|
||||
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
|
||||
},
|
||||
"required": ["city", "unit"]
|
||||
}
|
||||
},
|
||||
"convert_currency": {
|
||||
"description": "Convert an amount of money between currencies.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"amount": { "type": "number" },
|
||||
"from": { "type": "string", "description": "ISO 4217 code, e.g. USD" },
|
||||
"to": { "type": "string", "description": "ISO 4217 code, e.g. EUR" }
|
||||
},
|
||||
"required": ["amount", "from", "to"]
|
||||
}
|
||||
},
|
||||
"create_calendar_event": {
|
||||
"description": "Add an event to the user's calendar.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": { "type": "string" },
|
||||
"date": { "type": "string", "description": "YYYY-MM-DD" },
|
||||
"time": { "type": "string", "description": "HH:MM, 24-hour" },
|
||||
"duration_minutes": { "type": "integer" }
|
||||
},
|
||||
"required": ["title", "date", "time", "duration_minutes"]
|
||||
}
|
||||
},
|
||||
"set_timer": {
|
||||
"description": "Start a countdown timer.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "minutes": { "type": "integer" } },
|
||||
"required": ["minutes"]
|
||||
}
|
||||
},
|
||||
"get_stock_price": {
|
||||
"description": "Latest price of a stock by its ticker symbol.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "ticker": { "type": "string", "description": "e.g. AAPL" } },
|
||||
"required": ["ticker"]
|
||||
}
|
||||
},
|
||||
"search_files": {
|
||||
"description": "Search the user's files.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": { "type": "string" },
|
||||
"extension": { "type": "string", "description": "File extension without the dot, e.g. pdf" }
|
||||
},
|
||||
"required": ["query"]
|
||||
}
|
||||
},
|
||||
"send_message": {
|
||||
"description": "Send a chat message to a contact.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"recipient": { "type": "string" },
|
||||
"text": { "type": "string" }
|
||||
},
|
||||
"required": ["recipient", "text"]
|
||||
}
|
||||
},
|
||||
"calculate": {
|
||||
"description": "Evaluate an arithmetic expression.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "expression": { "type": "string", "description": "e.g. 3 * (4 + 5)" } },
|
||||
"required": ["expression"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "weather-berlin",
|
||||
"tools": ["get_weather", "get_stock_price", "set_timer"],
|
||||
"prompt": "What's the weather in Berlin right now? Use Celsius.",
|
||||
"expect": { "name": "get_weather", "args": { "city": "Berlin", "unit": "celsius" } }
|
||||
},
|
||||
{
|
||||
"id": "currency-usd-eur",
|
||||
"tools": ["convert_currency", "calculate", "get_stock_price"],
|
||||
"prompt": "How much is 250 US dollars in euros?",
|
||||
"expect": { "name": "convert_currency", "args": { "amount": 250, "from": "USD", "to": "EUR" } }
|
||||
},
|
||||
{
|
||||
"id": "calendar-budget",
|
||||
"tools": ["create_calendar_event", "set_timer", "send_message"],
|
||||
"prompt": "Put a meeting called Budget review on 2026-11-03 at 14:30 for 45 minutes in my calendar.",
|
||||
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "budget review" }, "date": "2026-11-03", "time": "14:30", "duration_minutes": 45 } }
|
||||
},
|
||||
{
|
||||
"id": "timer-12",
|
||||
"tools": ["set_timer", "create_calendar_event", "get_weather"],
|
||||
"prompt": "Set a timer for 12 minutes.",
|
||||
"expect": { "name": "set_timer", "args": { "minutes": 12 } }
|
||||
},
|
||||
{
|
||||
"id": "stock-aapl",
|
||||
"tools": ["get_stock_price", "convert_currency", "search_files"],
|
||||
"prompt": "What's Apple's stock price at the moment? The ticker is AAPL.",
|
||||
"expect": { "name": "get_stock_price", "args": { "ticker": "AAPL" } }
|
||||
},
|
||||
{
|
||||
"id": "files-invoices",
|
||||
"tools": ["search_files", "send_message", "calculate"],
|
||||
"prompt": "Find my PDF files about invoices.",
|
||||
"expect": { "name": "search_files", "args": { "query": { "contains": "invoice" }, "extension": { "oneOf": ["pdf", ".pdf"] } } }
|
||||
},
|
||||
{
|
||||
"id": "message-maria",
|
||||
"tools": ["send_message", "create_calendar_event", "set_timer"],
|
||||
"prompt": "Tell Maria that I'll be ten minutes late.",
|
||||
"expect": { "name": "send_message", "args": { "recipient": "Maria", "text": { "contains": "late" } } }
|
||||
},
|
||||
{
|
||||
"id": "weather-tokyo-f",
|
||||
"tools": ["get_weather", "convert_currency", "search_files"],
|
||||
"prompt": "Weather in Tokyo, in Fahrenheit please.",
|
||||
"expect": { "name": "get_weather", "args": { "city": "Tokyo", "unit": "fahrenheit" } }
|
||||
},
|
||||
{
|
||||
"id": "currency-jpy-chf",
|
||||
"tools": ["calculate", "convert_currency", "get_weather"],
|
||||
"prompt": "Convert 1200 Japanese yen to Swiss francs.",
|
||||
"expect": { "name": "convert_currency", "args": { "amount": 1200, "from": "JPY", "to": "CHF" } }
|
||||
},
|
||||
{
|
||||
"id": "timer-90",
|
||||
"tools": ["create_calendar_event", "set_timer", "send_message"],
|
||||
"prompt": "I need a 90 minute timer.",
|
||||
"expect": { "name": "set_timer", "args": { "minutes": 90 } }
|
||||
},
|
||||
{
|
||||
"id": "calendar-dentist",
|
||||
"tools": ["send_message", "get_weather", "create_calendar_event"],
|
||||
"prompt": "Schedule 'Dentist' for 2026-12-01 at 09:00, it takes 30 minutes.",
|
||||
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "dentist" }, "date": "2026-12-01", "time": "09:00", "duration_minutes": 30 } }
|
||||
},
|
||||
{
|
||||
"id": "calc-17x23",
|
||||
"tools": ["calculate", "get_stock_price", "set_timer"],
|
||||
"prompt": "What is 17 times 23? Use the calculator.",
|
||||
"expect": { "name": "calculate", "args": { "expression": { "matches": "^\\s*17\\s*[*x×]\\s*23\\s*$" } } }
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { hostname, userInfo } from "node:os";
|
||||
import { describe, it } from "node:test";
|
||||
import { endpointRunMeta, endpointSystem, gpuLabel, imageTag, metaNotes, metaRows, modelLabel, pcieLabel, quantFromName } from "./benchmark-meta";
|
||||
import type { EndpointHardware, EndpointSnapshot } from "./db/schema";
|
||||
import { formatLinkPair, parseLinkText, systemSummaryText } from "./hardware";
|
||||
|
||||
const hardware: EndpointHardware = {
|
||||
gpuName: "Intel Arc Pro B65",
|
||||
gpuCount: 2,
|
||||
vramGb: 32,
|
||||
pcie: "Gen5 x16",
|
||||
p2p: "off",
|
||||
rebar: true,
|
||||
gpuDriver: "xe (kernel 6.17.1)",
|
||||
cpu: "AMD EPYC 9124 16-Core Processor",
|
||||
memoryGb: 128,
|
||||
os: "Debian GNU/Linux 13 (trixie)",
|
||||
virtualization: "Proxmox VM with GPU passthrough",
|
||||
kvCache: "q8_0",
|
||||
description: "testing q8 KV",
|
||||
};
|
||||
|
||||
const snap = (h: EndpointHardware = hardware, over: Partial<EndpointSnapshot> = {}): EndpointSnapshot => ({
|
||||
type: "endpoint",
|
||||
endpointName: "arc-box llama",
|
||||
model: "Qwen3-8B-Q4_K_M.gguf",
|
||||
engine: "llama.cpp",
|
||||
engineVersion: "b6123",
|
||||
contextSize: 32768,
|
||||
hardware: h,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("PCIe links", () => {
|
||||
it("formats current vs maximum and parses typed links", () => {
|
||||
assert.equal(formatLinkPair({ gen: 4, width: 8 }, { gen: 5, width: 16 }), "Gen4 x8 of Gen5 x16");
|
||||
assert.equal(formatLinkPair({ gen: 5, width: 16 }, { gen: 5, width: 16 }), "Gen5 x16");
|
||||
assert.deepEqual(parseLinkText("gen 4 x8"), { gen: 4, width: 8 });
|
||||
assert.equal(parseLinkText("fast"), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("run metadata from an endpoint", () => {
|
||||
it("takes the GPUs, link and model facts from the hardware notes", () => {
|
||||
const m = endpointRunMeta(snap());
|
||||
assert.equal(gpuLabel(m), "2× Intel Arc Pro B65 (32 GiB)");
|
||||
assert.equal(pcieLabel(m), "Gen5 x16");
|
||||
assert.equal(m.p2p, "off");
|
||||
assert.equal(m.rebar, true);
|
||||
assert.equal(m.runtime.engineName, "llama.cpp");
|
||||
assert.equal(m.runtime.engineVersion, "b6123");
|
||||
assert.equal(modelLabel(m), "Qwen3-8B-Q4_K_M.gguf Q4_K_M with q8_0 KV cache");
|
||||
assert.equal(m.contextSize, 32768);
|
||||
assert.equal(endpointRunMeta(snap(hardware, { slots: 4 })).concurrency, 4, "slots the server reported");
|
||||
assert.equal(endpointRunMeta(snap({ ...hardware, concurrency: 2 }, { slots: 4 })).concurrency, 2, "the notes win");
|
||||
});
|
||||
|
||||
it("lets the notes override what the server reported, and leaves out what nobody knows", () => {
|
||||
const m = endpointRunMeta(snap({ engineName: "ik_llama.cpp", engineVersion: "4012", contextSize: 16384, quant: "IQ4_XS" }, { engine: null, engineVersion: null }));
|
||||
assert.equal(m.runtime.engineName, "ik_llama.cpp");
|
||||
assert.equal(m.runtime.engineVersion, "4012");
|
||||
assert.equal(m.model.quant, "IQ4_XS");
|
||||
assert.equal(m.contextSize, 16384);
|
||||
assert.equal(gpuLabel(m), null, "no GPU in the notes");
|
||||
const keys = metaRows(m).map((r) => r.key);
|
||||
assert.ok(!keys.includes("image") && !keys.includes("digest") && !keys.includes("pcie"));
|
||||
});
|
||||
|
||||
it("finds the quant in model names", () => {
|
||||
assert.equal(quantFromName("Qwen3-8B-Q4_K_M.gguf"), "Q4_K_M");
|
||||
assert.equal(quantFromName("unsloth/Qwen3-8B-GGUF:UD-IQ3_XXS"), "UD-IQ3_XXS");
|
||||
assert.equal(quantFromName("GLM-4.6-Q8_0-00001-of-00008.gguf"), "Q8_0");
|
||||
assert.equal(quantFromName("Qwen/Qwen3.8-27B-FP8"), "FP8");
|
||||
assert.equal(quantFromName("qwen3:8b"), null);
|
||||
assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
|
||||
});
|
||||
});
|
||||
|
||||
describe("system summary", () => {
|
||||
it("lists the facts from the notes", () => {
|
||||
const text = systemSummaryText(endpointSystem(hardware, "0.15.0"));
|
||||
assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor/);
|
||||
assert.match(text, /RAM: 128/);
|
||||
assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\)/);
|
||||
assert.match(text, /GPU driver: xe \(kernel 6\.17\.1\)/);
|
||||
assert.match(text, /Virtualization: VM \(Proxmox VM with GPU passthrough\)/);
|
||||
assert.match(text, /Kaname 0\.15\.0/);
|
||||
assert.match(systemSummaryText(endpointSystem({ virtualization: "bare metal" }, "x")), /Virtualization: bare metal/);
|
||||
});
|
||||
|
||||
it("never contains the endpoint's address, the hostname, user or paths", () => {
|
||||
const s = endpointSystem(hardware, "0.15.0");
|
||||
const notes = metaNotes(endpointRunMeta(snap()), s, hardware.description ?? null);
|
||||
const published = JSON.stringify([s, notes]);
|
||||
for (const secret of [hostname(), userInfo().username].filter((x) => x.length > 2)) assert.ok(!published.includes(secret), `contains ${secret}`);
|
||||
assert.doesNotMatch(published, /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
|
||||
assert.doesNotMatch(published, /https?:\/\//);
|
||||
assert.equal(notes.description, "testing q8 KV");
|
||||
assert.equal(notes.gpus, "2× Intel Arc Pro B65 (32 GiB)");
|
||||
assert.equal(notes.pcie_max, "Gen5 x16");
|
||||
// Only these keys exist; a new field must be added here on purpose.
|
||||
assert.deepEqual(Object.keys(s).sort(), ["cpu", "gpuDrivers", "kaname", "kernel", "memoryBytes", "os", "storage", "virtualization"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
// What a benchmark run records about its setup (RunMeta, SystemSummary) and the BetterBench notes
|
||||
// made from it. Kaname can't see the machine behind an endpoint, so both come from the endpoint's
|
||||
// hardware notes plus what the server reports. Pure; shared by the worker, the web app and tests.
|
||||
|
||||
import type { EndpointEngine, EndpointHardware, EndpointSnapshot, RunMeta, SystemSummary } from "@/lib/db/schema";
|
||||
import { formatLink, formatLinkPair, onOff, parseLinkText, systemSummaryText } from "@/lib/hardware";
|
||||
|
||||
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
|
||||
export function imageTag(ref: string): string | null {
|
||||
const noDigest = ref.split("@")[0];
|
||||
const last = noDigest.slice(noDigest.lastIndexOf("/") + 1);
|
||||
const i = last.indexOf(":");
|
||||
return i >= 0 ? last.slice(i + 1) : null;
|
||||
}
|
||||
|
||||
const REPO_QUANT = /(?:^|[-_.])(nvfp4|mxfp4|fp8(?:[-_]dynamic)?|int8|int4|w8a8|w4a16|awq|gptq|bnb[-_]?4bit|bf16|fp16)(?=$|[-_.])/i;
|
||||
|
||||
const NAME_QUANT = /[-_.:]((?:UD-)?(?:I?Q\d(?:_[A-Z0-9]+)*|BF16|F16|F32|MXFP4(?:_MOE)?|TQ\d_\d))$/i;
|
||||
|
||||
/** The quant named in a model name: a GGUF quant tag ("Q4_K_M", "IQ3_XXS") or FP8, AWQ, … */
|
||||
export function quantFromName(name: string): string | null {
|
||||
const base = name.trim().replace(/\.gguf$/i, "").replace(/-\d{5}-of-\d{5}$/, "");
|
||||
const gguf = base.match(NAME_QUANT);
|
||||
if (gguf) return gguf[1];
|
||||
const m = base.split(/[/:]/).pop()?.match(REPO_QUANT);
|
||||
return m ? m[1].toUpperCase().replace("_", "-") : null;
|
||||
}
|
||||
|
||||
export const ENGINE_LABEL: Record<EndpointEngine, string> = { "llama.cpp": "llama.cpp", vllm: "vLLM", sglang: "SGLang", ollama: "Ollama", other: "OpenAI-compatible server" };
|
||||
|
||||
/** The run's setup from the endpoint snapshot: the hardware notes win over what the server reported. */
|
||||
export function endpointRunMeta(s: EndpointSnapshot): RunMeta {
|
||||
const h = s.hardware;
|
||||
const count = h.gpuName?.trim() ? Math.max(1, h.gpuCount ?? 1) : 0;
|
||||
const link = h.pcie ? parseLinkText(h.pcie) : null;
|
||||
const engine = s.engine ?? "other";
|
||||
return {
|
||||
v: 1,
|
||||
gpus: Array.from({ length: count }, () => ({
|
||||
name: h.gpuName!.trim(),
|
||||
vramMb: h.vramGb ? Math.round(h.vramGb * 1024) : null,
|
||||
linkCurrent: link,
|
||||
linkMax: link,
|
||||
rebar: h.rebar ?? null,
|
||||
})),
|
||||
// Typed in by the user, not sampled at idle.
|
||||
linkUnderLoad: true,
|
||||
p2p: count < 2 ? "n/a" : (h.p2p ?? null),
|
||||
rebar: count ? (h.rebar ?? null) : null,
|
||||
runtime: {
|
||||
image: h.image?.trim() ?? "",
|
||||
tag: h.image?.trim() ? imageTag(h.image.trim()) : null,
|
||||
digest: null,
|
||||
engine,
|
||||
engineName: h.engineName?.trim() || ENGINE_LABEL[engine],
|
||||
engineVersion: h.engineVersion?.trim() || s.engineVersion,
|
||||
},
|
||||
model: { repoId: s.model, file: null, quant: h.quant?.trim() || quantFromName(s.model), kvCache: h.kvCache?.trim() || null },
|
||||
contextSize: h.contextSize ?? s.contextSize,
|
||||
concurrency: h.concurrency ?? s.slots ?? null,
|
||||
overridden: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** The publishable system summary from the notes: CPU, RAM, OS, driver, virtualization, Kaname. */
|
||||
export function endpointSystem(h: EndpointHardware, kaname: string): SystemSummary {
|
||||
const virt = h.virtualization?.trim() || null;
|
||||
const bare = !!virt && /bare[\s-]*metal/i.test(virt);
|
||||
return {
|
||||
cpu: { model: h.cpu?.trim() || null, cores: null, threads: null },
|
||||
// GB as entered (formatBytes shows decimal units too).
|
||||
memoryBytes: h.memoryGb ? Math.round(h.memoryGb * 1e9) : null,
|
||||
storage: null,
|
||||
os: h.os?.trim() || null,
|
||||
kernel: null,
|
||||
gpuDrivers: h.gpuDriver?.trim() ? [h.gpuDriver.trim()] : [],
|
||||
virtualization: { vm: virt ? !bare : null, hypervisor: virt && !bare ? virt : null, gpuPassthrough: null },
|
||||
kaname,
|
||||
};
|
||||
}
|
||||
|
||||
/** "2× NVIDIA RTX 4090 (24 GiB)", "1× Intel Arc Pro B65 (32 GiB) + 1× …"; null without GPUs. */
|
||||
export function gpuLabel(m: RunMeta): string | null {
|
||||
if (m.gpus.length === 0) return null;
|
||||
const counts = new Map<string, number>();
|
||||
for (const g of m.gpus) {
|
||||
const name = `${g.name ?? "unknown GPU"}${g.vramMb ? ` (${Math.round(g.vramMb / 1024)} GiB)` : ""}`;
|
||||
counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
}
|
||||
return [...counts].map(([name, n]) => `${n}× ${name}`).join(" + ");
|
||||
}
|
||||
|
||||
/** The PCIe links of the GPUs used, deduplicated; "(idle)" when not measured under load. */
|
||||
export function pcieLabel(m: RunMeta): string | null {
|
||||
const links = [...new Set(m.gpus.map((g) => formatLinkPair(g.linkCurrent, g.linkMax) ?? "unknown"))];
|
||||
if (!links.length) return null;
|
||||
const idle = !m.linkUnderLoad && m.gpus.some((g) => g.linkCurrent);
|
||||
return `${links.join(", ")}${idle ? " (at idle)" : ""}`;
|
||||
}
|
||||
|
||||
/** Maximum links only ("Gen5 x16"): known before the run, unlike the link under load. */
|
||||
export function pcieMaxLabel(m: RunMeta): string | null {
|
||||
const links = [...new Set(m.gpus.map((g) => formatLink(g.linkMax) ?? "unknown"))];
|
||||
return links.length ? links.join(", ") : null;
|
||||
}
|
||||
|
||||
export const engineLabel = (m: RunMeta) => [m.runtime.engineName, m.runtime.engineVersion].filter(Boolean).join(" ");
|
||||
|
||||
/** "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache" */
|
||||
export function modelLabel(m: RunMeta): string {
|
||||
const name = m.model.repoId.split("/").pop() ?? m.model.repoId;
|
||||
return `${name}${m.model.quant ? ` ${m.model.quant}` : ""}${m.model.kvCache ? ` with ${m.model.kvCache} KV cache` : ""}`;
|
||||
}
|
||||
|
||||
/** Rows for the run page, compare views and sweeps (label → value, "unknown" where not known). */
|
||||
export function metaRows(m: RunMeta): { key: string; label: string; value: string }[] {
|
||||
return [
|
||||
{ key: "gpus", label: "GPUs", value: gpuLabel(m) ?? "none (CPU)" },
|
||||
...(m.gpus.length ? [{ key: "pcie", label: "PCIe", value: pcieLabel(m) ?? "unknown" }] : []),
|
||||
...(m.gpus.length ? [{ key: "p2p", label: "P2P", value: m.p2p ?? "unknown" }] : []),
|
||||
...(m.gpus.length ? [{ key: "rebar", label: "ReBAR", value: onOff(m.rebar) }] : []),
|
||||
{ key: "engine", label: "Engine", value: engineLabel(m) || "unknown" },
|
||||
...(m.runtime.image ? [{ key: "image", label: "Image", value: m.runtime.image }] : []),
|
||||
...(m.runtime.digest ? [{ key: "digest", label: "Digest", value: m.runtime.digest }] : []),
|
||||
{ key: "model", label: "Model", value: modelLabel(m) },
|
||||
{ key: "ctx", label: "Context", value: m.contextSize != null ? m.contextSize.toLocaleString("en-US") : "unknown" },
|
||||
{ key: "concurrency", label: "Concurrency", value: m.concurrency != null ? String(m.concurrency) : "server default" },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* BetterBench --note values (recorded in results.json, shown in its report and published to
|
||||
* launch80). `engine` is the key launch80 uses to name the stack.
|
||||
*/
|
||||
export function metaNotes(m: RunMeta, system: SystemSummary | null, description: string | null): Record<string, string> {
|
||||
const notes: Record<string, string> = {
|
||||
engine: engineLabel(m) || m.runtime.engine,
|
||||
...(m.runtime.image ? { image: m.runtime.image } : {}),
|
||||
...(m.runtime.digest ? { digest: m.runtime.digest } : {}),
|
||||
...(m.model.quant ? { quant: m.model.quant } : {}),
|
||||
...(m.model.kvCache ? { kv_cache: m.model.kvCache } : {}),
|
||||
...(m.contextSize != null ? { ctx: String(m.contextSize) } : {}),
|
||||
...(m.concurrency != null ? { concurrency: String(m.concurrency) } : {}),
|
||||
gpus: gpuLabel(m) ?? "none",
|
||||
};
|
||||
if (m.gpus.length) {
|
||||
notes.pcie_max = pcieMaxLabel(m) ?? "unknown";
|
||||
notes.p2p = m.p2p ?? "unknown";
|
||||
notes.rebar = onOff(m.rebar);
|
||||
}
|
||||
if (system) notes.system = systemSummaryText(system);
|
||||
if (description?.trim()) notes.description = description.trim().replace(/\s+/g, " ").slice(0, 2000);
|
||||
return notes;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
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";
|
||||
import type { BenchmarkSummary, DeploymentSnapshot, EndpointSnapshot } from "./db/schema";
|
||||
|
||||
const snap = {
|
||||
deploymentName: "bench test",
|
||||
@@ -15,7 +15,7 @@ const snap = {
|
||||
memoryMb: 2640,
|
||||
command: "",
|
||||
host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
|
||||
} as BenchmarkSnapshot;
|
||||
} as DeploymentSnapshot;
|
||||
|
||||
const summary: BenchmarkSummary = {
|
||||
v: 2,
|
||||
@@ -50,7 +50,25 @@ const summary: BenchmarkSummary = {
|
||||
|
||||
const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
|
||||
|
||||
const endpointSnap: EndpointSnapshot = {
|
||||
type: "endpoint",
|
||||
endpointName: "arc box",
|
||||
model: "Qwen3-8B-Q4_K_M.gguf",
|
||||
engine: "llama.cpp",
|
||||
engineVersion: "b6123",
|
||||
contextSize: 32768,
|
||||
hardware: { gpuName: "Intel Arc Pro B65", gpuCount: 2 },
|
||||
};
|
||||
|
||||
describe("benchmark report (launch80 conventions)", () => {
|
||||
it("describes an endpoint run from its hardware notes, without the endpoint's name", () => {
|
||||
assert.equal(describeHardware(endpointSnap), "2× Intel Arc Pro B65");
|
||||
assert.equal(describeHardware({ ...endpointSnap, hardware: { cpu: "AMD EPYC 7282 16-Core Processor" } }), "an AMD EPYC 7282");
|
||||
const s = reportSummary({ ...run, snapshot: endpointSnap });
|
||||
assert.match(s, /Qwen3-8B-Q4_K_M\.gguf \(Q4_K_M, 32,768-token context\) on llama\.cpp b6123, 2× Intel Arc Pro B65/);
|
||||
assert.doesNotMatch(s, /arc box/);
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// 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 { quantFromName } from "@/lib/benchmark-meta";
|
||||
import { engineName, isEndpointSnapshot, modelName } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
@@ -23,21 +25,31 @@ 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)". */
|
||||
const shortCpu = (cpu: string | null | undefined) =>
|
||||
cpu
|
||||
?.replace(/\s+\d+-Core Processor$/i, "")
|
||||
.replace(/\(R\)|\(TM\)/g, "")
|
||||
.trim();
|
||||
|
||||
/** "RTX 3080" / "2× Arc Pro B65" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
|
||||
export function describeHardware(s: BenchmarkSnapshot): string {
|
||||
if (isEndpointSnapshot(s)) {
|
||||
const h = s.hardware;
|
||||
if (h.gpuName?.trim()) return (h.gpuCount ?? 1) > 1 ? `${h.gpuCount}× ${h.gpuName.trim()}` : h.gpuName.trim();
|
||||
const cpu = shortCpu(h.cpu);
|
||||
return cpu ? `an ${cpu}` : "unknown hardware";
|
||||
}
|
||||
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();
|
||||
const cpu = shortCpu(s.host?.cpuModel);
|
||||
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 {
|
||||
if (isEndpointSnapshot(s)) return s.hardware.quant?.trim() || quantFromName(s.model) || "weights not stated";
|
||||
return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
|
||||
}
|
||||
|
||||
@@ -53,13 +65,19 @@ export function reportSubtitle(run: Run): string {
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
/** The context window the run had (endpoint notes, the server's report, or the launch options). */
|
||||
export function contextOf(s: BenchmarkSnapshot): number | null {
|
||||
return isEndpointSnapshot(s) ? (s.hardware.contextSize ?? s.contextSize) : s.options.contextSize;
|
||||
}
|
||||
|
||||
export function reportSummary(run: Run): string {
|
||||
const s = run.snapshot;
|
||||
const ctx = contextOf(s);
|
||||
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 ?? ""}${
|
||||
`${modelName(s)} (${weightsLabel(s)}${ctx ? `, ${int(ctx)}-token context` : ""}) on ${engineName(s)}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
|
||||
sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
|
||||
}.`.replace(" ,", ","),
|
||||
);
|
||||
@@ -158,7 +176,7 @@ export function reportCaveats(run: Run): string[] {
|
||||
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 (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context${(sum.maxModelLen ?? contextOf(run.snapshot)) ? ` of ${int((sum.maxModelLen ?? contextOf(run.snapshot))!)}` : ""}).`);
|
||||
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);
|
||||
}
|
||||
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user