Merge features-c2: section C of the backlog, items 6-24, for v0.11.2
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
1b8f08ea89
469 files changed
+59479
-2945
No files matched your search
@@ -39,6 +39,16 @@ jobs:
|
||||
- name: Build
|
||||
run: go build ./...
|
||||
|
||||
# The Terraform provider is a module of its own, which ./... above does
|
||||
# not reach. Its tests check its client against docs/admin-api.openapi.json,
|
||||
# so a change to the admin API that breaks the provider fails here. The
|
||||
# acceptance tests (TF_ACC=1) are left out: they need Terraform itself.
|
||||
- name: Test the Terraform provider
|
||||
working-directory: terraform-provider-llmgw
|
||||
run: |
|
||||
go vet ./...
|
||||
go test ./...
|
||||
|
||||
# The NVML backend needs cgo and cannot run without a driver, but it must
|
||||
# at least keep compiling: it is the only source of NVLink topology and a
|
||||
# break would otherwise surface on a GPU node, far from here.
|
||||
|
||||
@@ -5,3 +5,7 @@
|
||||
*.db-shm
|
||||
.DS_Store
|
||||
coverage.out
|
||||
# The provider built in place, and what Terraform leaves beside an example.
|
||||
/terraform-provider-llmgw/terraform-provider-llmgw
|
||||
/terraform-provider-llmgw/examples/.terraform*
|
||||
/terraform-provider-llmgw/examples/terraform.tfstate*
|
||||
+309
-19
@@ -412,62 +412,352 @@ portal is not done — the page shows; the console and ctl change.
|
||||
templates driven by `server init` or the console; llmgw-native webhooks
|
||||
for model parked, budget spent, update available (from the reconciler
|
||||
and `modelserve`).
|
||||
6. **Request metadata and tags (S).** Accept `metadata`/`user` from the
|
||||
6. **Done (branch `features-c2`):** `metadata`, `x-llmgw-tags` and `user`
|
||||
on the usage record (migration 0023), `ctl request` shows them,
|
||||
`router.tag_labels` metrics with 100 values per tag. Left: export and
|
||||
`ctl usage` by tag or end user (the hourly and daily sums do not carry
|
||||
tags; it would read the request records, within their retention).
|
||||
**Request metadata and tags (S).** Accept `metadata`/`user` from the
|
||||
body or `x-llmgw-tags`; store on the usage row; tenant metric labels
|
||||
behind an allowlist. `router/handlers.go` parse, `accounting/recorder.go`.
|
||||
7. **Canary and weighted A/B between model revisions (M).**
|
||||
7. **Done (branch `features-c2`):** `ctl model canary/promote/canaries`,
|
||||
session-sticky split with `x-llmgw-variant` pins, rollback on error rate
|
||||
or TTFT, `canary_rolled_back` notification, console menu. Left: A/B
|
||||
between two different models (the split is between a model and its
|
||||
newer weights); the comparison is per control plane and lives in memory,
|
||||
so a restart begins it again; a key-level pin.
|
||||
**Canary and weighted A/B between model revisions (M).**
|
||||
`control/modelserve/updates.go` `replace` swaps every replica; add
|
||||
weighted routing across two revisions/aliases (scheduler filter, alias
|
||||
resolution in `router/router.go:569`), a header/key pin, automatic
|
||||
rollback on error-rate or TTFT regression from per-replica metrics.
|
||||
8. **Batch API and Files (M–L).** `/v1/files`, `/v1/batches`, JSONL
|
||||
8. **Done (branch `features-c2`):** `/v1/files` and `/v1/batches`
|
||||
(OpenAI's shape), worker under a store lease, lines kept as served,
|
||||
lowest band, usage tagged `batch=<id>`, output and error files with
|
||||
retention, `no_store` refused. Left: the Responses API (`/v1/responses`)
|
||||
as a batch endpoint; the console and `ctl` do not list batches (an
|
||||
operator sees them through usage tags); a file is one row in the store,
|
||||
so a store backup carries batch files with it.
|
||||
**Batch API and Files (M–L).** `/v1/files`, `/v1/batches`, JSONL
|
||||
storage, a worker feeding the bronze band, accounting. New
|
||||
`internal/router/batch`.
|
||||
9. **Request/response logging and replay (M).** Opt-in per project with
|
||||
9. **Done (branch `features-c2`):** `keys requests` (retention, sample),
|
||||
kept after redaction, `ctl request --body/--replay`, console, pruning.
|
||||
Left: a streamed answer is kept as its text, not its chunks; replay is
|
||||
one request at a time (a set of them against a model is item 21's eval).
|
||||
**Request/response logging and replay (M).** Opt-in per project with
|
||||
retention like threads; sampled or full; redaction hooks from B;
|
||||
`ctl request <id> --body`; replay against another model.
|
||||
10. **OpenAI compatibility gaps (S–M each).** Responses: `text.format` →
|
||||
10. **Done (branch `features-c2`):** Responses `text.format`,
|
||||
`input_image`, `previous_response_id` (thread in the id); rerank and
|
||||
score passthrough; transcription and translation as multipart;
|
||||
`/v1/moderations` by the judge. Left: audio is charged no tokens (an
|
||||
engine's duration usage is not read); `input_image` by `file_id`;
|
||||
moderation scores are 0 or 1, as a judge says yes or no.
|
||||
**OpenAI compatibility gaps (S–M each).** Responses: `text.format` →
|
||||
`response_format`, `input_image`, `previous_response_id` via threads
|
||||
(`router/responses.go`). Rerank/score passthrough for vLLM,
|
||||
`/v1/audio/transcriptions` for a whisper engine, `/v1/moderations`
|
||||
mapped to the guard model.
|
||||
11. **Anthropic `/v1/messages` (M).** Translate like `responses.go`.
|
||||
12. **`server restore` (S).** Restore is manual shell today
|
||||
11. **Done (branch `features-c2`):** `/v1/messages` and `count_tokens`,
|
||||
streamed and not, tools, images, `x-api-key`, Anthropic error shape.
|
||||
Left: extended thinking (a reasoning model's thoughts are not mapped to
|
||||
thinking blocks); prompt caching; the account page's "Connect your
|
||||
editor" does not offer Claude Code yet.
|
||||
**Anthropic `/v1/messages` (M).** Translate like `responses.go`.
|
||||
12. **Done (branch `features-c2`):** `server restore` (dry run, version
|
||||
check, decryption, modes and owners, SQLite and PostgreSQL),
|
||||
`backup_copy_to` (directory or ssh), the drill in docs/install.md.
|
||||
Left: restoring a replicated store's members (restore into the primary;
|
||||
Patroni replicates it); the console's Back up now does not offer
|
||||
restore; an ssh copy holds the archive in memory while it sends it.
|
||||
**`server restore` (S).** Restore is manual shell today
|
||||
(`docs/install.md:1187`); add the command with version check, dry run,
|
||||
off-host copy target; a documented DR drill.
|
||||
13. **SLO-based admission and token-level metrics (S–M).** TPOT and
|
||||
13. **Done (branch `features-c2`):** TPOT, inter-token and tokens/s
|
||||
histograms by model, pool and tenant; `slo` pressure in admission's
|
||||
saturation; `llmgw_model_slo_seconds` and `llmgw-slo` alerts. Left: the
|
||||
p99 is per control plane, from its own requests; an SLO per band or per
|
||||
tenant; placement does not yet add replicas for an SLO (item 14).
|
||||
**SLO-based admission and token-level metrics (S–M).** TPOT and
|
||||
inter-token histograms, output tokens/s per model and tenant in
|
||||
`router/metrics.go`; use `catalog.SLO` in `admission/saturation.go`.
|
||||
14. **Scheduled and warm-pool autoscaling (S–M).** Time-of-day min/max,
|
||||
14. **Done (branch `features-c2`):** `scaling.schedule` (days, from, to,
|
||||
min, max; past midnight), `scaling.prewarm`, `control.timezone`;
|
||||
queue-depth scaling was there already. Left: `ctl scale` sets min and
|
||||
max only (a schedule is set in the definition); scaling for an SLO
|
||||
rather than for queue depth.
|
||||
**Scheduled and warm-pool autoscaling (S–M).** Time-of-day min/max,
|
||||
pre-warm, queue-depth scaling in `catalog.Scaling`,
|
||||
`control/reconciler/demand.go`, `headroom.go`.
|
||||
15. **Secrets management (S–M).** Vault/KMS for `api_key_file`, the DSN, the
|
||||
15. **Done (branch `features-c2`):** `env:` and `vault:` references
|
||||
wherever a secret file is named (store address, api_key_file, OIDC,
|
||||
SCIM, webhooks), Vault KV with token or AppRole, `secrets.master_key`
|
||||
sealing cluster_secrets (Vault transit or a local key). Left: the
|
||||
certificate authority's key is still a file in /etc/llmgw (signing in
|
||||
Vault's PKI engine instead is its own change); rotating the master key;
|
||||
`backup_copy_key` and `admin_token_file` are files only.
|
||||
**Secrets management (S–M).** Vault/KMS for `api_key_file`, the DSN, the
|
||||
CA key, `cluster_secrets` (`store/secrets.go`, `store/seal.go`);
|
||||
envelope-encrypt them in backups (with A8 backups).
|
||||
16. **GDPR and residency (S).** "Forget user" anonymises `user_id` in usage
|
||||
16. **Done (branch `features-c2`):** `users forget` (pseudonymised usage
|
||||
and sums, kept requests, files, batches, limits and audit names), `keys
|
||||
residency --in-cluster` (asked-for, fallback and canary). Left: an
|
||||
export of everything held about a person (article 15); residency by
|
||||
region between several clusters; backups keep what was forgotten until
|
||||
they age out.
|
||||
**GDPR and residency (S).** "Forget user" anonymises `user_id` in usage
|
||||
and rollups and erases threads/memory (`store/hierarchy.go:241` leaves
|
||||
it today); per-project "never route to an External provider".
|
||||
17. **Response/semantic cache (M).** Exact-match first, per project,
|
||||
17. **Done (branch `features-c2`):** exact-match answer cache per project (`keys
|
||||
cache --ttl/--any/--off`, console **Cache answers…**, `projects`
|
||||
columns, 30-second setting cache), reproducible answers only unless
|
||||
`--any`, LRU in memory bounded by `router.cache.max_bytes` and
|
||||
`max_entry_bytes`, streamed answers kept and replayed as chunks,
|
||||
`x-llmgw-cache` and `Cache-Control: no-cache`, guardrails before a hit
|
||||
and the output policy on it, `no_store` and threads bypass, a hit
|
||||
recorded as `cache_hit` with no tokens and no cost (migration 0027),
|
||||
metrics, docs. Left: semantic (embedding-similarity) caching through the
|
||||
embeddings models; a cache shared across control planes (each process
|
||||
keeps its own, deliberately: a shared one would write every answer to
|
||||
the store); a hit still waits its turn in admission, because the
|
||||
guardrails judge the request after admission and the key is the request
|
||||
they let through; logprobs in a streamed answer leave it unkept; `users
|
||||
forget` does not reach into the cache (answers age out by the TTL); no
|
||||
listing or flushing of what is cached (`--off` stops it being served at
|
||||
once, the memory is freed by TTL and LRU).
|
||||
**Response/semantic cache (M).** Exact-match first, per project,
|
||||
opt-in, TTL; semantic via the embeddings models later. Before
|
||||
`dispatch` in `router/handlers.go`.
|
||||
18. **Kubernetes/Helm and an air-gapped bundle (M).** `deploy/`,
|
||||
18. **Done (branch `features-c2`):** offline bundles — `llmgw bundle create`
|
||||
(releases with signed checksums, every llama.cpp build per arch/variant
|
||||
with GitHub's checksums, starter/judge and named Hugging Face model
|
||||
files pinned and checked; directory or tar; manifest sha256), `bundle
|
||||
import` (checked, all-or-nothing, into the mirror under `_llmgw/`),
|
||||
`bundle trust`, `bundle show --verify`;
|
||||
`offline.mirror`/`offline.checksums` in server.yaml, with nodes
|
||||
installing llama.cpp from the mirror against checksums the control plane
|
||||
sends over the agent stream (proto `EngineWant.offline_*`), releases
|
||||
defaulting to the mirror for `node add`, `ctl upgrade` and agent
|
||||
upgrades, update checks off; `server init --bundle` and the setup form's
|
||||
bundle fields; docs/data.md's offline claim corrected; install.md
|
||||
"Offline sites". A Helm chart for the control plane
|
||||
(`deploy/helm/llmgw`, one replica, SQLite PVC or external PostgreSQL,
|
||||
Secrets, Services, Ingress, ServiceMonitor) with
|
||||
`deploy/container/Dockerfile` and docs/kubernetes.md; GPU nodes stay
|
||||
outside Kubernetes by design. Left: vLLM/SGLang offline (a wheelhouse of
|
||||
several GB per CUDA build and a uv `--find-links` install path); the
|
||||
NVML release binary and uv in bundles; the setup wizard's preflight
|
||||
still fails a machine without internet; `join`'s printed `curl` from the
|
||||
mirror checks nothing; models in a bundle are single files (no whole-
|
||||
repository safetensors sets yet); the chart runs one replica (a standby
|
||||
is never ready, so HA in Kubernetes needs a different readiness design),
|
||||
has not been installed on a real cluster, and ships no agent DaemonSet;
|
||||
no published container image.
|
||||
**Kubernetes/Helm and an air-gapped bundle (M).** `deploy/`,
|
||||
`agent/provision`; `docs/data.md` claims offline operation but install
|
||||
assumes the internet.
|
||||
19. **OpenAPI for the admin API, Terraform provider (M).** Generate from
|
||||
19. **Done (branch `features-c2`):** `adminapi.Routes` and
|
||||
`internal/docgen/openapi` generating `docs/admin-api.openapi.json` (3.1,
|
||||
bearer security, every route, query parameters, schemas from the Go
|
||||
types with their comments), served embedded at `GET
|
||||
/api/v1/openapi.json`, kept true by a route-table test and a staleness
|
||||
test; validated with openapi-spec-validator and openapi-generator-cli.
|
||||
`GET /api/v1/models/{name}`. `docs/admin-api.md`. `terraform-provider-
|
||||
llmgw/` (terraform-plugin-framework): `llmgw_model`, `llmgw_quota`,
|
||||
`llmgw_guard_attachment`, data sources `llmgw_models` and `llmgw_nodes`;
|
||||
client tests against a fake admin API and the OpenAPI document;
|
||||
acceptance tests with Terraform and OpenTofu against the fake; one
|
||||
apply, empty plan, in-place change and destroy against a real `llmgw
|
||||
server` run by hand. Left: organizations, teams, projects, people and
|
||||
keys are not in the admin API (they are `llmgw org`/`users`/`keys`
|
||||
against the store), so not in the provider; a model's definition beyond
|
||||
scaling, class, owner and adapters is changed by replacing it (the API
|
||||
has no edit, and `resources` is not used yet); `canary`, `slo`,
|
||||
`scaling.schedule` and `prewarm`, `guard` role and `origin` are not in
|
||||
`llmgw_model`; models cannot be imported; the provider is not published
|
||||
to a registry and has no release build; the acceptance tests are not run
|
||||
in CI (they need Terraform); the document's schemas mark nothing
|
||||
required and give no enums; `catalog.SLO`'s fields have no JSON tags, so
|
||||
they are `TTFTp99` and `TPOTp99` on the wire.
|
||||
**OpenAPI for the admin API, Terraform provider (M).** Generate from
|
||||
`adminapi/api.go` routes via `docgen`.
|
||||
20. **Tracing beyond the router (S).** Spans for reconciler, placement,
|
||||
20. **Done (branch `features-c2`):** spans for the reconcile pass (begun only
|
||||
when a pass does something), placement with its answer or rejections,
|
||||
scale-up/down, drain, stop, eviction, preemption, reaping, restarts and
|
||||
lost nodes; a `replica start` span from placement to serving whose
|
||||
context travels to the agent in the start command
|
||||
(`ControlMessage.trace`), where weights fetch, engine launch, rendezvous
|
||||
and readiness wait continue the trace; stops, drains, adoption and
|
||||
engine installs; modelserve jobs as a trace with a span per step linked
|
||||
to the replica's start; an agent `tracing` block; docs in install.md's
|
||||
"Tracing". Left: the router's span for a request does not link to the
|
||||
replica it was sent to's start; heartbeats, fabric scans, logs and agent
|
||||
upgrades are not traced; the supervisor has no restart span because it
|
||||
never restarts an engine itself (a restart is the reconciler's `restart
|
||||
replica` and reaches a node as a stop and a start); canary and promote
|
||||
jobs, which landed on `features-c2` after this was branched, are traced
|
||||
only through the shared step recording (as `<kind> model`), unchecked by
|
||||
a test.
|
||||
**Tracing beyond the router (S).** Spans for reconciler, placement,
|
||||
agent start (`obs/trace.go`, `control/reconciler`, `agent/supervisor`).
|
||||
21. **Eval harness (M).** `llmgw eval` extending `internal/bench` with
|
||||
21. **Done (branch `features-c2`):** `internal/bench/eval` (suites in YAML or
|
||||
JSON lines; exact, contains, regex, number, a JSON Schema subset, and a
|
||||
judge model with a rubric; weights and a threshold), run on the control
|
||||
plane through `Router.Replay`; `llmgw ctl eval MODEL --suite FILE|NAME`,
|
||||
`--history`, `--run`, `--suites`; runs and their cases kept (migration
|
||||
0028, `eval_runs` and `eval_cases`); `model update`/`promote --eval
|
||||
SUITE --min-score N`, a model's standing gate (`ctl model gate`, `eval:`
|
||||
in the catalog) — a promote asks the canary first, an update tries the
|
||||
new weights as a 0% canary and promotes or removes it; the console's
|
||||
model menu; `arithmetic` and `json-format` in `deploy/eval/`, carried in
|
||||
the binary. Left: the suite of a model's standing gate is read by name
|
||||
on the control plane at the time of the update, so two control planes
|
||||
need the same `control.eval_dir`; a gated update needs room for one more
|
||||
replica while it runs (there is no in-place gate, and a declared model
|
||||
in server.yaml cannot be updated at all); no comparison against the old
|
||||
weights' score (the gate is an absolute threshold, not "no worse than
|
||||
before"); a run is not stopped once started (Esc in the console only
|
||||
stops watching it), and the in-memory progress of a run lives on the
|
||||
control plane that started it; runs are never pruned; the JSON Schema
|
||||
support is a subset (no `$ref`, `oneOf`, `not`, `uniqueItems`); judge
|
||||
cases go through the same concurrency as the model's, and a judge's
|
||||
answers are not kept, only its score and reason; a gateway without a
|
||||
control plane cannot run suites (there is no mode that asks through the
|
||||
client API with a key).
|
||||
**Eval harness (M).** `llmgw eval` extending `internal/bench` with
|
||||
quality suites gating `model update`.
|
||||
22. **MIG (M–L).** Treat a MIG slice as a GPU class in
|
||||
22. **Done (branch `features-c2`):** MIG instances discovered on both paths
|
||||
(nvidia-smi `-L` + `-q -x`; NVML through an interface with a faithful
|
||||
fake) and reported instead of their card, each with its MIG UUID, own
|
||||
memory and class `<card class>-mig-<profile>`; device numbers 1000 + 100
|
||||
× card + instance, shown as `card/migN`; placement on MIG classes;
|
||||
tp/pp/gpus/nodes above 1 on a MIG class refused in catalog validation
|
||||
and again in placement; `CUDA_VISIBLE_DEVICES=MIG-<uuid>` for vLLM and
|
||||
llama.cpp (no Vulkan device variable on MIG); per-instance memory and
|
||||
processes in heartbeats and the GPU check, card sensors under each
|
||||
instance, utilisation absent rather than zero; doctor MIG findings (`mig
|
||||
-lgi`/`-lci` parsed); `ctl nodes`, console, `ctl status`, `ctl model
|
||||
plan`/`serve` by class; docs/install.md MIG section. Written and tested
|
||||
against fakes only — untested on real MIG hardware. Left: run it on an
|
||||
A100/H100 in MIG mode (check `-L`/`-q -x`/`mig -lgi`/`-lci` and NVML MIG
|
||||
device names against the parsers, and that `CUDA_VISIBLE_DEVICES=MIG-…`
|
||||
reaches vLLM's workers through Ray); instances changed while the agent
|
||||
runs are only seen when it restarts (no rescan); llmgw does not create
|
||||
or reshape instances (no mig-parted integration); quotas count an
|
||||
instance as one GPU, the same as a whole card; SGLang on MIG not
|
||||
checked; device numbers assume fewer than 100 instances per card and
|
||||
that instance numbers stay put while shards run on them.
|
||||
**MIG (M–L).** Treat a MIG slice as a GPU class in
|
||||
`agent/discovery/gpu_nvml.go` and `control/placement`.
|
||||
23. **More engines (M each).** TensorRT-LLM/Triton adapter; Ollama/GGUF
|
||||
23. **Done (branch `features-c2`):** engine `trtllm`
|
||||
(`internal/agent/engines/trtllm.go`): `trtllm-serve` through a launcher
|
||||
of llmgw's that demands the replica's key (trtllm-serve has none) and
|
||||
writes the options file that turns on `/prometheus/metrics` and the
|
||||
iteration statistics; the scrape contract for it
|
||||
(`scrape.TRTLLMMapping`, with a per-engine metrics path); found, not
|
||||
installed — `engines.trtllm.python` in `agent.yaml`, probed from the
|
||||
package's metadata; catalog validation (GPU class, one node, no GGUF
|
||||
source, the flags a profile may not give); `ctl engine-check trtllm`,
|
||||
which asks `trtllm-serve serve --help` through its module. Ollama/GGUF
|
||||
import: `mirror import-ollama` (manifest parsing, blob digest check,
|
||||
projector beside the model, all or nothing, a model definition printed),
|
||||
`mirror import` for any local file, and the console's **I** on the
|
||||
Mirror view. Left: TensorRT-LLM has not run on real hardware — the first
|
||||
node with one should run `engine-check` and serve a model before anyone
|
||||
relies on it; no installer for it; no multi-node TensorRT-LLM replica
|
||||
(it needs an MPI or Slurm launch from one node); Triton Inference Server
|
||||
as an engine is not done; trtllm's queue gauges are set per iteration,
|
||||
so an idle engine shows its last batch until the next request;
|
||||
`--num_serve_frontends` is refused because extra front ends would not
|
||||
demand the key. The Ollama import runs on the mirror machine only — the
|
||||
mirror's API takes no files, so an Ollama elsewhere means copying the
|
||||
blob or running the import there; Ollama models kept as separate tensors
|
||||
or as several weight layers, and its LoRA adapters, are refused or left
|
||||
with a sentence; files an import run with `sudo` writes are root's, as
|
||||
`mirror add`'s are.
|
||||
**More engines (M each).** TensorRT-LLM/Triton adapter; Ollama/GGUF
|
||||
import. `agent/engines/engine.go` interface and the metric contract in
|
||||
`router/scrape`.
|
||||
24. Lower: precise KV-index routing (plan phase 6), LoRA affinity for
|
||||
24. **Done (branch `features-c2`), all six parts.** Lower: precise KV-index routing (plan phase 6), LoRA affinity for
|
||||
vLLM, multi-cluster federation via External providers, facility-aware
|
||||
placement (`docs/facility-aware-placement.md`), portal i18n, SDK/docs
|
||||
portal.
|
||||
What was built, and what is left:
|
||||
- 24 (portal i18n): built — English/Turkish catalogue with fallback, per-
|
||||
language templates, cookie/Accept-Language/`landing.language` choice
|
||||
and a footer switcher, Turkish numbers and dates, every template and
|
||||
handler message translated, tests that no template text stays English;
|
||||
left — errors built with fmt.Errorf in other packages (store, catalog,
|
||||
mirror, adminapi) still English on Turkish pages, percent sign
|
||||
placement is mixed (%50 on limits, 93% on cluster pages), RFC3339
|
||||
footer timestamps and plain-text http.Error bodies untranslated, the
|
||||
/docs documents themselves English, a per-person language column
|
||||
(cookie only today).
|
||||
- 24 (SDK/docs portal): built — /docs renders the embedded manual (goldmark,
|
||||
GFM, heading anchors, links rewritten, no script; public,
|
||||
`landing.docs_sign_in` to require a session), and docs/clients.md
|
||||
shows the official OpenAI/Anthropic SDKs against llmgw. Left: the
|
||||
console's generated "Commands" page is not in the portal (it is built
|
||||
from the cobra tree, which internal/web cannot see); no search across
|
||||
documents.
|
||||
- [~] 24. Precise KV index (tier 2) — built: vLLM KV events via the agent
|
||||
(loopback ZMQ, pure-Go zmq4, msgpack in both of vLLM's encodings)
|
||||
forwarded as net block-hash changes over the agent stream; router
|
||||
index, tokenize via the replica's `/tokenize`, sha256_cbor block-hash
|
||||
chain checked against cbor2/hashlib golden values; scorer by leading-
|
||||
block share with tier 1 fallback; opt-in `kv_events` per profile;
|
||||
metrics; docs. Left: validation against a real vLLM (event shape, hash
|
||||
agreement, `/tokenize` matching the served prompt, cost of
|
||||
tokenizing); vLLM's replay endpoint instead of resetting on a gap;
|
||||
data-parallel ranks (one publisher each, ports offset); hybrid models'
|
||||
cache groups and CPU-offloaded blocks; LoRA/multimodal/cache_salt
|
||||
requests (extra keys); a router-only deployment (no agents)
|
||||
subscribing directly; standby control planes have no index until they
|
||||
lead; a per-replica fallback when only some candidates have an index;
|
||||
caching tokenizations of repeated prompts.
|
||||
- **24 LoRA affinity (branch `features-c2`):** built `max_loaded_adapters`
|
||||
(catalog), vLLM adapter support at start and on demand
|
||||
(`engines/lora.go`, `vllm.go`), the agent linking fetched adapters as
|
||||
`llmgw-lora/<name>` in the engines' working directory, the router's
|
||||
adapter tracker (`router/lora.go`: loads/unloads with the engine key,
|
||||
LRU eviction never of an adapter in use, one load per adapter per
|
||||
replica, `/v1/models` sync, 404 reload) and the `adapter-affinity`
|
||||
scheduler filter in the chat, batch and long-context profiles, with
|
||||
metrics and docs; tested against a fake of vLLM's HTTP interface.
|
||||
**Left:** never run against a real vLLM — in particular that vLLM
|
||||
resolves the relative `llmgw-lora/<name>` path against its working
|
||||
directory on every node (multi-node too) and that unloading an adapter
|
||||
mid-request is harmless; the agent still fetches every adapter at
|
||||
replica start, so a new adapter needs a restart (fetching on first
|
||||
load would need an agent command and a proto change); load timeout and
|
||||
resync interval are constants, not config; SGLang's runtime LoRA API
|
||||
is not driven; no per-replica "adapters held" view in the console or
|
||||
admin API; the debug profile has no affinity.
|
||||
- 24. Multi-cluster federation — built: peers via `ctl federation` kept in
|
||||
the store, their models as PEER/MODEL synced from /v1/models
|
||||
(withdrawn-while-referenced), /ready health with latency and routing
|
||||
withdrawal, `ctl model fallbacks` for overflow, hop header loop
|
||||
refusal, residency/no_store hold, optional attribution tags, console
|
||||
view, metrics, docs. Left: server.yaml-declared models cannot name a
|
||||
peer model as a fallback (config catalog is validated before peers are
|
||||
read); per-peer CA / mTLS for peers behind a private CA; transitive
|
||||
federation (A→B→C models) deliberately not offered; latency is /ready
|
||||
RTT only (no per-request peer TTFT used in routing or weighting); the
|
||||
peer's adapters are not imported (listed as aliases); no console form
|
||||
to add/remove peers (CLI only); key file must exist on every control
|
||||
plane.
|
||||
- 24 (facility) — built: location labels (`ctl label`, agent.yaml),
|
||||
spreading across racks/PDUs, `keep_within`, held domains with drain
|
||||
(`ctl facility hold/release`, kept in the store), power caps from
|
||||
`facility.budgets` against declared/derived/measured draw, shown in
|
||||
explain-placement, `ctl nodes`, `ctl facility`, the console and the
|
||||
API. Left: temperature conditions with hysteresis and their
|
||||
enforcement (steps 3–4), a Prometheus/DCIM source, power headroom as a
|
||||
rack-levelling score, spreading multi-node replicas across racks,
|
||||
`llmgw_domain_*` metrics and alerts (near cap, over cap, stale data),
|
||||
shedding and tokens per watt (step 5), and a drained node's state
|
||||
surviving a restart.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+601
-1
@@ -21,7 +21,484 @@ is only released once its **exit criterion** is met, not when its code lands.
|
||||
Until v1.0.0 the minor version is the breaking one: configuration formats and Go
|
||||
APIs change between minors without a deprecation period.
|
||||
|
||||
## Unreleased
|
||||
## v0.11.2 — 2026-10-05
|
||||
|
||||
### Routing by what each vLLM replica's cache holds
|
||||
|
||||
- A vLLM profile can set `kv_events: true`. The agent then starts the engine
|
||||
publishing its KV cache events (`--kv-events-config`) to a port on
|
||||
127.0.0.1 the agent listens on, with `--prefix-caching-hash-algo
|
||||
sha256_cbor` and `PYTHONHASHSEED=1729`, so its block hashes can be
|
||||
computed outside Python. The events never leave the node.
|
||||
- The agent mirrors each engine's set of cached blocks and sends the net
|
||||
changes up its existing stream to the control plane four times a second
|
||||
(new `KVEvents` agent message), starting every new stream with a full
|
||||
copy. Lost events (a gap in vLLM's sequence numbers), an engine restart or
|
||||
`AllBlocksCleared` start a replica's index again; blocks offloaded to CPU,
|
||||
remote ones and a hybrid model's second cache group are not indexed.
|
||||
- The control plane passes them to the router's index, only for replicas
|
||||
the sending node runs, and empties what a stream described when it closes.
|
||||
- For a model with `kv_events`, the router asks one of its replicas to
|
||||
tokenize the request (vLLM's `/tokenize`, with messages and tools, so the
|
||||
chat template is applied exactly), hashes the tokens into blocks as vLLM
|
||||
does, and scores replicas by the share of the prompt's leading blocks they
|
||||
hold. The imbalance guard still applies. With no answer — no events yet,
|
||||
an image, a cache salt, a LoRA adapter, a failed or slow tokenize — it falls
|
||||
back to the approximate tree (`router.prefix`) or to load.
|
||||
- The agent checks first blocks against llmgw's hashing; an engine that
|
||||
hashes another way (a profile overriding the algorithm, a changed vLLM) is
|
||||
reported in the agent's log and `llmgw_kv_index_problem`, and routed as
|
||||
though it published nothing.
|
||||
- New settings `router.kv_index.tokenize_timeout` (250ms), `min_blocks` (4)
|
||||
and `max_blocks` (4096). New metrics `llmgw_kv_index_decisions_total`
|
||||
(`kv_hit`, `kv_miss_min_load`, `load_balance_override`,
|
||||
`fallback_no_index`, `fallback_unsupported`, `fallback_tokenize_failed`),
|
||||
`llmgw_kv_index_tokenize_seconds`, `llmgw_kv_index_blocks`.
|
||||
- Experimental: tested against vLLM's event format and hashing as its source
|
||||
defines them, and against libzmq and msgspec publishing — not yet against a
|
||||
running vLLM.
|
||||
|
||||
### LoRA adapters on vLLM, loaded on demand
|
||||
|
||||
- **vLLM models can carry adapters.** A PEFT adapter directory (a mirror
|
||||
version ending in `/`, a path on the nodes, or a Hugging Face repository
|
||||
id) is registered at start with `--enable-lora --lora-modules`, and a
|
||||
request names it as its model, as on llama.cpp. `scale` applies on
|
||||
llama.cpp only. SGLang and TensorRT-LLM profiles still refuse adapters.
|
||||
- **`max_loaded_adapters: N` on a model** has each replica hold at most N of
|
||||
its adapters. Replicas start holding none (vLLM with
|
||||
`VLLM_ALLOW_RUNTIME_LORA_UPDATING=True` and `--max-loras N`, unless the
|
||||
profile's args set their own). The router loads an adapter on a replica
|
||||
through `/v1/load_lora_adapter` when a request first wants it there, and
|
||||
unloads the least recently used one no request is running on to make room.
|
||||
vLLM profiles only; llama.cpp keeps loading every adapter at start, since
|
||||
llama-server can rescale an adapter it started with but not load another.
|
||||
- **Adapter affinity:** a request for an adapter goes to a replica that has
|
||||
it, or is loading it, while that replica is not saturated; otherwise to one
|
||||
with room for another adapter; otherwise where load sends it — which is how
|
||||
a busy adapter spreads to a second replica. Requests arriving during a load
|
||||
wait for it instead of loading the adapter again.
|
||||
- **Self-correcting:** each replica's `/v1/models` is read when the router
|
||||
first meets it and every 30 seconds, so adapters loaded before a restart or
|
||||
by another router are known; a 404 for an adapter the router thought loaded
|
||||
loads it again and retries. An adapter vLLM refuses (not found, rank above
|
||||
`--max-lora-rank`) fails the request with vLLM's reason, without trying it
|
||||
on every replica.
|
||||
- **Metrics:** `llmgw_adapter_affinity_total{model,result=hit|joined|loaded}`,
|
||||
`llmgw_adapter_loads_total{model,outcome}`,
|
||||
`llmgw_adapter_evictions_total{model,outcome}`.
|
||||
- The admin API and `ctl model adapters` read the file as GGUF only for a
|
||||
model with llama.cpp profiles.
|
||||
|
||||
### Federating clusters: another llmgw cluster as a provider
|
||||
|
||||
- `llmgw ctl federation add NAME --url URL --key-file FILE [--send-tags]`
|
||||
makes another llmgw gateway a peer. It is checked first (its `/ready`,
|
||||
timed, and its `/v1/models` with the key) and kept in the store (migration
|
||||
0029, `federation_peers`) with the models it offers.
|
||||
- A peer's models join the catalog as `NAME/MODEL`, always prefixed, and
|
||||
follow the peer's own list every `federation.interval` (10s). A model the
|
||||
peer drops goes, unless a model here still falls back to it: then it is
|
||||
kept withdrawn (in the catalog, sent nothing) until the fallback changes.
|
||||
The peer's aliases and its own peers' models are not taken.
|
||||
- A peer whose `/ready` fails, which refuses the key, or which does not answer
|
||||
is taken out of routing until it answers again. `/ready` now counts only a
|
||||
gateway's own endpoints, not its peers'.
|
||||
- `llmgw ctl model fallbacks MODEL [FALLBACK...]` (and `PUT
|
||||
/api/v1/models/{name}/fallbacks`) sets a runtime model's fallbacks, so
|
||||
overflow can go to a peer's model.
|
||||
- Requests to a peer carry `x-llmgw-hop` with the ids of the clusters they
|
||||
have passed through (each cluster's id is kept in the store). A request that
|
||||
comes back to a cluster is refused with 508 `federation_loop`, and a peer a
|
||||
request came from is not sent it.
|
||||
- The peer sees one key, this cluster's, and the request's `X-Request-Id`.
|
||||
With `--send-tags`, also `x-llmgw-tags: federated_from=<federation.name>,
|
||||
org=,team=,project=` (ids); off by default.
|
||||
- In-cluster residency and `no_store` keep requests off peers, by name and as
|
||||
fallbacks. Usage records the peer's model as served, and `peer:NAME/MODEL`
|
||||
as the replica.
|
||||
- `ctl federation list|remove|sync`, a Federation view in the console,
|
||||
`llmgw_federation_peer_up`, `_latency_seconds` and `_models` metrics, admin
|
||||
API `/api/v1/federation`, and a "Federating clusters" section in
|
||||
docs/install.md. New `federation:` block in server.yaml (`name`,
|
||||
`interval`).
|
||||
- A response header the gateway already set (X-Request-Id,
|
||||
x-llmgw-served-model) is no longer repeated from the upstream's.
|
||||
|
||||
### Facility-aware placement: racks, PDUs, holds and power caps
|
||||
|
||||
- **Where a node is**, from five labels: `llmgw.io/site`, `room`, `row`,
|
||||
`rack` and `pdu` (a list, for a dual-fed rack), in `agent.yaml` or set from
|
||||
the control plane with **`llmgw ctl label NODE key=value… [key-…]`**, which
|
||||
is kept in the store (migration 0031, `node_labels`), wins over the agent's
|
||||
labels, works before the node joins, and refuses a misspelt `llmgw.io/` key.
|
||||
A node with no location places as before.
|
||||
- **Replicas spread across racks and PDUs.** A model's next replica goes to a
|
||||
node sharing no rack or PDU with its others when there is one: an ordering
|
||||
above weights already on disk and bin packing, never a filter.
|
||||
- **`keep_within: rack`** (or row, room, site) on a profile keeps a
|
||||
multi-node replica's nodes in one such domain.
|
||||
- **Holds.** **`llmgw ctl facility hold rack:r12-07 --reason … [--drain]`**
|
||||
places nothing new in a rack, row, room, site or PDU; `--drain` also drains
|
||||
its nodes. **`llmgw ctl facility release`** undoes both. Kept across
|
||||
restarts (migration 0031, `facility_holds`).
|
||||
- **Power caps.** `facility.budgets` in `server.yaml` gives a domain's
|
||||
`cap_watts` and `other_watts`, with a `margin`; a replica's draw is the
|
||||
profile's `power_watts`, or its cards at the power limit they report
|
||||
(`gpu_watts` otherwise) and its cores at `cpu_core_watts`, with `node_watts`
|
||||
per node. Use is the larger of reserved and measured, node by node; a shard
|
||||
that would take a domain past its cap less the margin is refused, and a
|
||||
multi-node replica's shards are counted together. Unknown draw never blocks.
|
||||
- **Seen everywhere it matters.** `ctl explain-placement` names the held
|
||||
domain or the kilowatts, and keeps the rejections of a replica that was
|
||||
placed, so one in an unexpected rack says why. `ctl nodes` has LOCATION,
|
||||
*ready, held* and `--domain`. **`llmgw ctl facility`** lists every domain
|
||||
with nodes, use, limit, reserved, measured and holds. The console's Nodes
|
||||
view has WHERE; a node's menu has **Location…** and **Hold rack…/Release**.
|
||||
Admin API: `GET /api/v1/facility`, `POST /api/v1/facility/holds`,
|
||||
`DELETE /api/v1/facility/holds/{domain}`, `POST /api/v1/nodes/{id}/labels`.
|
||||
- Docs: `docs/facility-aware-placement.md` says what is built and where it
|
||||
departs from the design; `docs/install.md` and `docs/console.md`.
|
||||
|
||||
### SGLang measured, checked and benchmarked as itself
|
||||
|
||||
- **Fixed:** the router read SGLang replicas with vLLM's metric names, and
|
||||
SGLang was started without `--enable-metrics`, so it served no `/metrics`
|
||||
at all: every scrape failed as though the replica were unreachable, quietly,
|
||||
and requests were routed to it blind. SGLang is now started with
|
||||
`--enable-metrics` and read in its own names — `sglang:num_running_reqs`,
|
||||
`sglang:num_queue_reqs`, `sglang:token_usage` (the KV pool's fill), the
|
||||
prompt and generation token counters and `sglang:num_requests_total`, as
|
||||
0.5.21 publishes them.
|
||||
- **Fixed:** `llmgw ctl engine-check sglang` asked the interpreter for
|
||||
`--help` and checked SGLang's flags against Python's. It now asks
|
||||
`python -m sglang.launch_server --help`, in the environment SGLang was
|
||||
installed into (or `--bin`).
|
||||
- **Fixed:** SGLang was given `--tp`, which argparse accepts only as an
|
||||
abbreviation of `--tp-size`; it is given `--tp-size`.
|
||||
- **Fixed:** `llmgw ctl bench --metrics` read an engine's metrics with the
|
||||
key given for `--target` — a client's key when the target is the gateway,
|
||||
or none — so llama.cpp and TensorRT-LLM, which guard their metrics with the
|
||||
engine's key, refused every read, and the run reported a queue depth of
|
||||
zero and suggested no thresholds without saying why. The engine key is now
|
||||
asked of the admin API for the replica at `--metrics`' address (or given
|
||||
with the new `--metrics-key`); metrics that cannot be read — refused, or in
|
||||
another engine's names than `--engine` — fail the run before any load,
|
||||
saying why; and a step whose metrics went unread shows `-` and the reason
|
||||
rather than zeros.
|
||||
|
||||
### Reusing answers
|
||||
|
||||
- **A response cache, per project, off until asked for.** `llmgw keys cache
|
||||
--project P --ttl 1h` has the same request — same project, endpoint,
|
||||
model by its catalog name, and body with `stream`, `stream_options`,
|
||||
`user`, `metadata`, `store` and `service_tier` left out and its keys in
|
||||
any order — answered from the gateway's memory instead of the model, for
|
||||
the TTL. `--off` stops it; without either it says how it stands. The
|
||||
console has it as **Cache answers…** on a project.
|
||||
- **Only answers that come out the same are reused:** chat and completions
|
||||
asked at temperature 0 or with a seed, and embeddings, rerank and score.
|
||||
`--any` reuses sampled answers too. Only a whole 200 from the model asked
|
||||
for is kept — not an error, a fallback's or a canary's answer, one a
|
||||
guardrail changed or stopped, or one over `router.cache.max_entry_bytes`.
|
||||
- **Streams both ways:** a streamed answer is kept put back together into
|
||||
one completion (tool calls and reasoning included), and a kept answer is
|
||||
streamed as chunks — with the usage chunk if the client asked — to a
|
||||
client that streams. `/v1/messages` and `/v1/responses` get it too.
|
||||
- **Headers:** `x-llmgw-cache: hit|miss|bypass` on every answer of a
|
||||
project that reuses answers, `Age` on a hit. `Cache-Control: no-cache`
|
||||
or `no-store`, or `x-llmgw-cache: no`, asks the model anew.
|
||||
- **Policies still apply:** limits and the input guardrails run before the
|
||||
cache is looked in, the output policy judges a reused answer as it would
|
||||
a new one, and a request under `no_store` or continuing a stored
|
||||
conversation is never served from it nor kept in it. A project's answers
|
||||
are never looked up by another project's keys.
|
||||
- **A hit costs nothing:** recorded as a 200 with no tokens and no cost,
|
||||
marked `cache_hit` on the usage record (migration 0027), and shown by
|
||||
`llmgw ctl request`; it counts towards the requests-per-minute limit only.
|
||||
- **In memory only:** `router.cache.max_bytes` (128 MB) for all projects
|
||||
together in each gateway process, least recently used dropped first;
|
||||
nothing is written to the store. `llmgw_cache_requests_total{model,result}`,
|
||||
`llmgw_cache_bytes` and `llmgw_cache_entries`.
|
||||
|
||||
### Offline sites and Kubernetes
|
||||
|
||||
- **Offline bundles.** `llmgw bundle create` (on any machine with internet)
|
||||
collects what a cluster would otherwise download — llmgw's release for
|
||||
each `--arch` with its signed checksums, every llama.cpp build for those
|
||||
architectures (or the `--variant` ones) with the checksums GitHub
|
||||
publishes, the starter model and guardrails' judge, and any `--model
|
||||
name/version=hf:owner/repo/file` pinned to the registry's commit and its
|
||||
checksum — each checked as it arrives, into a directory or one `.tar`
|
||||
(`--tar`), with a manifest whose sha256 it prints to carry apart from the
|
||||
bundle. Run again into the same directory, it downloads only what is
|
||||
missing. `llmgw bundle show --verify` reads one back.
|
||||
- **`llmgw bundle import`** checks every file against the manifest and
|
||||
llmgw's release against the project's signing key, and only then puts them
|
||||
into the mirror — releases and engines under `_llmgw/`, models where the
|
||||
mirror keeps models, with their checksums — so a damaged bundle leaves the
|
||||
mirror as it was; a different file under a version already there is
|
||||
refused. On a control plane it also records the engines' checksums in
|
||||
`offline.checksums` (`/etc/llmgw/offline.sha256`); `llmgw bundle trust`
|
||||
does that alone, for a mirror on another machine.
|
||||
- **`offline.mirror` in server.yaml** makes the cluster reach nothing
|
||||
outside: nodes install llama.cpp from the mirror, each file held to the
|
||||
checksum the control plane sends them over the agent's authenticated
|
||||
connection — never one from the mirror — and `releases` defaults to the
|
||||
mirror's copy, so `node add`, `ctl upgrade` and agents upgrading fetch
|
||||
from it; no registry is asked about newer weights. A release may now come
|
||||
over plain HTTP when the build trusts a signing key, since the signature
|
||||
holds whatever carries it. vLLM and SGLang come from PyPI and are said to
|
||||
be unsupported on an offline node rather than attempted.
|
||||
- **`llmgw server init --bundle PATH --bundle-sha256 …`**, and the same two
|
||||
fields on the setup form: installs a control plane offline — the bundle
|
||||
into the mirror, the checksums trusted, `offline:` written to server.yaml,
|
||||
the starter model and judge served from the bundle or skipped when it does
|
||||
not carry them.
|
||||
- `docs/data.md` no longer says only weights and `ctl plan` reach outside:
|
||||
it lists everything that does, and what an offline cluster changes.
|
||||
- **A Helm chart for the control plane** (`deploy/helm/llmgw`): one replica
|
||||
in a StatefulSet, SQLite on a claim or an external PostgreSQL, the agent
|
||||
port's certificate and the admin token from Secrets, the API and metrics
|
||||
Service, a LoadBalancer for the agents' mutual TLS, an optional Ingress
|
||||
and ServiceMonitor, `config` laid into server.yaml, and the offline
|
||||
checksums from a ConfigMap; read-only root, non-root, ready on `/leader`.
|
||||
`deploy/container/Dockerfile` builds the image it runs. GPU nodes stay
|
||||
outside Kubernetes and join with `node add` (docs/kubernetes.md says why).
|
||||
|
||||
### The admin API described, and a Terraform provider
|
||||
|
||||
- **The admin API in OpenAPI 3.1.** Every endpoint under `/api/v1`, its path
|
||||
and query parameters, and the schema of each request and answer with the
|
||||
meaning of each field, in
|
||||
[docs/admin-api.openapi.json](docs/admin-api.openapi.json) and served by
|
||||
every control plane at `GET /api/v1/openapi.json` (with the token, like the
|
||||
rest). The bearer token, the `X-Llmgw-Actor` header and the error shape are
|
||||
in it. Generated by `go generate ./internal/docgen` from a route table in
|
||||
`internal/control/adminapi/routes.go` and the Go types the handlers use, with
|
||||
the fields' comments as descriptions; a test fails when an endpoint is
|
||||
served and not in the table, another when the committed document is stale.
|
||||
Checked with openapi-spec-validator and openapi-generator-cli's validate.
|
||||
- **[docs/admin-api.md](docs/admin-api.md)**: how to reach the API (loopback,
|
||||
an SSH tunnel, `admin_remote`), the token at `/var/lib/llmgw/admin-token`,
|
||||
what a request must carry — an address in `Host`, `application/json` on
|
||||
every change, even a `DELETE` — and some calls with `curl`.
|
||||
- **`GET /api/v1/models/{name}`**: one model's whole definition as it is in
|
||||
force, with the defaults the catalog filled in. The listing has only its
|
||||
state and its profiles' names.
|
||||
- **A Terraform provider**, in `terraform-provider-llmgw/`, a module of its
|
||||
own so the gateway does not carry its dependencies. `llmgw_model` (a model
|
||||
added at runtime: scaling, class, owner and adapters change in place, the
|
||||
rest replaces it), `llmgw_quota`, `llmgw_guard_attachment`, and the
|
||||
`llmgw_models` and `llmgw_nodes` data sources. Its client is checked
|
||||
against the OpenAPI document, endpoint by endpoint and field by field, so a
|
||||
change to the admin API that breaks it fails its tests; CI runs them.
|
||||
Built and installed by hand for now: see its
|
||||
[README](terraform-provider-llmgw/README.md).
|
||||
|
||||
### Tracing beyond the router
|
||||
|
||||
- **The control plane traces what it does to the fleet.** A reconcile pass
|
||||
that does something is a `reconcile` trace — passes with nothing to do are
|
||||
not traced at all — with what it did beneath it: `scale up` with `place`
|
||||
(the profile, engine, GPU class, pool, fabric and nodes chosen, or every
|
||||
candidate turned down and why, as `ctl explain-placement` would print it),
|
||||
`scale down`, `drain replica` and `stop replica` each with its reason,
|
||||
`evict`, `preempt` with its victims, `reap replica` with the error and
|
||||
when the model is tried again, `restart replica`, `restart refused`,
|
||||
`node unreachable` and `node lost`.
|
||||
- **A replica's start is one trace, down to the node.** `replica start`
|
||||
stays open from placement until the replica serves, fails or is stopped,
|
||||
with each shard's progress as an event and how long it took. The command
|
||||
to each node is a `send start` span whose context travels in the command
|
||||
(a new `trace` field on the agent protocol's `ControlMessage`), and the
|
||||
agent continues the same trace: `start shard`, with `fetch weights`
|
||||
(local, cached, downloaded, or downloaded by another shard; a `download`
|
||||
with its bytes and where a resume began, the source's credentials and
|
||||
query left out), `launch engine` (and `wait for rendezvous` on a worker
|
||||
of a multi-node replica), and `wait for engine` with how often the engine
|
||||
was asked and its last answer. "Why did qwen take four minutes to start"
|
||||
is that one trace.
|
||||
- **Stops, drains and adoptions on a node** are in the control plane's
|
||||
trace too: `stop shard` and `stop engine`, saying whether the engine had
|
||||
to be killed; `drain shard`; and `adopt` when a registering node reports
|
||||
engines already running, with how many nobody claimed. An engine install
|
||||
is an `install engine` trace on the node.
|
||||
- **Model jobs are traces.** `ctl model serve` and `ctl model update` are
|
||||
`serve model` and `update model`, with a span per step — registry,
|
||||
mirror, check, catalog, placement, smoke test, replicas — and from the
|
||||
placement step a link to the replica's own start.
|
||||
- **The agent has a `tracing` block** in `agent.yaml`, the same as
|
||||
`server.yaml`'s (`endpoint`, `sample_ratio`; `OTEL_EXPORTER_OTLP_ENDPOINT`
|
||||
when unset). Point both at one collector. A node follows the control
|
||||
plane's sampling for every start it is sent. Traces from a node carry its
|
||||
id as `service.instance.id`, and a control plane's its host name.
|
||||
- With no endpoint nothing changes: every span is the no-op one, and a
|
||||
command carries no trace context.
|
||||
|
||||
### Quality suites, and new weights held to one
|
||||
|
||||
- **`llmgw ctl eval MODEL --suite FILE|NAME`** asks a model a quality suite
|
||||
and scores its answers: per case, then the cases weighed into one score, 0
|
||||
to 1, against the suite's `threshold` (or `--min-score`); it exits non-zero
|
||||
below it. `--concurrency`, `--judge`, `--detach`, `--json`.
|
||||
- **Suites** are YAML or JSON lines: a prompt or a conversation, a weight,
|
||||
and one way to score it — `exact`, `contains`, `regex`, `number` within
|
||||
a `tolerance` (the last number in the answer), `json_schema` (the answer
|
||||
read as JSON, in a code fence or a sentence or not, held to a schema), or
|
||||
`judge`: a rubric another model on the cluster grades 0 to 1. A
|
||||
reasoning model's `<think>` is not part of its answer.
|
||||
- **Run on the control plane**, through the router as its own requests,
|
||||
as a replay is: past admission, quotas, accounting and the guardrails.
|
||||
`--suite` is a file sent whole, or a suite's name in `control.eval_dir`
|
||||
(`/etc/llmgw/eval`) or built in: `arithmetic` and `json-format`, in
|
||||
`deploy/eval/`, sized for small models. `--suites` lists them.
|
||||
- **Kept** in the store (migration 0028): every run with its model, the
|
||||
repository and revision of the weights that answered, the suite's name
|
||||
and hash, its score and each case's answer and reason.
|
||||
`llmgw ctl eval --history [MODEL]` lists them, `--run ID` shows one.
|
||||
- **Updates and promotions held to a suite.** `llmgw ctl model update` and
|
||||
`model promote` take `--eval SUITE --min-score N`, or a model carries one
|
||||
(`llmgw ctl model gate MODEL --eval SUITE`, `eval:` in its definition).
|
||||
A promotion asks the canary first and leaves it in place below the score;
|
||||
an update runs the new weights first as a canary given none of the
|
||||
model's requests, asks it, and promotes it or takes it out again, so the
|
||||
old weights serve until the new have passed. The job's `eval` step says
|
||||
the score; `--skip-eval` moves once without the model's suite.
|
||||
- **The console** has **Ask it a quality suite…** (the score counted in as it
|
||||
comes), **Its quality runs** and **Hold its updates to a quality suite…**
|
||||
on a model's menu.
|
||||
- **Fixed:** a change to the admin API with a body over 64 KiB reached its
|
||||
handler cut off at 64 KiB, by the audit log's reading of it.
|
||||
|
||||
### MIG instances as GPUs of their own class
|
||||
|
||||
- **A card in MIG mode is placed as its instances.** Discovery reports a card
|
||||
in MIG mode as its MIG instances instead of the whole card, each a device of
|
||||
its own with its UUID (`MIG-…`), its own memory, and a class named from the
|
||||
card's and the profile: two `3g.40gb` instances of an A100 80GB are two
|
||||
devices of class `a100-80g-mig-3g.40gb`. A profile names that class like
|
||||
any other, and placement puts a replica on a free instance of it. Both
|
||||
discovery paths do it: nvidia-smi (instances from `nvidia-smi -L`, their
|
||||
memory and ids from `nvidia-smi -q -x`) and NVML (`GetMigMode`,
|
||||
`GetMaxMigDeviceCount`, `GetMigDeviceHandleByIndex`). llmgw does not create
|
||||
instances; `docs/install.md` has a MIG section on making them.
|
||||
- **One instance a replica.** A process opens only one MIG device, and
|
||||
instances have no NVLink or peer-to-peer between them, so a profile on a
|
||||
MIG class asking for more than one GPU, tp or pp above 1, or more than one
|
||||
node is refused when the model is added, with that reason; placement
|
||||
refuses it again. `ctl model plan` and `ctl model serve` plan an instance
|
||||
for a model one holds and never several together.
|
||||
- **Engines are given the instance by UUID.** Placement numbers card 0's
|
||||
instance 2 as device 1002 (1000 + 100 × card + instance); the agent turns
|
||||
that into `CUDA_VISIBLE_DEVICES=MIG-<uuid>` for vLLM and llama.cpp, and
|
||||
leaves `GGML_VK_VISIBLE_DEVICES` unset (Vulkan cannot see MIG). Every view
|
||||
shows the device as `0/mig2`.
|
||||
- **Memory per instance, no made-up utilisation.** Each instance's memory,
|
||||
and the processes holding it, are its own — read per GPU and compute
|
||||
instance from nvidia-smi's report, so a foreign process on one instance
|
||||
keeps that instance out of placement and not its neighbours. Temperature,
|
||||
power and wear are the card's. No driver reports utilisation per instance,
|
||||
so none is published for one: the console says `n/a on MIG`, and
|
||||
`llmgw_gpu_utilization_percent` has no series for it rather than a zero.
|
||||
- **A card in MIG mode with nothing carved is kept out of placement**, with
|
||||
the reason in `ctl nodes`, since CUDA will not open the whole card while MIG
|
||||
is on.
|
||||
- **`llmgw doctor` reports MIG**: each card's mode and instances, and warns
|
||||
of a card in MIG mode with no instances, of GPU instances with no compute
|
||||
instance, and of a mode change waiting for a reset, with the `nvidia-smi`
|
||||
command for each.
|
||||
- `ctl nodes` counts a node's devices by class when it has MIG instances or
|
||||
more than one class (`a100-80g-mig-3g.40gb×2,a100-80g×1`); the console's
|
||||
GPU list shows instances under their card with their own memory and the
|
||||
card's heat and power, and a node's page lists its classes with counts.
|
||||
`ctl status` and the plan count each device under its own class, where a
|
||||
node's cards were all put under its first class before.
|
||||
- The agent protocol's `GPU` gains `mig` (parent card, its memory, profile,
|
||||
GPU and compute instance ids); the node API's GPUs gain `label`, `class`,
|
||||
`card`, `mig_profile` and memory, and nodes gain `gpus_by_class`.
|
||||
|
||||
### Engines and the mirror
|
||||
|
||||
- **TensorRT-LLM as an engine** (`engine: trtllm`), on nodes where you
|
||||
installed it: name its interpreter in the node's `agent.yaml`
|
||||
(`engines.trtllm.python`) and the node offers it while that interpreter
|
||||
has the `tensorrt_llm` package. llmgw does not install it. The agent starts
|
||||
`trtllm-serve serve` with the replica's host, port, `--tp_size`,
|
||||
`--pp_size` and served name, through a few lines of its own that make it
|
||||
demand the gateway's key on every path but `/health` (trtllm-serve has no
|
||||
key option), turn on the Prometheus endpoint and iteration statistics, and
|
||||
keep usage reports to NVIDIA off. The router reads it at
|
||||
`/prometheus/metrics` — `trtllm_num_requests_running`,
|
||||
`trtllm_num_requests_waiting`, `trtllm_kv_cache_utilization`, tokens and
|
||||
successes. Needs TensorRT-LLM 1.3 (rc13 or later) and an Ampere or newer
|
||||
GPU; one node per replica. Profiles may not give it an options file,
|
||||
`--trust_remote_code`, `--grpc`, `--num_serve_frontends` or the flags the
|
||||
agent sets; `--set PATH=VALUE` changes a setting instead. `llmgw ctl
|
||||
engine-check trtllm --bin <python>` checks an installed one. Written
|
||||
against TensorRT-LLM's documented command line, server and metrics and
|
||||
tested with stand-ins for them; not yet run on a datacenter GPU.
|
||||
- **`llmgw mirror import-ollama [NAME[:TAG]]`** puts a model you already
|
||||
have in Ollama into the mirror for llama.cpp: its GGUF, and a vision
|
||||
model's projector beside it, each checked against the sha256 Ollama named
|
||||
its file by. With no name it lists Ollama's models; it finds Ollama's
|
||||
directory itself (`OLLAMA_MODELS`, `~/.ollama/models`, Ollama's Linux
|
||||
service) or takes `--ollama-dir`. The version is the tag and the start of
|
||||
the digest, since a tag moves in Ollama. It prints a model definition to
|
||||
add, with Ollama's `num_ctx` as `--ctx-size`. The console's **Mirror**
|
||||
view does the same with **I**, for the mirror beside the control plane.
|
||||
- **`llmgw mirror import FILE... --model NAME`** copies files already on the
|
||||
mirror machine into it the way a download is kept: whole or not at all, the
|
||||
checksum beside it, a version never replaced, a `.gguf` checked to be one,
|
||||
and `--sha256` checked when given.
|
||||
|
||||
### The portal in Turkish
|
||||
|
||||
- **The web portal speaks English and Turkish** — the landing page, sign-up
|
||||
and sign-in, the account page and its editor setup, the claim page, chat,
|
||||
the about page, and every administrators' page (cluster, nodes, NVLink and
|
||||
fabrics, people, limits, usage, organizations, mirror, guardrails), and
|
||||
the docs portal around its documents, which stay English. Flash
|
||||
messages and form errors built by the server are translated too.
|
||||
- **A switcher at the foot of every page** (English · Türkçe) remembers the
|
||||
choice in a cookie; without one the browser's Accept-Language decides, and
|
||||
without that the new `landing.language` (`en` or `tr`, empty is English).
|
||||
An unknown code stops the server starting. `<html lang>` and
|
||||
Content-Language follow the page.
|
||||
- **Figures and dates in the page's language**: a Turkish page writes
|
||||
1.234,5, 04.10.2026 and "3 saat önce"; chart tooltips name the day in
|
||||
Turkish. Form values, CSS and SVG coordinates are unchanged.
|
||||
- **Ready for more languages**: the catalogue is JSON under
|
||||
`internal/web/locales/<code>/`, and a language is a directory. Tests refuse
|
||||
a key a page uses that some language lacks, a translation with different
|
||||
arguments from English, and any template text left in English — so a new
|
||||
page cannot quietly ship English-only.
|
||||
- Messages that come from the control plane and other packages (node
|
||||
warnings, engine errors, store refusals) are still shown as written, in
|
||||
English; the API, CLI and console are English.
|
||||
|
||||
### Documentation
|
||||
|
||||
- **A docs portal at /docs.** The manual the binary carries — the pages
|
||||
`llmgw docs` prints and the console's Manual shows, the configuration
|
||||
reference among them — rendered on the client port in the portal's own
|
||||
look: a sidebar of the documents in reading order, the open one's sections
|
||||
under it, a link on every heading, and links between documents kept inside
|
||||
the portal (links to files that are not in the binary, such as `deploy/`,
|
||||
go to the repository). No script on the page, so the Content-Security-Policy
|
||||
has nothing to allow. Public by default, like the landing page; set
|
||||
`landing.docs_sign_in: true` to send visitors to sign in first. Signed in,
|
||||
the page carries the usual menu, which now has a **Docs** link.
|
||||
- **A client developer's guide, `docs/clients.md`.** How to use llmgw from
|
||||
the official OpenAI and Anthropic SDKs — there is no llmgw SDK, and none is
|
||||
needed — in Python, TypeScript, Go and curl: the base URL and key,
|
||||
streaming, tools, embeddings, the Responses API, batches, the Anthropic SDK
|
||||
against `/v1/messages`, and what llmgw adds as headers (`x-llmgw-thread`,
|
||||
`x-session-id`, metadata and `x-llmgw-tags`, `x-llmgw-variant`,
|
||||
`/v1/memory`, `/mcp`), with the statuses a client meets. The portal's index
|
||||
leads with it, and the landing page and the account page link to it.
|
||||
- The console's Manual and the portal read one list of documents in one
|
||||
order (`llmgw.Manual`), so the two cannot drift.
|
||||
|
||||
### Administration
|
||||
|
||||
@@ -71,6 +548,129 @@ APIs change between minors without a deprecation period.
|
||||
- **Other ways in:** `GET /api/v1/usage/export` (CSV, or `format=json`)
|
||||
and **E** on the console's Usage view.
|
||||
|
||||
### Forgetting a person, and requests that stay in the cluster
|
||||
|
||||
- **`llmgw users forget`** erases a person for a request to be forgotten:
|
||||
their usage kept under a random pseudonym so totals stay true, their kept
|
||||
requests, personal files, batches and limits deleted, their name taken out
|
||||
of the audit log, the account removed.
|
||||
- **`llmgw keys residency --project P --in-cluster`**: no model served by an
|
||||
outside provider for the project's keys, asked for, as a fallback or as a
|
||||
canary.
|
||||
- Both are on the console's menus.
|
||||
|
||||
### Secrets in Vault
|
||||
|
||||
- **Secrets from Vault or the environment.** Every setting naming a secret's
|
||||
file also takes `env:VARIABLE` or `vault:mount/path#field` (HashiCorp
|
||||
Vault or OpenBao, KV v1 or v2; a token, AppRole, or VAULT_TOKEN).
|
||||
- **The store's own secrets sealed** under `secrets.master_key`: Vault's
|
||||
transit engine (`vault-transit:KEY`), or a 32-byte key read from a
|
||||
reference. A store, or a backup of it, then does not hold what engine keys
|
||||
are derived from. Values from before are sealed as they are next read.
|
||||
|
||||
### Scaling by the clock
|
||||
|
||||
- **`scaling.schedule`**: windows of the week with their own `min` and
|
||||
`max` — more replicas through working hours, an on-demand model kept
|
||||
loaded while people are at work — in `control.timezone`.
|
||||
- **`scaling.prewarm`** opens a window early, so its replicas have loaded
|
||||
when it starts.
|
||||
|
||||
### Token-level timing, and admission by SLO
|
||||
|
||||
- **Per-token metrics:** `llmgw_tpot_seconds`, `llmgw_inter_token_seconds`
|
||||
and `llmgw_output_tokens_per_second` by model and pool, and TPOT and
|
||||
tokens a second by tenant.
|
||||
- **A model's `slo` counts in admission:** past its `ttft_p99` or
|
||||
`tpot_p99` (the recent p99), it is treated as saturated, so the lower bands
|
||||
wait. `llmgw_model_slo_seconds` and the `llmgw-slo` alerts make the
|
||||
promise visible in Prometheus.
|
||||
|
||||
### Restoring a backup, and copies off the machine
|
||||
|
||||
- **`llmgw server restore ARCHIVE`** puts a backup back: checks it first
|
||||
(whole, opens with `--identity`, not newer than this llmgw, where the store
|
||||
goes), says so with `--dry-run`, then moves `/etc/llmgw` aside, restores it
|
||||
with modes and owners, restores the store (SQLite, or PostgreSQL with
|
||||
`pg_restore --clean`), and starts the server. A drill is in
|
||||
docs/install.md.
|
||||
- **`backup_copy_to`** copies each archive to a directory or over ssh as it
|
||||
is written, keeping as many there as here; refused without
|
||||
`backup_recipients`.
|
||||
- Archives now record each file's owner by name, so a restore on another
|
||||
machine gives the llmgw user its files back.
|
||||
|
||||
### Anthropic's Messages API
|
||||
|
||||
- **`/v1/messages`** (and `/v1/messages/count_tokens`) translated to chat
|
||||
completions and back, streamed or not: text, images, tools and their
|
||||
results, the system prompt, stop sequences. Claude Code and Anthropic's
|
||||
SDKs reach the models here; the key may come in `x-api-key`. Errors come
|
||||
back in Anthropic's shape.
|
||||
|
||||
### More of OpenAI's API
|
||||
|
||||
- **Responses:** `text.format` asks for structured output, `input_image`
|
||||
sends images, and `previous_response_id` continues a conversation the
|
||||
gateway keeps as a thread (for a project that keeps conversations).
|
||||
- **Passed through:** `/v1/rerank` and `/v1/score` for vLLM's rerankers, and
|
||||
`/v1/audio/transcriptions` and `/translations` as the multipart form came,
|
||||
for an engine serving Whisper.
|
||||
- **`/v1/moderations`** is answered by the guardrails' judge model.
|
||||
|
||||
### Requests kept, and replayed
|
||||
|
||||
- **A project can keep its requests and answers** (`llmgw keys requests
|
||||
--project P --retain-hours N [--sample 0.05]`, or **Keep requests…** in the
|
||||
console): what the model was sent, after redaction, and what the client
|
||||
got. Off until asked; never under `no_store`; pruned hourly.
|
||||
- **`llmgw ctl request ID --body`** shows one; **`--replay MODEL`** sends it
|
||||
to another model and shows both answers.
|
||||
|
||||
### Batches
|
||||
|
||||
- **OpenAI's Batch and Files APIs.** `POST /v1/files` (purpose batch),
|
||||
`POST /v1/batches`, and reading, listing, cancelling and deleting them, so
|
||||
OpenAI's clients send batches here unchanged.
|
||||
- **Serving:** each line goes as a request of the key that made the batch,
|
||||
in the lowest admission band, a few at a time; rate limits are waited
|
||||
out. Answers and failures are written to files kept 30 days.
|
||||
- **Accounting:** each line is an ordinary usage record tagged
|
||||
`batch=<id>`.
|
||||
- **Restarts:** answered lines are kept as they are answered, and any
|
||||
gateway on the store carries a batch on under a lease.
|
||||
- **Limits:** `router.batch` bounds the file, the lines and the
|
||||
concurrency. Refused to a project under a `no_store` policy.
|
||||
|
||||
### New weights tried on a share of the traffic first
|
||||
|
||||
- **Canaries.** `llmgw ctl model canary MODEL --percent 10` fetches the newer
|
||||
weights of a model's repository and runs them beside it as `MODEL-canary`,
|
||||
given that share of its requests.
|
||||
- **Routing:** a session stays on one side; `x-llmgw-variant` pins a
|
||||
request to `canary` or `stable` and says which served it. Clients cannot
|
||||
name the canary.
|
||||
- **Rolled back by itself** when, over 50 of its requests or more, its
|
||||
error rate is five points above the model's or its time to the first
|
||||
token half again as long; `canary_rolled_back` is sent to the
|
||||
notification webhooks.
|
||||
- **Then:** `--percent` changes its share, `llmgw ctl model promote`
|
||||
moves the model to it, `--abort` takes it out, and `llmgw ctl model
|
||||
canaries` compares the two sides. All of it is also on the console's
|
||||
model menu.
|
||||
|
||||
### Requests can be tagged
|
||||
|
||||
- **Tags and end users on every usage record.** OpenAI's `metadata` and the
|
||||
`x-llmgw-tags` header (`feature=search, env=prod`) tag a request; OpenAI's
|
||||
`user` field names the client's own end user. Both are kept with the
|
||||
request's usage and shown by `llmgw ctl request`. Tags are not sent to the
|
||||
engine. A malformed one is refused with 400.
|
||||
- **Counted by tag, for the tags named.** `router.tag_labels` lists the tags
|
||||
counted in `llmgw_tagged_requests_total` and `llmgw_tagged_tokens_total`,
|
||||
the first 100 values of each apart and the rest as `other`.
|
||||
|
||||
### A hardened install by default
|
||||
|
||||
- **`server init` and the setup screens write a hardened configuration.**
|
||||
|
||||
@@ -63,6 +63,19 @@ Since v0.11.0, not yet released (see [CHANGELOG.md](CHANGELOG.md),
|
||||
- **Notifications** — webhooks, signed or Slack-shaped, for a model parked,
|
||||
a node lost, a budget spent and new weights published (`notify.webhooks`,
|
||||
`ctl notify test`), and Alertmanager receiver templates.
|
||||
- **Traffic and models** — request tags, canaries of new weights with
|
||||
automatic rollback, quality suites gating updates, a response cache,
|
||||
kept and replayed requests, batches, Anthropic's Messages API, more of
|
||||
OpenAI's (structured output, images, rerank, audio, moderations),
|
||||
scaling by the clock, SLO-aware admission, TensorRT-LLM, MIG, models
|
||||
imported from Ollama, routing by what each vLLM replica's cache holds,
|
||||
LoRA adapters loaded on demand, other llmgw clusters as providers, and
|
||||
placement that knows racks, PDUs and power caps.
|
||||
- **Operations** — `server restore` and off-machine backup copies, secrets
|
||||
in Vault, forgetting a person and keeping a project's requests in the
|
||||
cluster, offline installs from a bundle, a Helm chart, tracing from the
|
||||
control plane to the engines, the admin API in OpenAPI with a Terraform
|
||||
provider, and the portal in English and Turkish with its docs at /docs.
|
||||
|
||||
Every one of these is in the console as well as on the command line:
|
||||
[docs/console.md](docs/console.md).
|
||||
@@ -95,6 +108,8 @@ Every page is also in the binary: `llmgw docs`, or **Manual** in the console.
|
||||
the firewall, upgrades, backups
|
||||
- [docs/node-onboarding.md](docs/node-onboarding.md) — adding nodes to a
|
||||
cluster that exists
|
||||
- [docs/kubernetes.md](docs/kubernetes.md) — the control plane on
|
||||
Kubernetes with the Helm chart, and why GPU nodes stay outside it
|
||||
- [docs/fabrics.md](docs/fabrics.md) — InfiniBand fabrics and NVLink: what
|
||||
llmgw needs of them, checking a node with `llmgw doctor`, and what to look at
|
||||
when a replica spanning nodes will not run
|
||||
@@ -105,6 +120,8 @@ Every page is also in the binary: `llmgw docs`, or **Manual** in the console.
|
||||
every view, and the command each of its actions runs
|
||||
- [docs/onboarding.md](docs/onboarding.md) — accounts, keys, limits, staff
|
||||
roles and single sign-on
|
||||
- [docs/clients.md](docs/clients.md) — using the gateway from code with the
|
||||
official OpenAI and Anthropic SDKs, and llmgw's extensions
|
||||
- [docs/guardrails.md](docs/guardrails.md) — checking requests and answers:
|
||||
policies, detectors, a judge model, and where each applies
|
||||
- [docs/choosing-models.md](docs/choosing-models.md) — which models to run,
|
||||
@@ -117,6 +134,9 @@ Every page is also in the binary: `llmgw docs`, or **Manual** in the console.
|
||||
does not exist or miss one that does
|
||||
- [docs/data.md](docs/data.md) — what llmgw stores, what it does not, and
|
||||
what leaves the machine; written for a security review
|
||||
- [docs/admin-api.md](docs/admin-api.md) and its OpenAPI document — the
|
||||
admin API, for scripts; [terraform-provider-llmgw/](terraform-provider-llmgw/)
|
||||
manages models, quotas and guardrails with Terraform or OpenTofu
|
||||
- [deploy/](deploy/) — [a mirror](deploy/mirror/) on its own machine,
|
||||
[Caddy and nginx](deploy/proxy/) in front of the client port, [two control
|
||||
planes](deploy/ha/) behind a balancer, and [Prometheus, Alertmanager and
|
||||
|
||||
+541
-229
File diff suppressed because it is too large.
Load diff
@@ -27,9 +27,36 @@ message AgentMessage {
|
||||
FabricScanReply fabric_scan = 5;
|
||||
FabricTestReply fabric_test = 6;
|
||||
UpgradeReply upgrade = 7;
|
||||
KVEvents kv_events = 8;
|
||||
}
|
||||
}
|
||||
|
||||
// KVEvents is a change to what one vLLM replica's prefix cache holds, read
|
||||
// by the agent from the engine's KV cache events and sent on for the router's
|
||||
// precise index (plan §7.5 tier 2).
|
||||
//
|
||||
// A net effect since the last one, not the events themselves: a block stored
|
||||
// and evicted between two sends is not worth the bytes. On every new stream
|
||||
// the agent first sends each replica in full, with clear_first set, because a
|
||||
// control plane that has just started or taken over knows nothing.
|
||||
message KVEvents {
|
||||
string replica_id = 1;
|
||||
// block_size is how many tokens make one of the replica's blocks.
|
||||
int32 block_size = 2;
|
||||
// clear_first says to forget what was known of the replica before applying the
|
||||
// rest: its cache was cleared, its engine restarted, events were lost, or
|
||||
// this is the first piece of a full copy.
|
||||
bool clear_first = 3;
|
||||
// stored and removed are block hashes as vLLM publishes them: the low 64
|
||||
// bits of the sha256_cbor digest.
|
||||
repeated fixed64 stored = 4;
|
||||
repeated fixed64 removed = 5;
|
||||
// problem, when set, is why the replica's events cannot be used — most
|
||||
// likely an engine hashing another way than llmgw configured. Its index is
|
||||
// empty while it stands.
|
||||
string problem = 6;
|
||||
}
|
||||
|
||||
// ControlMessage is anything the control plane tells a node.
|
||||
message ControlMessage {
|
||||
oneof msg {
|
||||
@@ -45,6 +72,12 @@ message ControlMessage {
|
||||
UpgradeAgent upgrade = 10;
|
||||
ControlPlanes control_planes = 11;
|
||||
}
|
||||
// trace is the W3C trace context (traceparent, and tracestate when there
|
||||
// is one) of the control plane's span that sent this command, so what the
|
||||
// agent does for it — fetching weights, launching the engine, waiting for
|
||||
// it to answer — lands in the same trace. Empty when the control plane is
|
||||
// not tracing, and ignored by an agent that is not.
|
||||
map<string, string> trace = 12;
|
||||
}
|
||||
|
||||
// ControlPlanes is every control plane an agent may dial, sent by the leader
|
||||
@@ -252,6 +285,25 @@ message GPU {
|
||||
string cluster_uuid = 19;
|
||||
string clique_id = 20;
|
||||
string fabric_bandwidth = 21;
|
||||
// mig is set when this is a MIG instance rather than a whole card. index
|
||||
// is then 1000 + 100 × card + device, uuid the instance's (MIG-…), and
|
||||
// memory the instance's share; utilization_percent stays zero, because no
|
||||
// driver measures it per instance.
|
||||
MIGDevice mig = 22;
|
||||
}
|
||||
|
||||
// MIGDevice is which card a MIG instance is carved from, and how.
|
||||
message MIGDevice {
|
||||
int32 parent_index = 1;
|
||||
string parent_uuid = 2;
|
||||
// parent_memory_total_mb is the whole card's: the class is named from it.
|
||||
int32 parent_memory_total_mb = 3;
|
||||
// device is the instance's number on its card, as nvidia-smi -L lists it.
|
||||
int32 device = 4;
|
||||
// profile is NVIDIA's name for the slice, like 3g.40gb.
|
||||
string profile = 5;
|
||||
int32 gpu_instance = 6;
|
||||
int32 compute_instance = 7;
|
||||
}
|
||||
|
||||
message FabricAttachment {
|
||||
@@ -515,6 +567,15 @@ message EngineWant {
|
||||
// variant is the build to install, when one is chosen for the node rather
|
||||
// than left to its hardware: "cu13", "cu129". Empty is the agent's choice.
|
||||
string variant = 3;
|
||||
// offline_base, on a cluster with no way to the internet, is where this
|
||||
// engine version's files are on its mirror:
|
||||
// http://mirror:8081/_llmgw/engines/llamacpp/b10991. Set, the node never
|
||||
// asks the engine's publisher.
|
||||
string offline_base = 4;
|
||||
// offline_sha256 is each of those files' checksum by name, from the
|
||||
// bundle the control plane trusts — not from the mirror, which serves
|
||||
// every node over plain HTTP.
|
||||
map<string, string> offline_sha256 = 5;
|
||||
}
|
||||
|
||||
// ProvisionStatus is where one engine's installation stands on a node.
|
||||
@@ -625,6 +686,9 @@ message EngineProfile {
|
||||
// adapters are LoRA adapters loaded beside the model, in order: the index
|
||||
// is the id a request applies one by.
|
||||
repeated LoraAdapter adapters = 12;
|
||||
// kv_events has a vLLM engine publish its KV cache events to the agent, for
|
||||
// the router's precise index.
|
||||
bool kv_events = 13;
|
||||
}
|
||||
|
||||
// RemoveWeights deletes cached model files a node no longer needs.
|
||||
|
||||
@@ -5,6 +5,8 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
// Time zones for scaling schedules, on a machine without the tz database.
|
||||
_ "time/tzdata"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/cli"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# The llmgw control plane as a container image, for deploy/helm/llmgw.
|
||||
#
|
||||
# The project publishes binaries, not an image, so this is built where the
|
||||
# image is to live:
|
||||
#
|
||||
# docker build -f deploy/container/Dockerfile --build-arg VERSION=v0.11.1 \
|
||||
# -t registry.internal/llmgw:v0.11.1 .
|
||||
# docker push registry.internal/llmgw:v0.11.1
|
||||
#
|
||||
# The binary is static (CGO_ENABLED=0, as every release is), so the image is
|
||||
# that one file on a base with nothing else in it: no shell, no package
|
||||
# manager. `kubectl exec ... -- llmgw ctl status` still works, because it
|
||||
# runs the binary rather than a shell.
|
||||
#
|
||||
# Only the control plane runs from it. An agent installs engines on its
|
||||
# machine, manages its GPUs and supervises processes there as root, which is
|
||||
# what a container is built to prevent: docs/kubernetes.md.
|
||||
|
||||
FROM golang:1.26 AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
ARG VERSION=dev
|
||||
RUN CGO_ENABLED=0 go build -trimpath \
|
||||
-ldflags "-s -w -X gitea.mynodes.xyz/ilker/llmgw/internal/version.Version=${VERSION}" \
|
||||
-o /out/llmgw ./cmd/llmgw && \
|
||||
mkdir -p /out/state
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=build /out/llmgw /usr/local/bin/llmgw
|
||||
# The chart mounts server.yaml, the certificates and the token under
|
||||
# /etc/llmgw, and the SQLite store, when it is one, under /var/lib/llmgw —
|
||||
# owned by the user the server runs as, so a volume Docker fills from the
|
||||
# image is writable without Kubernetes' fsGroup.
|
||||
COPY --from=build --chown=65532:65532 /out/state /var/lib/llmgw
|
||||
USER 65532:65532
|
||||
EXPOSE 8080 7443 9091
|
||||
ENTRYPOINT ["/usr/local/bin/llmgw"]
|
||||
CMD ["server", "--config", "/etc/llmgw/server.yaml"]
|
||||
@@ -0,0 +1,58 @@
|
||||
# Arithmetic a small instruction model gets right: sums, products and a
|
||||
# little reading, each answer scored by the last number in it. A quantisation
|
||||
# that has gone wrong, or a chat template that no longer matches the
|
||||
# weights, shows up here as a falling score long before anyone notices it in
|
||||
# conversation.
|
||||
#
|
||||
# llmgw ctl eval MODEL --suite arithmetic
|
||||
# llmgw ctl model update MODEL --eval arithmetic --min-score 0.8
|
||||
#
|
||||
# Copy it into control.eval_dir (/etc/llmgw/eval) to change it; a suite
|
||||
# there of the same name replaces this one.
|
||||
name: arithmetic
|
||||
description: Sums, products and word problems, each scored by the number in its answer.
|
||||
threshold: 0.7
|
||||
system: You are a careful calculator. Answer with the number only, without words or units.
|
||||
max_tokens: 64
|
||||
cases:
|
||||
- id: add-small
|
||||
prompt: What is 17 + 25?
|
||||
number: 42
|
||||
- id: add-carry
|
||||
prompt: What is 389 + 476?
|
||||
number: 865
|
||||
- id: subtract
|
||||
prompt: What is 1000 - 357?
|
||||
number: 643
|
||||
- id: subtract-negative
|
||||
prompt: What is 12 - 30?
|
||||
number: -18
|
||||
- id: multiply
|
||||
prompt: What is 12 * 12?
|
||||
number: 144
|
||||
- id: multiply-larger
|
||||
prompt: What is 23 * 17?
|
||||
number: 391
|
||||
weight: 2
|
||||
- id: divide
|
||||
prompt: What is 144 / 6?
|
||||
number: 24
|
||||
- id: decimal
|
||||
prompt: What is 2.5 * 4?
|
||||
number: 10
|
||||
- id: percent
|
||||
prompt: What is 15% of 200?
|
||||
number: 30
|
||||
- id: words-apples
|
||||
prompt: Ana has 7 apples and buys 5 more, then gives 3 away. How many apples does she have?
|
||||
number: 9
|
||||
weight: 2
|
||||
- id: words-time
|
||||
prompt: A train leaves at 14:00 and the trip takes 150 minutes. How many hours does the trip take?
|
||||
number: 2.5
|
||||
tolerance: 0.01
|
||||
weight: 2
|
||||
- id: order-of-operations
|
||||
prompt: What is 2 + 3 * 4?
|
||||
number: 14
|
||||
weight: 2
|
||||
@@ -0,0 +1,94 @@
|
||||
# Following a format: asked for JSON of a given shape, does the model give
|
||||
# it — the thing an application parsing its answers depends on, and the
|
||||
# first to go when a chat template drifts. Each answer is read as JSON (a
|
||||
# code fence or a sentence around it is forgiven) and held to a schema.
|
||||
#
|
||||
# llmgw ctl eval MODEL --suite json-format
|
||||
#
|
||||
# Copy it into control.eval_dir (/etc/llmgw/eval) to change it; a suite
|
||||
# there of the same name replaces this one.
|
||||
name: json-format
|
||||
description: Answers asked for as JSON of a given shape, held to a schema.
|
||||
threshold: 0.7
|
||||
system: You answer with a single JSON value and nothing else.
|
||||
max_tokens: 200
|
||||
cases:
|
||||
- id: person
|
||||
prompt: >-
|
||||
Give a JSON object for a person named Ada Lovelace, born in 1815, with the
|
||||
keys "name" (a string) and "born" (a number).
|
||||
json_schema:
|
||||
type: object
|
||||
required: [name, born]
|
||||
properties:
|
||||
name: {type: string, pattern: "Ada"}
|
||||
born: {type: integer, minimum: 1815, maximum: 1815}
|
||||
|
||||
- id: list-of-colours
|
||||
prompt: Give a JSON array of exactly three colour names, as strings.
|
||||
json_schema:
|
||||
type: array
|
||||
minItems: 3
|
||||
maxItems: 3
|
||||
items: {type: string, minLength: 1}
|
||||
|
||||
- id: boolean-answer
|
||||
prompt: >-
|
||||
Is water wet? Answer as a JSON object with one key, "answer", whose
|
||||
value is true or false.
|
||||
json_schema:
|
||||
type: object
|
||||
required: [answer]
|
||||
properties:
|
||||
answer: {type: boolean}
|
||||
|
||||
- id: nested
|
||||
prompt: >-
|
||||
Give a JSON object describing a book: "title" (a string), "author" (an
|
||||
object with "first" and "last", both strings) and "pages" (a whole number
|
||||
above zero). Use any book.
|
||||
json_schema:
|
||||
type: object
|
||||
required: [title, author, pages]
|
||||
properties:
|
||||
title: {type: string, minLength: 1}
|
||||
author:
|
||||
type: object
|
||||
required: [first, last]
|
||||
properties:
|
||||
first: {type: string}
|
||||
last: {type: string}
|
||||
pages: {type: integer, exclusiveMinimum: 0}
|
||||
weight: 2
|
||||
|
||||
- id: enum-choice
|
||||
prompt: >-
|
||||
Classify the sentence "I love this product!" as positive, negative or
|
||||
neutral. Answer as a JSON object {"sentiment": "..."} using one of those
|
||||
three words in lower case.
|
||||
json_schema:
|
||||
type: object
|
||||
required: [sentiment]
|
||||
properties:
|
||||
sentiment: {enum: [positive]}
|
||||
weight: 2
|
||||
|
||||
- id: numbers
|
||||
prompt: 'Give a JSON object {"sum": N} where N is the sum of 4, 5 and 6.'
|
||||
json_schema:
|
||||
type: object
|
||||
required: [sum]
|
||||
properties:
|
||||
sum: {const: 15}
|
||||
|
||||
- id: no-extra-keys
|
||||
prompt: >-
|
||||
Give a JSON object with exactly two keys, "city" and "country", for
|
||||
Paris. No other keys.
|
||||
json_schema:
|
||||
type: object
|
||||
required: [city, country]
|
||||
additionalProperties: false
|
||||
properties:
|
||||
city: {type: string}
|
||||
country: {type: string}
|
||||
@@ -159,6 +159,12 @@ router:
|
||||
# back to a client that did not ask for it.
|
||||
inject_usage: true
|
||||
max_body_bytes: 33554432
|
||||
# Memory for the answers of projects that reuse them (llmgw keys cache),
|
||||
# all together; the least recently used go first. Nothing is reused until a
|
||||
# project turns it on.
|
||||
# cache:
|
||||
# max_bytes: 134217728 # 128 MB
|
||||
# max_entry_bytes: 1048576 # 1 MB
|
||||
|
||||
timeouts:
|
||||
dial: 5s
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
apiVersion: v2
|
||||
name: llmgw
|
||||
description: >-
|
||||
The llmgw control plane — the OpenAI-compatible gateway, the router and the
|
||||
scheduler that places models on GPU and CPU nodes. The nodes themselves run
|
||||
outside Kubernetes; see docs/kubernetes.md.
|
||||
type: application
|
||||
# The chart's own version; appVersion is the llmgw release the image holds.
|
||||
version: 0.1.0
|
||||
appVersion: "v0.11.1"
|
||||
home: https://gitea.mynodes.xyz/ilker/llmgw
|
||||
sources:
|
||||
- https://gitea.mynodes.xyz/ilker/llmgw
|
||||
keywords:
|
||||
- llm
|
||||
- gateway
|
||||
- inference
|
||||
@@ -0,0 +1,27 @@
|
||||
The llmgw control plane is starting as {{ include "llmgw.fullname" . }}.
|
||||
|
||||
The admin API listens on the pod's loopback only. To reach it from here:
|
||||
|
||||
kubectl -n {{ .Release.Namespace }} port-forward statefulset/{{ include "llmgw.fullname" . }} 9090:9090 &
|
||||
export LLMGW_ADMIN_TOKEN=$(kubectl -n {{ .Release.Namespace }} get secret {{ include "llmgw.adminSecret" . }} \
|
||||
-o jsonpath='{.data.{{ if .Values.adminToken.existingSecret }}{{ .Values.adminToken.secretKey }}{{ else }}admin-token{{ end }}}' | base64 -d)
|
||||
llmgw ctl status
|
||||
|
||||
The first administrator:
|
||||
|
||||
kubectl -n {{ .Release.Namespace }} exec -it statefulset/{{ include "llmgw.fullname" . }} -- \
|
||||
llmgw users create you@example.com --password '<a password>'
|
||||
kubectl -n {{ .Release.Namespace }} exec -it statefulset/{{ include "llmgw.fullname" . }} -- \
|
||||
llmgw users role you@example.com admin
|
||||
|
||||
Agents connect to the {{ include "llmgw.fullname" . }}-agents Service on port {{ .Values.agentService.port }}:
|
||||
|
||||
kubectl -n {{ .Release.Namespace }} get service {{ include "llmgw.fullname" . }}-agents
|
||||
|
||||
Its address must be in the certificate in {{ .Values.agentTLS.existingSecret }}. Nodes join from
|
||||
the machine holding llmgw's authority:
|
||||
|
||||
sudo llmgw node add ubuntu@gpu01 --server https://<that address>:{{ .Values.agentService.port }} \
|
||||
--pki ./pki --admin 127.0.0.1:9090
|
||||
|
||||
docs/kubernetes.md has the rest, and why the nodes stay outside Kubernetes.
|
||||
@@ -0,0 +1,74 @@
|
||||
{{/* The release's name for everything the chart makes. */}}
|
||||
{{- define "llmgw.fullname" -}}
|
||||
{{- if contains .Chart.Name .Release.Name -}}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "llmgw.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ .Chart.Name }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "llmgw.labels" -}}
|
||||
{{ include "llmgw.selectorLabels" . }}
|
||||
app.kubernetes.io/version: {{ .Values.image.tag | default .Chart.AppVersion | quote }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "llmgw.image" -}}
|
||||
{{- if not .Values.image.repository -}}
|
||||
{{- fail "image.repository: the image built from deploy/container/Dockerfile, pushed where the cluster can pull it (the project publishes binaries, not an image)" -}}
|
||||
{{- end -}}
|
||||
{{- printf "%s:%s" .Values.image.repository (.Values.image.tag | default .Chart.AppVersion) -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "llmgw.adminSecret" -}}
|
||||
{{- .Values.adminToken.existingSecret | default (printf "%s-admin" (include "llmgw.fullname" .)) -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
server.yaml: what the chart decides — listeners, where the certificates,
|
||||
the token and the store are mounted — laid over .Values.config. The chart's
|
||||
keys win, because each names a port or a path the pod is built around.
|
||||
*/}}
|
||||
{{- define "llmgw.serverConfig" -}}
|
||||
{{- $store := "/var/lib/llmgw/llmgw.db" -}}
|
||||
{{- if eq .Values.store.type "postgres" -}}
|
||||
{{- $store = "@/etc/llmgw/store/dsn" -}}
|
||||
{{- end -}}
|
||||
{{- $base := dict
|
||||
"listen" ":8080"
|
||||
"admin_listen" "127.0.0.1:9090"
|
||||
"metrics_listen" ":9091"
|
||||
"agent_listen" ":7443"
|
||||
"admin_token_file" "/etc/llmgw/admin/admin-token"
|
||||
"agent_tls" (dict "ca" "/etc/llmgw/tls/ca.pem" "cert" "/etc/llmgw/tls/server.pem" "key" "/etc/llmgw/tls/server-key.pem")
|
||||
"auth" (dict "store" $store)
|
||||
-}}
|
||||
{{- if .Values.offlineChecksums.configMap -}}
|
||||
{{- $_ := set $base "offline" (dict "checksums" "/etc/llmgw/offline/offline.sha256") -}}
|
||||
{{- end -}}
|
||||
{{- $cfg := mustMergeOverwrite (deepCopy (.Values.config | default dict)) $base -}}
|
||||
# Made by the llmgw Helm chart from its values. Every key: docs/reference.md
|
||||
{{ toYaml $cfg }}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Refuses values that would make a pod that cannot work. */}}
|
||||
{{- define "llmgw.validate" -}}
|
||||
{{- if not (has .Values.store.type (list "sqlite" "postgres")) -}}
|
||||
{{- fail (printf "store.type %q: sqlite or postgres" .Values.store.type) -}}
|
||||
{{- end -}}
|
||||
{{- if ne (int .Values.replicas) 1 -}}
|
||||
{{- fail "replicas: this chart runs one control plane; values.yaml says why" -}}
|
||||
{{- end -}}
|
||||
{{- if and (eq .Values.store.type "postgres") (not .Values.store.postgres.existingSecret) -}}
|
||||
{{- fail "store.postgres.existingSecret: a Secret holding the PostgreSQL address" -}}
|
||||
{{- end -}}
|
||||
{{- if not .Values.agentTLS.existingSecret -}}
|
||||
{{- fail "agentTLS.existingSecret: a Secret with ca.pem, server.pem and server-key.pem from llmgw's authority (see values.yaml)" -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,10 @@
|
||||
{{- include "llmgw.validate" . -}}
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
data:
|
||||
server.yaml: |
|
||||
{{- include "llmgw.serverConfig" . | nindent 4 }}
|
||||
@@ -0,0 +1,37 @@
|
||||
{{- if .Values.ingress.enabled }}
|
||||
# The OpenAI-compatible API, the portal and the chat page on port 8080. Never
|
||||
# the agent port: its mutual TLS cannot pass through an HTTP proxy.
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
{{- with .Values.ingress.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.ingress.className }}
|
||||
ingressClassName: {{ . }}
|
||||
{{- end }}
|
||||
{{- with .Values.ingress.tls }}
|
||||
tls:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
rules:
|
||||
{{- range .Values.ingress.hosts }}
|
||||
- host: {{ .host | quote }}
|
||||
http:
|
||||
paths:
|
||||
{{- range .paths }}
|
||||
- path: {{ .path }}
|
||||
pathType: {{ .pathType }}
|
||||
backend:
|
||||
service:
|
||||
name: {{ include "llmgw.fullname" $ }}
|
||||
port:
|
||||
name: api
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,19 @@
|
||||
{{- if not .Values.adminToken.existingSecret }}
|
||||
{{- $name := include "llmgw.adminSecret" . }}
|
||||
{{- $token := randAlphaNum 64 }}
|
||||
{{- /* Kept across upgrades: a new token on every upgrade would lock out every console holding the old one. */}}
|
||||
{{- with lookup "v1" "Secret" .Release.Namespace $name }}
|
||||
{{- $token = index .data "admin-token" | b64dec }}
|
||||
{{- end }}
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: {{ $name }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
annotations:
|
||||
helm.sh/resource-policy: keep
|
||||
type: Opaque
|
||||
data:
|
||||
admin-token: {{ $token | b64enc | quote }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,21 @@
|
||||
{{- if .Values.serviceMonitor.enabled }}
|
||||
# For the Prometheus Operator: the metrics port, which serves metrics and
|
||||
# nothing else. deploy/monitoring holds the rules and dashboards that read them.
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: ServiceMonitor
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
{{- with .Values.serviceMonitor.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 6 }}
|
||||
endpoints:
|
||||
- port: metrics
|
||||
path: /metrics
|
||||
interval: {{ .Values.serviceMonitor.interval }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,70 @@
|
||||
# The API and the metrics, for the cluster and an Ingress.
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
{{- with .Values.service.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
type: {{ .Values.service.type }}
|
||||
selector:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 4 }}
|
||||
ports:
|
||||
- name: api
|
||||
port: {{ .Values.service.port }}
|
||||
targetPort: api
|
||||
- name: metrics
|
||||
port: {{ .Values.service.metricsPort }}
|
||||
targetPort: metrics
|
||||
---
|
||||
# Where agents on the nodes connect. Mutual TLS ends in the pod: whatever is
|
||||
# in between must pass TCP through untouched.
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}-agents
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
{{- with .Values.agentService.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
type: {{ .Values.agentService.type }}
|
||||
{{- if and (eq .Values.agentService.type "LoadBalancer") .Values.agentService.loadBalancerIP }}
|
||||
loadBalancerIP: {{ .Values.agentService.loadBalancerIP }}
|
||||
{{- end }}
|
||||
{{- with .Values.agentService.loadBalancerSourceRanges }}
|
||||
loadBalancerSourceRanges:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
{{- if has .Values.agentService.type (list "LoadBalancer" "NodePort") }}
|
||||
externalTrafficPolicy: {{ .Values.agentService.externalTrafficPolicy }}
|
||||
{{- end }}
|
||||
selector:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 4 }}
|
||||
ports:
|
||||
- name: agents
|
||||
port: {{ .Values.agentService.port }}
|
||||
targetPort: agents
|
||||
---
|
||||
# The StatefulSet's own, giving each pod a stable name.
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}-headless
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
spec:
|
||||
clusterIP: None
|
||||
publishNotReadyAddresses: true
|
||||
selector:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 4 }}
|
||||
ports:
|
||||
- name: api
|
||||
port: 8080
|
||||
targetPort: api
|
||||
@@ -0,0 +1,181 @@
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
labels:
|
||||
{{- include "llmgw.labels" . | nindent 4 }}
|
||||
spec:
|
||||
# One control plane: Kubernetes replaces it within seconds when it goes,
|
||||
# and the agents reconnect on their own. See replicas in values.yaml.
|
||||
replicas: 1
|
||||
serviceName: {{ include "llmgw.fullname" . }}-headless
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 8 }}
|
||||
{{- with .Values.podLabels }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
annotations:
|
||||
# server.yaml is read at start: a changed one restarts the pod.
|
||||
checksum/config: {{ include "llmgw.serverConfig" . | sha256sum }}
|
||||
{{- with .Values.podAnnotations }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
# Agents reconnect within seconds of a control plane going; a long
|
||||
# grace period only delays the one that replaces it.
|
||||
terminationGracePeriodSeconds: 30
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65532
|
||||
runAsGroup: 65532
|
||||
fsGroup: 65532
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: llmgw
|
||||
image: {{ include "llmgw.image" . }}
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
args: ["server", "--config", "/etc/llmgw/server.yaml"]
|
||||
env:
|
||||
# For `kubectl exec ... -- llmgw ctl`, which reads the token
|
||||
# from here; the server reads admin_token_file.
|
||||
- name: LLMGW_ADMIN_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "llmgw.adminSecret" . }}
|
||||
key: {{ if .Values.adminToken.existingSecret }}{{ .Values.adminToken.secretKey }}{{ else }}admin-token{{ end }}
|
||||
ports:
|
||||
- name: api
|
||||
containerPort: 8080
|
||||
- name: agents
|
||||
containerPort: 7443
|
||||
- name: metrics
|
||||
containerPort: 9091
|
||||
# Up is /health. Ready is /leader: a control plane holds the
|
||||
# agents' connections and places models only once it leads — on
|
||||
# PostgreSQL, once the lease of the one it replaced has run out. A
|
||||
# cluster with no node yet is still ready: /ready would wait for a
|
||||
# replica, and nodes could then never connect.
|
||||
startupProbe:
|
||||
httpGet: {path: /health, port: api}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 60
|
||||
livenessProbe:
|
||||
httpGet: {path: /health, port: api}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 6
|
||||
readinessProbe:
|
||||
httpGet: {path: /leader, port: api}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
resources:
|
||||
{{- toYaml .Values.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /etc/llmgw/server.yaml
|
||||
subPath: server.yaml
|
||||
readOnly: true
|
||||
- name: agent-tls
|
||||
mountPath: /etc/llmgw/tls
|
||||
readOnly: true
|
||||
- name: admin-token
|
||||
mountPath: /etc/llmgw/admin
|
||||
readOnly: true
|
||||
{{- if eq .Values.store.type "postgres" }}
|
||||
- name: store
|
||||
mountPath: /etc/llmgw/store
|
||||
readOnly: true
|
||||
{{- end }}
|
||||
{{- if .Values.offlineChecksums.configMap }}
|
||||
- name: offline
|
||||
mountPath: /etc/llmgw/offline
|
||||
readOnly: true
|
||||
{{- end }}
|
||||
- name: data
|
||||
mountPath: /var/lib/llmgw
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
volumes:
|
||||
- name: config
|
||||
configMap:
|
||||
name: {{ include "llmgw.fullname" . }}
|
||||
- name: agent-tls
|
||||
secret:
|
||||
secretName: {{ .Values.agentTLS.existingSecret }}
|
||||
defaultMode: 0440
|
||||
items:
|
||||
- {key: ca.pem, path: ca.pem}
|
||||
- {key: server.pem, path: server.pem}
|
||||
- {key: server-key.pem, path: server-key.pem}
|
||||
- name: admin-token
|
||||
secret:
|
||||
secretName: {{ include "llmgw.adminSecret" . }}
|
||||
defaultMode: 0440
|
||||
items:
|
||||
- key: {{ if .Values.adminToken.existingSecret }}{{ .Values.adminToken.secretKey }}{{ else }}admin-token{{ end }}
|
||||
path: admin-token
|
||||
{{- if eq .Values.store.type "postgres" }}
|
||||
- name: store
|
||||
secret:
|
||||
secretName: {{ .Values.store.postgres.existingSecret }}
|
||||
defaultMode: 0440
|
||||
items:
|
||||
- key: {{ .Values.store.postgres.secretKey }}
|
||||
path: dsn
|
||||
{{- end }}
|
||||
{{- if .Values.offlineChecksums.configMap }}
|
||||
- name: offline
|
||||
configMap:
|
||||
name: {{ .Values.offlineChecksums.configMap }}
|
||||
items:
|
||||
- key: {{ .Values.offlineChecksums.key }}
|
||||
path: offline.sha256
|
||||
{{- end }}
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
{{- if eq .Values.store.type "postgres" }}
|
||||
# The store is PostgreSQL; nothing here outlives the pod.
|
||||
- name: data
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- with .Values.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.affinity }}
|
||||
affinity:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if eq .Values.store.type "sqlite" }}
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
labels:
|
||||
{{- include "llmgw.selectorLabels" . | nindent 10 }}
|
||||
spec:
|
||||
accessModes: ["ReadWriteOnce"]
|
||||
{{- with .Values.store.sqlite.storageClass }}
|
||||
storageClassName: {{ . }}
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.store.sqlite.size }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,132 @@
|
||||
# The llmgw control plane in Kubernetes. docs/kubernetes.md says what this
|
||||
# runs, what it does not, and how nodes outside the cluster join it.
|
||||
|
||||
image:
|
||||
# Where you pushed the image built from deploy/container/Dockerfile. The
|
||||
# project publishes binaries, not an image, so this has no default.
|
||||
repository: ""
|
||||
# Empty takes the chart's appVersion.
|
||||
tag: ""
|
||||
pullPolicy: IfNotPresent
|
||||
imagePullSecrets: []
|
||||
|
||||
# One control plane, always. Two against PostgreSQL would elect a leader and
|
||||
# keep a standby, but a standby serves nothing and is never ready, so a
|
||||
# rollout would wait on it for ever. Until the chart handles that, it runs
|
||||
# one: Kubernetes replaces it within seconds when it goes, and the agents
|
||||
# reconnect on their own.
|
||||
replicas: 1
|
||||
|
||||
store:
|
||||
# sqlite: a file on a PersistentVolumeClaim, for one replica.
|
||||
# postgres: a PostgreSQL you run, its address in a Secret.
|
||||
type: sqlite
|
||||
sqlite:
|
||||
size: 10Gi
|
||||
storageClass: ""
|
||||
postgres:
|
||||
# A Secret holding the address, postgres://user:password@host:5432/llmgw?sslmode=verify-full
|
||||
existingSecret: ""
|
||||
secretKey: dsn
|
||||
|
||||
# The agent port's certificate. It comes from llmgw's own authority, not a
|
||||
# public one — agents present certificates from the same authority — so it
|
||||
# is made outside the cluster, where the authority's key stays:
|
||||
#
|
||||
# llmgw ctl cert init-ca --dir ./pki
|
||||
# llmgw ctl cert issue-server llmgw-ctl --host <agent address> --dir ./pki --out ./pki
|
||||
# kubectl create secret generic llmgw-agent-tls \
|
||||
# --from-file=ca.pem=pki/ca.pem \
|
||||
# --from-file=server.pem=pki/server.pem \
|
||||
# --from-file=server-key.pem=pki/server-key.pem
|
||||
#
|
||||
# --host is every address agents dial: agentService's load balancer address
|
||||
# or DNS name.
|
||||
agentTLS:
|
||||
existingSecret: ""
|
||||
|
||||
# The admin API's token (llmgw ctl, the console). Empty makes one, kept in a
|
||||
# Secret across upgrades.
|
||||
adminToken:
|
||||
existingSecret: ""
|
||||
secretKey: admin-token
|
||||
|
||||
# server.yaml beyond what the chart sets (listeners, TLS, store, admin
|
||||
# token): any key of docs/reference.md, laid over the chart's. An offline
|
||||
# cluster sets offline.mirror here, and offlineChecksums below.
|
||||
config:
|
||||
control:
|
||||
enabled: true
|
||||
auth:
|
||||
enabled: true
|
||||
signup_open: false
|
||||
default_rpm: 60
|
||||
default_tpm: 200000
|
||||
default_price:
|
||||
prompt_per_1k: 1000
|
||||
completion_per_1k: 1000
|
||||
max_key_ttl: 2160h
|
||||
# mirror:
|
||||
# api: https://models.internal:8082
|
||||
# offline:
|
||||
# mirror: http://models.internal:8081
|
||||
# firewall_networks: ["10.42.0.0/16"] # the pods' network, so nodes' engines answer the router
|
||||
|
||||
# On an offline cluster, a ConfigMap or Secret holding the engine checksums
|
||||
# 'llmgw bundle trust' writes (offline.sha256), mounted where offline.checksums
|
||||
# points. Empty mounts none.
|
||||
offlineChecksums:
|
||||
configMap: ""
|
||||
key: offline.sha256
|
||||
|
||||
# The OpenAI-compatible API and the metrics, inside the cluster.
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 8080
|
||||
metricsPort: 9091
|
||||
annotations: {}
|
||||
|
||||
# Where agents connect, with mutual TLS. Nodes run outside the cluster, so
|
||||
# this is a load balancer by default; the TLS ends in the pod, never at a
|
||||
# proxy in between.
|
||||
agentService:
|
||||
type: LoadBalancer
|
||||
port: 7443
|
||||
annotations: {}
|
||||
loadBalancerIP: ""
|
||||
loadBalancerSourceRanges: []
|
||||
# Keeps the agents' addresses as they are, which the node's identity does
|
||||
# not need but the logs and the audit read better with.
|
||||
externalTrafficPolicy: Local
|
||||
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
annotations: {}
|
||||
hosts:
|
||||
- host: llm.example.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
tls: []
|
||||
# - secretName: llm-example-com
|
||||
# hosts: [llm.example.com]
|
||||
|
||||
# A ServiceMonitor for the Prometheus Operator, scraping the metrics port.
|
||||
serviceMonitor:
|
||||
enabled: false
|
||||
interval: 30s
|
||||
labels: {}
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
memory: 2Gi
|
||||
|
||||
nodeSelector: {}
|
||||
tolerations: []
|
||||
affinity: {}
|
||||
podAnnotations: {}
|
||||
podLabels: {}
|
||||
@@ -25,6 +25,13 @@ An HTTP server serving a directory. That is the whole design.
|
||||
model.safetensors
|
||||
```
|
||||
|
||||
At an offline site the mirror also holds what the nodes would otherwise fetch
|
||||
from the internet — llmgw's releases and the llama.cpp builds — under
|
||||
`_llmgw/releases/` and `_llmgw/engines/`, put there by `llmgw bundle import`
|
||||
(docs/install.md, "Offline sites"). They are not models: `mirror list` and
|
||||
`mirror unused` pass over them, and a node checks each against what the
|
||||
control plane says it must be, not against anything the mirror says.
|
||||
|
||||
The date in the path is the point of the layout, not decoration. A model
|
||||
repository that changes upstream changes what you are running, and the first
|
||||
sign is a prompt that worked last week answering differently this week with
|
||||
|
||||
@@ -555,3 +555,32 @@ groups:
|
||||
It was stopped or rewritten if the policy enforces; either way a
|
||||
model has seen it, in its prompt or its training. The usage rows
|
||||
with guard_category secret say which request.
|
||||
|
||||
- name: llmgw-slo
|
||||
rules:
|
||||
- alert: ModelTTFTOverSLO
|
||||
expr: >-
|
||||
histogram_quantile(0.99, sum by (le, model) (rate(llmgw_ttft_seconds_bucket[10m])))
|
||||
> on (model) group_left llmgw_model_slo_seconds{kind="ttft_p99"}
|
||||
for: 15m
|
||||
labels: { severity: warning }
|
||||
annotations:
|
||||
summary: "{{ $labels.model }} answers its first token past its SLO at p99"
|
||||
description: >-
|
||||
The p99 time to the first token over ten minutes is past the
|
||||
model's slo.ttft_p99. Admission already holds the lower bands back
|
||||
while it is; this says it has lasted. More replicas, or less
|
||||
traffic in the bands above.
|
||||
|
||||
- alert: ModelTPOTOverSLO
|
||||
expr: >-
|
||||
histogram_quantile(0.99, sum by (le, model) (rate(llmgw_tpot_seconds_bucket[10m])))
|
||||
> on (model) group_left llmgw_model_slo_seconds{kind="tpot_p99"}
|
||||
for: 15m
|
||||
labels: { severity: warning }
|
||||
annotations:
|
||||
summary: "{{ $labels.model }} produces tokens slower than its SLO at p99"
|
||||
description: >-
|
||||
The p99 time per output token is past slo.tpot_p99: replicas are
|
||||
batching more than they can decode quickly, or a slower card is
|
||||
serving. llmgw_output_tokens_per_second by pool says which.
|
||||
@@ -1,10 +1,103 @@
|
||||
// Package llmgw holds what the binary carries besides code: its manual.
|
||||
// Package llmgw holds what the binary carries besides code: its manual, the
|
||||
// description of its admin API, and the example quality suites.
|
||||
package llmgw
|
||||
|
||||
import "embed"
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Docs is the documentation, read on any machine by `llmgw docs` and the
|
||||
// console's manual without a checkout or the internet.
|
||||
//
|
||||
//go:embed README.md CHANGELOG.md docs/*.md
|
||||
var Docs embed.FS
|
||||
|
||||
// Doc is one page of the manual.
|
||||
type Doc struct {
|
||||
// Key is what `llmgw docs KEY` takes, and the page's address under /docs/
|
||||
// on the gateway.
|
||||
Key string
|
||||
// Path is the file in Docs.
|
||||
Path string
|
||||
// Title is the document's first heading.
|
||||
Title string
|
||||
}
|
||||
|
||||
// Source is the document's markdown.
|
||||
func (d Doc) Source() string {
|
||||
b, err := fs.ReadFile(Docs, d.Path)
|
||||
if err != nil {
|
||||
return "# " + d.Path + "\n\nNot in this build."
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// docOrder is the documents in the order someone new reads them. Here rather
|
||||
// than with either reader, because the console's manual and the gateway's
|
||||
// docs portal both list them, and two lists drift.
|
||||
var docOrder = []string{"console", "quick-install", "install", "node-onboarding", "onboarding",
|
||||
"clients", "guardrails", "choosing-models", "fabrics", "facility-aware-placement", "data",
|
||||
"reference", "development"}
|
||||
|
||||
// Manual is every document, in reading order: those docOrder names, then any
|
||||
// other under docs/ alphabetically, so a new one is never missing, then the
|
||||
// README and the changes.
|
||||
func Manual() []Doc {
|
||||
var out []Doc
|
||||
seen := map[string]bool{}
|
||||
add := func(key, path string) {
|
||||
if seen[key] {
|
||||
return
|
||||
}
|
||||
b, err := fs.ReadFile(Docs, path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, Doc{Key: key, Path: path, Title: titleOf(string(b), path)})
|
||||
}
|
||||
for _, k := range docOrder {
|
||||
add(k, "docs/"+k+".md")
|
||||
}
|
||||
entries, _ := fs.ReadDir(Docs, "docs")
|
||||
var rest []string
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".md") {
|
||||
rest = append(rest, strings.TrimSuffix(e.Name(), ".md"))
|
||||
}
|
||||
}
|
||||
sort.Strings(rest)
|
||||
for _, k := range rest {
|
||||
add(k, "docs/"+k+".md")
|
||||
}
|
||||
add("readme", "README.md")
|
||||
add("changes", "CHANGELOG.md")
|
||||
return out
|
||||
}
|
||||
|
||||
// titleOf is a document's first top-level heading, or its path when it has
|
||||
// none.
|
||||
func titleOf(src, path string) string {
|
||||
for _, l := range strings.Split(src, "\n") {
|
||||
if strings.HasPrefix(l, "# ") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(l, "# "))
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// AdminOpenAPI is the admin API described in OpenAPI 3.1, generated from its
|
||||
// route table by `go generate` in internal/docgen and served at
|
||||
// /api/v1/openapi.json, so a client can be pointed at the server it talks to.
|
||||
//
|
||||
//go:embed docs/admin-api.openapi.json
|
||||
var AdminOpenAPI []byte
|
||||
|
||||
// EvalSuites are the example quality suites under deploy/eval, which the
|
||||
// control plane runs by name when its eval directory has none of the name.
|
||||
//
|
||||
//go:embed deploy/eval/*.yaml
|
||||
var EvalSuites embed.FS
|
||||
@@ -0,0 +1,160 @@
|
||||
# The admin API
|
||||
|
||||
Written for whoever automates a cluster rather than typing at it: how to reach
|
||||
the control plane's management API, what it asks of a request, and where its
|
||||
description is.
|
||||
|
||||
`llmgw ctl` and the console are clients of this API and nothing more, so
|
||||
anything they do can be done with `curl`, a generated client or the
|
||||
[Terraform provider](../terraform-provider-llmgw/README.md). It adds and
|
||||
removes models, scales them, cordons and upgrades nodes, sets capacity
|
||||
quotas, attaches guardrail policies, and reads the fleet, usage and the audit
|
||||
log.
|
||||
|
||||
## Reaching it
|
||||
|
||||
The API is under `/api/v1` on the admin listener, `admin_listen` in
|
||||
`/etc/llmgw/server.yaml`: `127.0.0.1:9090` unless changed. It is on loopback
|
||||
on purpose. The same listener serves pprof when it is turned on, and the
|
||||
server refuses to start with it on any other address unless
|
||||
`admin_remote: true` — the token would cross the network in clear.
|
||||
|
||||
From another machine, tunnel to it rather than moving it:
|
||||
|
||||
```sh
|
||||
ssh -N -L 9090:127.0.0.1:9090 admin@control-plane &
|
||||
curl -s -H "Authorization: Bearer $LLMGW_ADMIN_TOKEN" http://127.0.0.1:9090/api/v1/summary
|
||||
```
|
||||
|
||||
With `admin_remote: true` and `admin_listen: 10.0.0.5:9090`, call that address
|
||||
directly — on a network you trust, or behind a TLS proxy that keeps the
|
||||
`Host` header an address.
|
||||
|
||||
## The token
|
||||
|
||||
Every path under `/api` needs the admin token as a bearer token:
|
||||
|
||||
```
|
||||
Authorization: Bearer 6f1c…
|
||||
```
|
||||
|
||||
The server writes it the first time it starts, 0600, to
|
||||
`/var/lib/llmgw/admin-token` under its systemd unit (`admin_token_file`
|
||||
moves it; a server run by hand keeps it in `secrets/admin-token` beside its
|
||||
configuration). `llmgw ctl` reads it from there, which is why it runs with
|
||||
sudo, or from `LLMGW_ADMIN_TOKEN`. To give it to automation:
|
||||
|
||||
```sh
|
||||
sudo cat /var/lib/llmgw/admin-token
|
||||
```
|
||||
|
||||
The token is the whole of the API's authorisation: whoever holds it can do
|
||||
everything the API does. Keep it where you keep other root credentials.
|
||||
|
||||
## What a request must look like
|
||||
|
||||
Besides the token, the listener refuses three things before a handler sees
|
||||
them, as defences against a browser being turned against it:
|
||||
|
||||
- **A name in `Host`.** The listener answers to an address or `localhost`,
|
||||
not a DNS name, so a page on some other site cannot reach it by rebinding
|
||||
a name to 127.0.0.1. Call it as `http://127.0.0.1:9090`, not
|
||||
`http://cp.example.com:9090`; behind a proxy, have the proxy send an
|
||||
address.
|
||||
- **A cross-site request.** One whose `Origin` is another host, or whose
|
||||
`Sec-Fetch-Site` says another site sent it.
|
||||
- **A change that is not JSON.** Every method but `GET` and `HEAD` must carry
|
||||
`Content-Type: application/json`, even a `DELETE` or a `POST` with no body.
|
||||
A form post from a page cannot set that header.
|
||||
|
||||
A change is recorded in the audit log with who made it, as the request says
|
||||
in `X-Llmgw-Actor` (letters, digits and `._-@`, at most 64; `unknown` when
|
||||
absent). `llmgw ctl` sends the name of whoever ran it; automation should send
|
||||
its own, `terraform` or `ci@deploy`, so `llmgw ctl audit` can tell them apart.
|
||||
|
||||
A refusal is a 4xx or 5xx with `{"error": "…"}` saying why. 501 means this
|
||||
control plane lacks what the endpoint needs — a store, a mirror, guard
|
||||
policies — and says which.
|
||||
|
||||
## Some calls
|
||||
|
||||
```sh
|
||||
H=(-H "Authorization: Bearer $LLMGW_ADMIN_TOKEN" -H "Content-Type: application/json" -H "X-Llmgw-Actor: $USER")
|
||||
API=http://127.0.0.1:9090/api/v1
|
||||
|
||||
# The fleet in one answer, and every model.
|
||||
curl -s "${H[@]}" $API/summary
|
||||
curl -s "${H[@]}" $API/models
|
||||
|
||||
# Add a model, read back its definition with the defaults filled in, scale it.
|
||||
curl -s "${H[@]}" -X POST $API/models -d '{
|
||||
"name": "qwen-small",
|
||||
"source": "/srv/models/qwen2.5-1.5b-instruct-q4_k_m.gguf",
|
||||
"profiles": [{"name": "cpu", "engine": "llamacpp", "min_memory_gb": 4, "cpu_cores": 4}],
|
||||
"scaling": {"min": 1, "max": 2}
|
||||
}'
|
||||
curl -s "${H[@]}" $API/models/qwen-small
|
||||
curl -s "${H[@]}" -X POST $API/models/qwen-small/scale -d '{"min": 0, "max": 2, "idle_timeout": 1800000000000}'
|
||||
|
||||
# A team's capacity quota.
|
||||
curl -s "${H[@]}" -X PUT $API/quotas -d '{"scope": "team:Acme/ml", "limit": {"gpus": 8}}'
|
||||
|
||||
# Remove the model; a DELETE carries the content type too.
|
||||
curl -s "${H[@]}" -X DELETE $API/models/qwen-small
|
||||
```
|
||||
|
||||
Durations in bodies are integer nanoseconds, as Go encodes them: half an hour
|
||||
is `1800000000000`.
|
||||
|
||||
## The description
|
||||
|
||||
The API is described in OpenAPI 3.1:
|
||||
|
||||
- served by every control plane at `GET /api/v1/openapi.json` (with the
|
||||
token, like the rest), as built into that binary, so it describes the
|
||||
server you are talking to;
|
||||
- committed as [admin-api.openapi.json](admin-api.openapi.json) for reading
|
||||
without a cluster.
|
||||
|
||||
```sh
|
||||
curl -s "${H[@]}" $API/openapi.json > llmgw-admin.json
|
||||
```
|
||||
|
||||
It lists every endpoint, its path and query parameters, and the schema of
|
||||
each request and answer, with the meaning of each field. Load it into any
|
||||
OpenAPI tool — Swagger UI, Redoc, an editor — or generate a client from it:
|
||||
|
||||
```sh
|
||||
docker run --rm -v "$PWD:/w" openapitools/openapi-generator-cli generate \
|
||||
-i /w/llmgw-admin.json -g python -o /w/llmgw-admin-client
|
||||
```
|
||||
|
||||
### How it is kept true
|
||||
|
||||
The document is generated, not written. `internal/control/adminapi/routes.go`
|
||||
holds a table of every endpoint: its method and path, a summary, its query
|
||||
parameters, and Go values of the types it reads and answers with. The
|
||||
generator in `internal/docgen/openapi` reads those types by reflection, the
|
||||
way `encoding/json` encodes them, and takes each field's description from its
|
||||
comment in the source.
|
||||
|
||||
Two tests keep it from drifting. One registers the API on a recording mux and
|
||||
fails when an endpoint is served and not in the table, or in the table and not
|
||||
served. The other regenerates the document and fails when it differs from the
|
||||
committed one. After changing an endpoint or a type it carries:
|
||||
|
||||
```sh
|
||||
go generate ./internal/docgen
|
||||
```
|
||||
|
||||
## What it does not cover
|
||||
|
||||
- **Organizations, teams, projects, people and API keys.** These live in the
|
||||
store and are managed with `llmgw org`, `llmgw users` and `llmgw keys` on the
|
||||
control plane, or in the web console's `/admin` pages on the client port
|
||||
behind a session. The admin API reads the tree only where a quota or a
|
||||
policy names a part of it.
|
||||
- **The client-facing API** (`/v1/chat/completions` and the rest), which is
|
||||
OpenAI's and Anthropic's, on `listen`, with API keys.
|
||||
- **The rest of the admin listener**: `/metrics`, `/health`, the dashboard
|
||||
pages and `/debug/pprof`, which are not under `/api`.
|
||||
File diff suppressed because it is too large.
Load diff
+548
@@ -0,0 +1,548 @@
|
||||
# Using llmgw from code
|
||||
|
||||
Written for a developer whose program talks to a model through llmgw. There
|
||||
is no llmgw SDK, and there will not be one: the gateway speaks OpenAI's API
|
||||
and Anthropic's Messages API, so the official SDKs for both work as they are.
|
||||
Only two things change — the base URL and the key. Everything llmgw adds on
|
||||
top is an HTTP header, which every one of those SDKs lets you set.
|
||||
|
||||
The examples use `https://llm.example.com` for the gateway; use the address
|
||||
your operator gave you, or the one on the gateway's own front page. Every
|
||||
example reads the key from `LLMGW_API_KEY`. `<model-name>` is a model this
|
||||
gateway serves: `GET /v1/models` lists the ones your key may use, and sending
|
||||
the placeholder unchanged is answered with that list rather than with an
|
||||
error.
|
||||
|
||||
## Getting a key
|
||||
|
||||
Keys are made on the gateway's **Account** page after signing in, or issued
|
||||
by an operator. A key is shown once and never again — only its hash is kept —
|
||||
so put it in a password manager straight away. `GET /me` with the key says
|
||||
what it may do and what it has spent.
|
||||
|
||||
## The base URL and the key
|
||||
|
||||
| SDK | Base URL | Key |
|
||||
|---|---|---|
|
||||
| OpenAI (any language) | `https://llm.example.com/v1` | `Authorization: Bearer …`, as the SDK sends it |
|
||||
| Anthropic (any language) | `https://llm.example.com` — the SDK adds `/v1/messages` | `x-api-key: …`, as the SDK sends it |
|
||||
|
||||
Both SDKs also read their usual environment variables, so a program that
|
||||
already uses them needs no change at all:
|
||||
|
||||
```
|
||||
export OPENAI_BASE_URL=https://llm.example.com/v1
|
||||
export OPENAI_API_KEY=$LLMGW_API_KEY
|
||||
|
||||
export ANTHROPIC_BASE_URL=https://llm.example.com
|
||||
export ANTHROPIC_API_KEY=$LLMGW_API_KEY
|
||||
```
|
||||
|
||||
## A first request
|
||||
|
||||
### curl
|
||||
|
||||
```
|
||||
curl https://llm.example.com/v1/chat/completions \
|
||||
-H "Authorization: Bearer $LLMGW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model": "<model-name>",
|
||||
"messages": [{"role": "user", "content": "Say hello in Turkish."}]}'
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```
|
||||
pip install openai
|
||||
```
|
||||
|
||||
```python
|
||||
import os
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="https://llm.example.com/v1",
|
||||
api_key=os.environ["LLMGW_API_KEY"])
|
||||
|
||||
reply = client.chat.completions.create(
|
||||
model="<model-name>",
|
||||
messages=[{"role": "user", "content": "Say hello in Turkish."}],
|
||||
)
|
||||
print(reply.choices[0].message.content)
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
```
|
||||
npm install openai
|
||||
```
|
||||
|
||||
```typescript
|
||||
import OpenAI from "openai";
|
||||
|
||||
const client = new OpenAI({
|
||||
baseURL: "https://llm.example.com/v1",
|
||||
apiKey: process.env.LLMGW_API_KEY,
|
||||
});
|
||||
|
||||
const reply = await client.chat.completions.create({
|
||||
model: "<model-name>",
|
||||
messages: [{ role: "user", content: "Say hello in Turkish." }],
|
||||
});
|
||||
console.log(reply.choices[0].message.content);
|
||||
```
|
||||
|
||||
### Go
|
||||
|
||||
```
|
||||
go get github.com/openai/openai-go/v3
|
||||
```
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/openai/openai-go/v3"
|
||||
"github.com/openai/openai-go/v3/option"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := openai.NewClient(
|
||||
option.WithBaseURL("https://llm.example.com/v1/"),
|
||||
option.WithAPIKey(os.Getenv("LLMGW_API_KEY")),
|
||||
)
|
||||
reply, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
|
||||
Model: "<model-name>",
|
||||
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Say hello in Turkish.")},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(reply.Choices[0].Message.Content)
|
||||
}
|
||||
```
|
||||
|
||||
The import path carries the SDK's major version; use the one your module
|
||||
already has.
|
||||
|
||||
## Streaming
|
||||
|
||||
Set `stream` and read the chunks. llmgw may send a last chunk that carries
|
||||
only the token counts and no choices, so check for a choice before reading
|
||||
one — the OpenAI API does the same when usage is asked for.
|
||||
|
||||
```python
|
||||
stream = client.chat.completions.create(
|
||||
model="<model-name>",
|
||||
messages=[{"role": "user", "content": "Count to ten."}],
|
||||
stream=True,
|
||||
)
|
||||
for chunk in stream:
|
||||
if chunk.choices and chunk.choices[0].delta.content:
|
||||
print(chunk.choices[0].delta.content, end="", flush=True)
|
||||
print()
|
||||
```
|
||||
|
||||
```typescript
|
||||
const stream = await client.chat.completions.create({
|
||||
model: "<model-name>",
|
||||
messages: [{ role: "user", content: "Count to ten." }],
|
||||
stream: true,
|
||||
});
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
stream := client.Chat.Completions.NewStreaming(ctx, openai.ChatCompletionNewParams{
|
||||
Model: "<model-name>",
|
||||
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Count to ten.")},
|
||||
})
|
||||
for stream.Next() {
|
||||
chunk := stream.Current()
|
||||
if len(chunk.Choices) > 0 {
|
||||
fmt.Print(chunk.Choices[0].Delta.Content)
|
||||
}
|
||||
}
|
||||
if err := stream.Err(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
With curl, add `"stream": true` to the body and `-N` so curl prints the
|
||||
events as they come.
|
||||
|
||||
## Tools
|
||||
|
||||
Function calling is OpenAI's: describe the tools, run the ones the model
|
||||
asks for, send the results back. Whether a model calls tools well is the
|
||||
model's business, not the gateway's; ask your operator which of the served
|
||||
models are set up for it.
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
tools = [{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "The current weather in a city.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}]
|
||||
|
||||
messages = [{"role": "user", "content": "Is it raining in Ankara?"}]
|
||||
reply = client.chat.completions.create(model="<model-name>", messages=messages, tools=tools)
|
||||
msg = reply.choices[0].message
|
||||
|
||||
if msg.tool_calls:
|
||||
messages.append(msg)
|
||||
for call in msg.tool_calls:
|
||||
args = json.loads(call.function.arguments)
|
||||
result = {"city": args["city"], "raining": False} # your code here
|
||||
messages.append({"role": "tool", "tool_call_id": call.id,
|
||||
"content": json.dumps(result)})
|
||||
reply = client.chat.completions.create(model="<model-name>", messages=messages, tools=tools)
|
||||
|
||||
print(reply.choices[0].message.content)
|
||||
```
|
||||
|
||||
## Embeddings
|
||||
|
||||
```python
|
||||
result = client.embeddings.create(
|
||||
model="<embedding-model>",
|
||||
input=["llmgw routes requests", "to GPUs it can reach"],
|
||||
)
|
||||
vectors = [d.embedding for d in result.data]
|
||||
```
|
||||
|
||||
```typescript
|
||||
const result = await client.embeddings.create({
|
||||
model: "<embedding-model>",
|
||||
input: ["llmgw routes requests", "to GPUs it can reach"],
|
||||
});
|
||||
const vectors = result.data.map((d) => d.embedding);
|
||||
```
|
||||
|
||||
An embedding model is a model of its own; a chat model does not answer
|
||||
`/v1/embeddings`.
|
||||
|
||||
## The Responses API
|
||||
|
||||
`/v1/responses` is served too, for clients that speak nothing else (Codex
|
||||
among them). llmgw translates it to chat completions, so it works with every
|
||||
model the gateway serves; what has no equivalent there — OpenAI's hosted
|
||||
tools, reasoning summaries — is ignored rather than refused.
|
||||
|
||||
```python
|
||||
response = client.responses.create(
|
||||
model="<model-name>",
|
||||
instructions="Answer in one sentence.",
|
||||
input="Why is the sky blue?",
|
||||
)
|
||||
print(response.output_text)
|
||||
```
|
||||
|
||||
Streamed, the events are the Responses API's own:
|
||||
|
||||
```python
|
||||
stream = client.responses.create(model="<model-name>", input="Count to ten.", stream=True)
|
||||
for event in stream:
|
||||
if event.type == "response.output_text.delta":
|
||||
print(event.delta, end="", flush=True)
|
||||
```
|
||||
|
||||
## Batches
|
||||
|
||||
For work that need not finish now: OpenAI's Files and Batch APIs. A batch runs
|
||||
at the lowest priority, so it uses what interactive traffic leaves free, and
|
||||
each line is counted against the key that submitted it.
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
with open("requests.jsonl", "w") as f:
|
||||
for i, text in enumerate(["first document", "second document"]):
|
||||
f.write(json.dumps({
|
||||
"custom_id": f"doc-{i}",
|
||||
"method": "POST",
|
||||
"url": "/v1/chat/completions",
|
||||
"body": {"model": "<model-name>",
|
||||
"messages": [{"role": "user", "content": "Summarise: " + text}]},
|
||||
}) + "\n")
|
||||
|
||||
batch_file = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
|
||||
batch = client.batches.create(
|
||||
input_file_id=batch_file.id,
|
||||
endpoint="/v1/chat/completions",
|
||||
completion_window="24h",
|
||||
)
|
||||
|
||||
# Later:
|
||||
batch = client.batches.retrieve(batch.id)
|
||||
if batch.status == "completed":
|
||||
for line in client.files.content(batch.output_file_id).text.splitlines():
|
||||
result = json.loads(line)
|
||||
print(result["custom_id"], result["response"]["body"]["choices"][0]["message"]["content"])
|
||||
```
|
||||
|
||||
## The Anthropic SDK
|
||||
|
||||
`/v1/messages` is Anthropic's Messages API, translated to chat completions and
|
||||
back, streamed or not, with tools and images. It serves the gateway's own
|
||||
models — `model` is a model this gateway serves, not a Claude model.
|
||||
|
||||
```
|
||||
pip install anthropic
|
||||
```
|
||||
|
||||
```python
|
||||
import os
|
||||
import anthropic
|
||||
|
||||
client = anthropic.Anthropic(base_url="https://llm.example.com",
|
||||
api_key=os.environ["LLMGW_API_KEY"])
|
||||
|
||||
message = client.messages.create(
|
||||
model="<model-name>",
|
||||
max_tokens=1024,
|
||||
messages=[{"role": "user", "content": "Say hello in Turkish."}],
|
||||
)
|
||||
print(message.content[0].text)
|
||||
|
||||
with client.messages.stream(
|
||||
model="<model-name>",
|
||||
max_tokens=1024,
|
||||
messages=[{"role": "user", "content": "Count to ten."}],
|
||||
) as stream:
|
||||
for text in stream.text_stream:
|
||||
print(text, end="", flush=True)
|
||||
```
|
||||
|
||||
```typescript
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
|
||||
const client = new Anthropic({
|
||||
baseURL: "https://llm.example.com",
|
||||
apiKey: process.env.LLMGW_API_KEY,
|
||||
});
|
||||
|
||||
const message = await client.messages.create({
|
||||
model: "<model-name>",
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: "user", content: "Say hello in Turkish." }],
|
||||
});
|
||||
for (const block of message.content) {
|
||||
if (block.type === "text") console.log(block.text);
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
client := anthropic.NewClient(
|
||||
option.WithBaseURL("https://llm.example.com/"),
|
||||
option.WithAPIKey(os.Getenv("LLMGW_API_KEY")),
|
||||
)
|
||||
message, err := client.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: "<model-name>",
|
||||
MaxTokens: 1024,
|
||||
Messages: []anthropic.MessageParam{
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Say hello in Turkish.")),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for _, block := range message.Content {
|
||||
if text, ok := block.AsAny().(anthropic.TextBlock); ok {
|
||||
fmt.Println(text.Text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
(`github.com/anthropics/anthropic-sdk-go` and its `option` package.)
|
||||
|
||||
With curl:
|
||||
|
||||
```
|
||||
curl https://llm.example.com/v1/messages \
|
||||
-H "x-api-key: $LLMGW_API_KEY" \
|
||||
-H "anthropic-version: 2023-06-01" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model": "<model-name>", "max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Say hello in Turkish."}]}'
|
||||
```
|
||||
|
||||
## What llmgw adds
|
||||
|
||||
Each is a header, so a request stays exactly what the SDK would send anywhere
|
||||
else. Set one for every request on the client, or for one request:
|
||||
|
||||
| | Every request | One request |
|
||||
|---|---|---|
|
||||
| Python (both SDKs) | `OpenAI(..., default_headers={...})` | `create(..., extra_headers={...})` |
|
||||
| TypeScript (both SDKs) | `new OpenAI({ ..., defaultHeaders: {...} })` | `create({...}, { headers: {...} })` |
|
||||
| Go (both SDKs) | `openai.NewClient(..., option.WithHeader(k, v))` | `New(ctx, params, option.WithHeader(k, v))` |
|
||||
| curl | | `-H "k: v"` |
|
||||
|
||||
### Stored conversations: `x-llmgw-thread`
|
||||
|
||||
Send the same thread id with each request and only the new turn; llmgw puts
|
||||
the stored conversation in front of it. The conversation continues on
|
||||
whichever model serves the next turn, even a different one. It must be
|
||||
turned on for your project by an operator (`llmgw keys threads`); a request
|
||||
that names a thread on a gateway that keeps none is refused rather than
|
||||
answered without its history.
|
||||
|
||||
```python
|
||||
import uuid
|
||||
|
||||
thread = str(uuid.uuid4()) # anyone in your project who knows it reads it
|
||||
for turn in ["My name is Deniz.", "What is my name?"]:
|
||||
reply = client.chat.completions.create(
|
||||
model="<model-name>",
|
||||
messages=[{"role": "user", "content": turn}],
|
||||
extra_headers={"x-llmgw-thread": thread},
|
||||
)
|
||||
print(reply.choices[0].message.content)
|
||||
```
|
||||
|
||||
A thread belongs to the project, not to the key, so use an id nobody can
|
||||
guess: at most 128 letters, digits and `- _ . :`. When the conversation no
|
||||
longer fits the model, the oldest turns are left out and the reply carries
|
||||
`x-llmgw-thread-trimmed` with how many. `DELETE /v1/threads/{id}` forgets one:
|
||||
|
||||
```
|
||||
curl -X DELETE https://llm.example.com/v1/threads/$THREAD \
|
||||
-H "Authorization: Bearer $LLMGW_API_KEY"
|
||||
```
|
||||
|
||||
### Sessions: `x-session-id`
|
||||
|
||||
Requests with the same session id go to the same replica while it is
|
||||
healthy, so a conversation that resends its history finds it already in that
|
||||
replica's cache and answers sooner. Without the header, the body's `user`
|
||||
field is used. Nothing is stored; it is only a routing hint.
|
||||
|
||||
```python
|
||||
client = OpenAI(base_url="https://llm.example.com/v1", api_key=os.environ["LLMGW_API_KEY"],
|
||||
default_headers={"x-session-id": "chat-7f3a"})
|
||||
```
|
||||
|
||||
### Tags and metadata
|
||||
|
||||
Requests can be labelled so the usage they record can be told apart — by
|
||||
feature, by customer, by job. Send OpenAI's own `metadata`, string keys to
|
||||
string values, or the same as the `x-llmgw-tags` header for a client that
|
||||
cannot set `metadata`; the `user` field is recorded too. Which tags also
|
||||
become metric labels is the operator's choice (`router.tag_labels`).
|
||||
|
||||
```python
|
||||
reply = client.chat.completions.create(
|
||||
model="<model-name>",
|
||||
messages=[{"role": "user", "content": "Classify this ticket."}],
|
||||
metadata={"feature": "triage", "customer": "acme"},
|
||||
user="user-1234",
|
||||
)
|
||||
```
|
||||
|
||||
```
|
||||
curl https://llm.example.com/v1/chat/completions \
|
||||
-H "Authorization: Bearer $LLMGW_API_KEY" \
|
||||
-H "x-llmgw-tags: feature=triage,customer=acme" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"model": "<model-name>", "messages": [{"role": "user", "content": "Classify this ticket."}]}'
|
||||
```
|
||||
|
||||
### Canaries: `x-llmgw-variant`
|
||||
|
||||
While an operator tries a model's newer weights on a share of its traffic, a
|
||||
session stays on one side. `x-llmgw-variant: canary` sends a request to the
|
||||
canary deliberately — to try it before it is promoted, or to compare the two.
|
||||
|
||||
```python
|
||||
reply = client.chat.completions.create(
|
||||
model="<model-name>",
|
||||
messages=[{"role": "user", "content": "hello"}],
|
||||
extra_headers={"x-llmgw-variant": "canary"},
|
||||
)
|
||||
```
|
||||
|
||||
### Memory notes: `/v1/memory`
|
||||
|
||||
Notes an agent keeps for itself across conversations: a key, some text, and
|
||||
optional tags, private to your project and to the agent named in
|
||||
`x-llmgw-agent` (`default` when it is not sent). An operator turns them on for
|
||||
a project (`llmgw keys memory`). They are plain REST, so any HTTP client
|
||||
will do:
|
||||
|
||||
```
|
||||
H="Authorization: Bearer $LLMGW_API_KEY"
|
||||
|
||||
curl -X PUT https://llm.example.com/v1/memory/favourite-colour -H "$H" \
|
||||
-H "x-llmgw-agent: helper" -H "Content-Type: application/json" \
|
||||
-d '{"text": "The user likes dark green.", "tags": ["preference"]}'
|
||||
|
||||
curl "https://llm.example.com/v1/memory?q=green" -H "$H" -H "x-llmgw-agent: helper"
|
||||
curl "https://llm.example.com/v1/memory?tag=preference" -H "$H" -H "x-llmgw-agent: helper"
|
||||
curl https://llm.example.com/v1/memory/favourite-colour -H "$H" -H "x-llmgw-agent: helper"
|
||||
curl -X DELETE https://llm.example.com/v1/memory/favourite-colour -H "$H" -H "x-llmgw-agent: helper"
|
||||
```
|
||||
|
||||
A key is up to 200 bytes, a note up to 16 KiB, with at most 16 tags of
|
||||
lowercase letters, digits, `-` and `_`, and 1000 notes per agent.
|
||||
|
||||
### MCP: `/mcp`
|
||||
|
||||
The same notes as tools an agent can be given — `remember`, `recall` and
|
||||
`forget` — from an MCP server at `https://llm.example.com/mcp` (the HTTP
|
||||
transport, answered as plain JSON). Add it to your agent's MCP servers with
|
||||
the key as a bearer token and, if you want notes kept apart, `x-llmgw-agent`.
|
||||
llmgw does not put these tools into requests by itself: an agent that is not
|
||||
given the server never sees its notes.
|
||||
|
||||
```
|
||||
curl https://llm.example.com/mcp \
|
||||
-H "Authorization: Bearer $LLMGW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
|
||||
```
|
||||
|
||||
### Headers llmgw sends back
|
||||
|
||||
| Header | Says |
|
||||
|---|---|
|
||||
| `x-request-id` | The request's id in the gateway's logs and usage records — quote it when asking an operator about a request. |
|
||||
| `x-llmgw-served-model` | The model that answered, when it was not the one asked for: a spent budget can move a request to a cheaper model. |
|
||||
| `x-llmgw-queue-ms` | How long the request waited for room before it was sent. |
|
||||
| `x-llmgw-thread-trimmed` | How many stored turns were left out to fit the model. |
|
||||
|
||||
## When something is refused
|
||||
|
||||
Errors come back in the shape of the API that was called — OpenAI's
|
||||
`{"error": {"message": …, "type": …}}` or Anthropic's — so each SDK raises
|
||||
its usual exception with the gateway's message in it. The ones worth knowing:
|
||||
|
||||
| Status | Usually means |
|
||||
|---|---|
|
||||
| 400 | Besides a malformed request: a prompt too long for the model, or a guardrail policy refused it (the code `content_policy_violation`). |
|
||||
| 401 | No key, a mistyped one, or one that was revoked or has expired. |
|
||||
| 403 | The key may not use that model. |
|
||||
| 429 | A rate limit or budget of the key, its project or its team was reached. `Retry-After` says when to try again, and is absent when waiting will not help — a spent monthly budget. |
|
||||
| 503 | No model of that name is served (the message lists the ones that are), the model is still loading, or every replica is busy and the request waited as long as it may. The SDKs retry by themselves; a name that is not served will not start to be. |
|
||||
|
||||
## Priority
|
||||
|
||||
With keys on, the key decides the request's priority band and routing
|
||||
profile, set by an operator; the `x-llmgw-band` and `x-llmgw-profile` headers
|
||||
are ignored, so a client cannot promote itself. On a gateway without keys
|
||||
they are read from the request.
|
||||
+50
-6
@@ -52,6 +52,18 @@ cluster, a backup and adding a node change this machine or another over ssh;
|
||||
those close the screen and run in the terminal, so their output is there to
|
||||
read, and Enter brings the console back.
|
||||
|
||||
## Setting up
|
||||
|
||||
On a machine with nothing installed, the control plane is set up from one
|
||||
form (`sudo llmgw server init`): the administrator's email, other names nodes
|
||||
reach the machine by, and ticks for PostgreSQL, the model mirror, this machine
|
||||
as a node, the starter model and the guardrails' judge. **Offline bundle**
|
||||
and **Its sha256** are for a site with no internet: the path of a bundle made
|
||||
by `llmgw bundle create`, and the sha256 it printed. Given, the bundle goes
|
||||
into the mirror, every file checked, and the cluster is set up to fetch
|
||||
nothing from outside (install.md, "Offline sites"). A bundle with no sha256,
|
||||
or with the mirror unticked, is said in the form and nothing starts.
|
||||
|
||||
## Watch
|
||||
|
||||
**Overview** is `llmgw ctl status`: nodes, GPUs by class, fabrics, replicas,
|
||||
@@ -71,11 +83,18 @@ installs. **N** sends a test notification to each webhook in server.yaml's
|
||||
`notify` section and says how each answered (`llmgw ctl notify test`). A node's and a model's own pages have their charts too, over the
|
||||
same range.
|
||||
|
||||
**Nodes** lists every node with its state, load, GPUs, replicas, disk and
|
||||
agent version. On a row:
|
||||
**Nodes** lists every node with its state, where it is (its rack, or row,
|
||||
room or site, and PDUs), load, GPUs, replicas, disk and agent version. A node
|
||||
in a held rack reads *ready, held*. On a row:
|
||||
|
||||
- **Details** — its address, system, load, engines and GPUs, and any warning.
|
||||
- **Details** — its address, location and any hold, system, load, engines and
|
||||
GPUs, and any warning.
|
||||
- **Cordon** places nothing new on it; **Uncordon** undoes it.
|
||||
- **Location…** sets its site, room, row, rack and PDUs (the `llmgw.io/`
|
||||
labels), which placement spreads replicas across.
|
||||
- **Hold rack …** places nothing new in the node's rack, and can drain it;
|
||||
**Release …** on a node in a held domain undoes it. See
|
||||
[facility-aware-placement.md](facility-aware-placement.md).
|
||||
- **Drain** moves its replicas off one at a time, each replacement up before
|
||||
the original stops.
|
||||
- **vllm build / sglang build** (nodes with GPUs) — which build of the engine
|
||||
@@ -110,6 +129,23 @@ and **UPDATE** when the registry has new weights for it. On a row:
|
||||
**Go back to …** returns to the weights the update replaced.
|
||||
**Ask the registry for new weights now** checks without waiting for the
|
||||
next scheduled look (`mirror.update_check`, six hours by default).
|
||||
- **Try the new weights as a canary…** — instead of swapping them in, runs
|
||||
them beside the model as `MODEL-canary`, one replica, given the share of
|
||||
its requests you choose. With a canary running the menu has **Canary's
|
||||
share…**, **Promote the canary…** (the model moves to its weights, the
|
||||
canary is removed) and **Take the canary out…**. A canary that errs or
|
||||
answers more slowly than the model is taken out by itself. The MODEL
|
||||
column shows `(10% to canary)` and `(canary of …)`.
|
||||
- **Ask it a quality suite…** — one of the suites the control plane has (in
|
||||
`control.eval_dir`, or built in: `arithmetic`, `json-format`), asked
|
||||
through the router; the dialog counts the answers as they come in, then
|
||||
shows the score, each case and the model's last runs. Esc stops watching;
|
||||
the run carries on and is kept. **Its quality runs** lists them, as
|
||||
`llmgw ctl eval --history` does.
|
||||
- **Hold its updates to a quality suite…** — the suite and score its new
|
||||
weights must reach before an update or a promotion moves it to them
|
||||
(`llmgw ctl model gate`); **none** takes it away. With one set, **Update
|
||||
to …** and **Promote the canary…** say so.
|
||||
- **Why is it placed where it is** — `llmgw ctl explain-placement`.
|
||||
- **Try again**, for a model parked after failing every start.
|
||||
- **Remove** — its replicas stop and it leaves the catalog. A model from
|
||||
@@ -131,7 +167,10 @@ team or project is guaranteed and may at most hold, and what it holds now.
|
||||
**Mirror** is what the model mirror holds, one row for each version of each
|
||||
model — a file, or the set of files a model of several is: shards, a vision
|
||||
projector, a config and tokenizer — with how far its download has got and
|
||||
which models use it. **A** downloads a URL into it; on a row, its files with
|
||||
which models use it. **A** downloads a URL into it; **I** imports a model
|
||||
from an Ollama on this machine into a mirror directory on this machine — the
|
||||
mirror beside the control plane — and shows the model definition to add for
|
||||
it (a mirror elsewhere: `llmgw mirror import-ollama` there); on a row, its files with
|
||||
their checksums and where each was fetched from, the source a model
|
||||
definition names for it, or remove it — with a warning when a model still
|
||||
uses it.
|
||||
@@ -155,7 +194,8 @@ and change it with the same commands as `llmgw users`, `llmgw keys` and
|
||||
dashboard, and what they belong to. **A** creates an account, already
|
||||
approved. On a row: approve one waiting, suspend or reinstate, give or take
|
||||
the cluster dashboard, add to or take out of an organization, team or
|
||||
project, their limits, a new password (their sessions close), delete.
|
||||
project, their limits, a new password (their sessions close), delete, and
|
||||
**Forget them…** for a request to be forgotten (`llmgw users forget`).
|
||||
|
||||
**API keys** — every key, its project, owner, state and last use. **A**
|
||||
issues one; the key is shown once, in the result, and never again. On a row:
|
||||
@@ -185,7 +225,11 @@ with anything secret taken out. `llmgw ctl audit` is the same, with filters.
|
||||
projects, with members, keys and limits. **A** adds an organization. On a
|
||||
row: add a team or project inside it, rename, move, limits for the level and
|
||||
for each of its members, its capacity quota, and for a project how long
|
||||
conversations and agent notes are kept. **Longest key lifetime…** caps how
|
||||
conversations and agent notes are kept, and whether its requests are
|
||||
(**Keep requests…**: for how long, and what share), and whether they stay in
|
||||
the cluster (**Requests stay in the cluster…**: never an outside provider),
|
||||
and whether the same request is answered again from memory (**Cache
|
||||
answers…**: for how long, and whether only reproducible answers or any). **Longest key lifetime…** caps how
|
||||
long a key made there may live, and is the expiry of one made without any
|
||||
(`llmgw keys ttl`; `auth.max_key_ttl` in server.yaml caps every key).
|
||||
**Remove** takes away only something empty.
|
||||
|
||||
+109
-12
@@ -32,13 +32,22 @@ the text, the value that matched, or the placeholder map of a redaction. See
|
||||
**Usage records**, one per request: the key, the project, the model asked for,
|
||||
the model that answered, prompt and completion token counts, cost, HTTP status
|
||||
and latency. No message content. The row is in `internal/store/store.go` as
|
||||
`Usage` and there is no field for text in it.
|
||||
`Usage` and there is no field for text in it. What the client chose to say
|
||||
about the request is kept with it: OpenAI's `user` field and its `metadata`
|
||||
or `x-llmgw-tags` — short strings, set by the client, for attributing spend.
|
||||
A client that puts a person's name or address there puts it in the usage
|
||||
records; the field is the client's, and so is that choice. Tags are not sent
|
||||
on to the engine.
|
||||
|
||||
**API keys**, as SHA-256 hashes. The key itself is shown once, at creation, and
|
||||
never stored — so a leaked database hands over no working credential, and
|
||||
neither llmgw nor an administrator can recover a key somebody lost. A prefix is
|
||||
kept so a key can be identified in a listing without revealing it.
|
||||
|
||||
**The store's own secrets**, like the one engine keys are derived from, plain
|
||||
unless `secrets.master_key` seals them — with Vault's transit engine, so that
|
||||
neither the store nor its backups hold them.
|
||||
|
||||
**People and tenancy**: accounts, the organisation/team/project tree, and the
|
||||
limits attached to it. Passwords are hashed.
|
||||
|
||||
@@ -46,10 +55,32 @@ limits attached to it. Passwords are hashed.
|
||||
|
||||
**Conversations and agent notes** — only for a project that asked. See below.
|
||||
|
||||
**Kept requests** — only for a project that asked (`llmgw keys requests`):
|
||||
what each request sent the model, after the guardrails' redaction and with
|
||||
any stored conversation in it, and the answer the client got, for the hours
|
||||
it said, all of them or a share. Never under a `no_store` policy.
|
||||
|
||||
**Batch files** — when a client uses the Batch API: the file of requests it
|
||||
uploaded (prompts) and the files the batch wrote (answers), in the store,
|
||||
until deleted (`DELETE /v1/files/{id}`) or, for what a batch wrote, until
|
||||
`router.batch.retain_days` (30) pass. Only keys of the project that made
|
||||
them can read them, and a project under a `no_store` policy cannot make
|
||||
them.
|
||||
|
||||
**Reused answers** — only for a project that asked (`llmgw keys cache`):
|
||||
each answer that may be reused, as the client got it, and a hash of the
|
||||
request it answers, in the gateway process's memory — never in the store,
|
||||
never on disk — for the project's TTL or until pushed out by newer ones
|
||||
(`router.cache.max_bytes`), and gone with a restart. Never under a `no_store`
|
||||
policy. Forgetting a person does not reach into it; the answers age out by
|
||||
the TTL. The store keeps only the setting, and a usage record's mark that it
|
||||
was answered from the cache.
|
||||
|
||||
## What is not stored
|
||||
|
||||
Prompts. Completions. Anything the model was shown or produced, unless the
|
||||
project turned on conversations or notes.
|
||||
project turned on conversations, notes or kept requests, or sent a batch.
|
||||
(Reused answers are held in memory only, as above.)
|
||||
|
||||
The chat page in llmgw's own web interface keeps the conversation in a
|
||||
JavaScript variable in the browser. Refresh it and the conversation is gone,
|
||||
@@ -95,22 +126,62 @@ your own hardware, and the answer comes back. The router talks to engines, the
|
||||
engines talk to nothing, the agents talk to the control plane. All of it is
|
||||
inside the cluster.
|
||||
|
||||
Two things can reach outside, both started by an operator rather than by a
|
||||
request:
|
||||
Around the serving path, a cluster set up the ordinary way does reach out.
|
||||
None of it carries a prompt, an answer, a key or a user — it is software and
|
||||
public model files coming in — but a review should know each one:
|
||||
|
||||
**Fetching weights.** When a model's `source` is a URL, the agent downloads it.
|
||||
Point that at an internal mirror and nothing leaves at all — which is also the
|
||||
**Installing engines.** Each node's agent downloads the llama.cpp build for its
|
||||
hardware from GitHub, checked against the checksum GitHub publishes, and vLLM
|
||||
(SGLang when asked) from PyPI, with `uv` from GitHub. On every node, when it
|
||||
joins and when the engine version changes.
|
||||
|
||||
**Releases.** `llmgw node add`, `llmgw ctl upgrade` and `llmgw upgrade` fetch
|
||||
llmgw's own release binaries from the project's release server, checked against
|
||||
its signed checksums.
|
||||
|
||||
**Fetching weights.** When a model's `source` is a URL, the agent downloads it;
|
||||
the mirror fetches what it is asked to, from Hugging Face or another URL, and
|
||||
`server init` has it fetch the starter model and the guardrails' judge. Point
|
||||
sources at the mirror and the nodes fetch only from it — which is also the
|
||||
faster arrangement, because eight nodes pulling forty gigabytes from the
|
||||
internet is a day's work and from a local mirror it is minutes. A `source` that
|
||||
is a path on disk is never fetched.
|
||||
|
||||
**`llmgw ctl plan`.** Reads a model's architecture from huggingface.co to work
|
||||
out whether it fits your hardware. An operator command run at planning time,
|
||||
not part of serving, and not run by anything automatically.
|
||||
**The registry.** With a mirror configured, the control plane asks Hugging Face
|
||||
every six hours whether the models served from it have newer files
|
||||
(`mirror.update_check`), and `/admin/mirror` searches it. `llmgw ctl plan`
|
||||
reads a model's architecture from huggingface.co to work out whether it fits
|
||||
your hardware.
|
||||
|
||||
There is no telemetry, no licence check, and no call home. The binary is
|
||||
static, built with `CGO_ENABLED=0`, and runs in a network with no route to the
|
||||
internet as long as the weights are already on disk.
|
||||
There is no telemetry, no licence check, and no call home.
|
||||
|
||||
### A cluster with no way out
|
||||
|
||||
A site with no route to the internet installs from an **offline bundle**
|
||||
instead, and then nothing at all leaves the cluster (docs/install.md, "Offline
|
||||
sites"). The bundle is made on a machine that has internet — llmgw's release
|
||||
binaries with their signed checksums, the llama.cpp builds with the checksums
|
||||
GitHub publishes, the model files with the checksums Hugging Face publishes,
|
||||
each checked as it is downloaded — carried in, and imported into the mirror.
|
||||
With `offline.mirror` set in `server.yaml`, nodes install engines from the
|
||||
mirror and never from GitHub, releases come from the mirror, and the registry
|
||||
is not asked about newer weights.
|
||||
|
||||
Verification is not weakened by any of this. A release is held to the project's
|
||||
signing key wherever it is fetched from. An engine file is held to the checksum
|
||||
recorded when the bundle was made, which the control plane keeps and hands each
|
||||
node over the agent's authenticated connection: the mirror serves plain HTTP,
|
||||
and nothing a node runs is taken on the mirror's word. The bundle itself is
|
||||
checked against the sha256 its maker printed, carried to the site apart from
|
||||
the bundle.
|
||||
|
||||
What does not come in a bundle: vLLM and SGLang, which are Python environments
|
||||
from PyPI — an offline node serves with llama.cpp unless one is installed on it
|
||||
by hand — and the operating system's own packages (the OpenMP runtime the
|
||||
engine needs, PostgreSQL when chosen), which come from the machines' package
|
||||
sources: at an offline site, the distribution mirror it already has. Searching
|
||||
the registry from `/admin/mirror` and `llmgw ctl plan` need the internet and
|
||||
do not work offline; `mirror.registry` can point the first at an internal copy.
|
||||
|
||||
## What the software cannot do for you
|
||||
|
||||
@@ -140,3 +211,29 @@ touch, whatever the catalog says.
|
||||
| Scope is part of the lookup | `internal/store/threads.go`, `Thread` |
|
||||
| Deletion is a client endpoint | `internal/router/threads.go`, `handleDeleteThread` |
|
||||
| Weight fetching is the only serving-path egress | `internal/agent/weights/fetch.go` |
|
||||
|
||||
## Forgetting a person
|
||||
|
||||
`llmgw users forget <email> --yes` (or **Forget them…** in the console) is for
|
||||
a request to be forgotten:
|
||||
|
||||
- their usage — every request record and every sum — is kept, so totals and
|
||||
budgets stay true, but under a random pseudonym that links to nothing;
|
||||
- their kept requests (`keys requests`), personal files and batches, and
|
||||
their own limits are deleted;
|
||||
- their email and id are taken out of the audit log, which keeps what was
|
||||
done;
|
||||
- then the account goes, as `users delete` removes it: sessions ended, keys
|
||||
revoked and left without an owner.
|
||||
|
||||
Conversations and agent notes belong to projects, not to the people in them,
|
||||
and are not touched: a project forgets them by its retention, and a thread by
|
||||
`DELETE /v1/threads/{id}`. Backups taken before still hold everything until
|
||||
they age out; that is what their retention is for.
|
||||
|
||||
## Keeping a project's requests in the cluster
|
||||
|
||||
`llmgw keys residency --project <path> --in-cluster` refuses the project's
|
||||
keys any model served by an outside provider, and never uses one for them as
|
||||
a fallback or a canary: their prompts do not leave the machines the cluster
|
||||
runs on. `--anywhere` lifts it.
|
||||
@@ -1,13 +1,109 @@
|
||||
# Facility-aware placement: rack power, temperature and cooling
|
||||
|
||||
**Status: step 0, reading the nodes' own sensors, is built; steps 1–5 are
|
||||
deferred** until the rack, PDU and power information of a real site is at
|
||||
hand — without it they would be designed against guesses.
|
||||
This is the design for step 5 of resource allocation, after reserved CPU cores
|
||||
and memory (1), capacity classes and preemption (2), tenant capacity quotas (3)
|
||||
and sizing by measured throughput (4), all of which shipped in v0.10.5. Of
|
||||
what follows, only the node sensors (rollout step 0) exist in the code: they
|
||||
are read, published and shown, and change no decision.
|
||||
**Status: steps 0, 1 and 2 are built, with the manual hold of step 4;
|
||||
temperature conditions (steps 3 and 4) and shedding (step 5) are not**,
|
||||
until the thermal data of a real site is at hand — without it thresholds would
|
||||
be designed against guesses. This is the design for step 5 of resource
|
||||
allocation, after reserved CPU cores and memory (1), capacity classes and
|
||||
preemption (2), tenant capacity quotas (3) and sizing by measured throughput
|
||||
(4). [What is built](#what-is-built) says what works today and where it
|
||||
departs from the design below; the rest of the document is the design.
|
||||
|
||||
## What is built
|
||||
|
||||
**Where a node is.** Five labels: `llmgw.io/site`, `room`, `row`, `rack` and
|
||||
`pdu` (a comma separated list, for a dual-fed rack). They come from the node's
|
||||
`agent.yaml` under `labels:`, or from the control plane:
|
||||
|
||||
```
|
||||
llmgw ctl label gpu01 llmgw.io/rack=r12-07 llmgw.io/pdu=r12-07-a,r12-07-b
|
||||
llmgw ctl label gpu01 llmgw.io/rack- # back to agent.yaml's value, if any
|
||||
```
|
||||
|
||||
Labels set with `ctl label` are kept in the store, win over the agent's, and
|
||||
may be set before the node joins. A misspelt `llmgw.io/` key is refused. A
|
||||
domain is named `level:name` — `rack:r12-07`, `pdu:r12-07-a` — and names are
|
||||
taken as given, so two rooms that both have a rack `r1` must label them apart.
|
||||
A node without location labels is in no domain and places as it always did.
|
||||
|
||||
**Spreading.** A model's next replica goes first to a node sharing no rack and
|
||||
no PDU with the nodes the model already runs on; nodes sharing fewer come
|
||||
before nodes sharing more. It is an ordering, never a filter: a rack holding
|
||||
the only free cards still takes the replica. It ranks above preferring a node
|
||||
that already holds the weights — a second replica one breaker away from the
|
||||
first is worth less than the copy saved — and above bin packing.
|
||||
|
||||
**Keeping a replica together.** A profile's `keep_within: rack` (or `row`,
|
||||
`room`, `site`) keeps a multi-node replica's nodes in one such domain, inside
|
||||
the fabric or NVLink domain placement already requires; nodes without the
|
||||
label are passed over for it, with the reason.
|
||||
|
||||
**Holds.** `llmgw ctl facility hold rack:r12-07 --reason "PDU swap"` places
|
||||
nothing new in the domain, as a cordon of each of its nodes would, including
|
||||
nodes labelled into it later. `--drain` also drains its nodes, one replica at
|
||||
a time with the replacement up first; `llmgw ctl facility release` undoes
|
||||
both. Holds are kept in the store across restarts (the drain itself is node
|
||||
state, which is not: after a restart the hold still keeps work out, and
|
||||
replicas not yet moved stay where they are). Any domain can be held: a PDU
|
||||
holds every rack on it.
|
||||
|
||||
**Power budgets.** In `server.yaml`:
|
||||
|
||||
```yaml
|
||||
facility:
|
||||
margin: 0.1 # share of every cap kept free
|
||||
gpu_watts: 700 # a card that reports no power limit
|
||||
cpu_core_watts: 10 # a core reserved by a CPU replica (cpu_cores)
|
||||
node_watts: 350 # each node's own draw beyond its cards
|
||||
budgets:
|
||||
- domain: rack:r12-07
|
||||
cap_watts: 16000 # what one feed carries alone, derated
|
||||
other_watts: 800 # switches, storage
|
||||
- domain: pdu:r12-07-a
|
||||
cap_watts: 7400
|
||||
```
|
||||
|
||||
A replica's draw is the profile's `power_watts` (split over its nodes) when
|
||||
declared; otherwise each card at the power limit it reports through the agent's
|
||||
sensors (or `gpu_watts`), and each reserved core at `cpu_core_watts`. A
|
||||
domain's use is, node by node, `node_watts` plus the larger of what is placed
|
||||
there and what the node's sensors read in the last two minutes
|
||||
(`measured_fresh`), plus the domain's `other_watts`. A shard that would take
|
||||
any of its node's domains past `cap × (1 − margin)` is refused; a multi-node
|
||||
replica's shards are counted together, so two that each fit a rack alone do not
|
||||
both go into it. A draw nobody knows — no declared figure, no card limit, no
|
||||
`gpu_watts` — counts as nothing: missing data never blocks.
|
||||
|
||||
**What people see.** `llmgw ctl explain-placement` names the domain: *rack
|
||||
r12-07 is held: PDU swap*, *rack r12-07: 14.2 kW of a 14.4 kW limit (16.0 kW
|
||||
cap less 10%) in use, the shard needs ~2.8 kW*. The rejections of a placed
|
||||
replica are kept too, so a replica in an unexpected rack says why. `llmgw ctl
|
||||
nodes` has a LOCATION column, shows *ready, held*, and filters with `--domain
|
||||
rack:r12-07`. `llmgw ctl facility` lists every domain with its nodes, use,
|
||||
limit, reserved and measured draw, and holds. The console's Nodes view has a
|
||||
WHERE column; a node's page shows its location and hold, and its menu sets
|
||||
the location (**Location…**) and holds or releases its rack. The admin API:
|
||||
`GET /api/v1/facility`, `POST /api/v1/facility/holds`, `DELETE
|
||||
/api/v1/facility/holds/{domain}`, `POST /api/v1/nodes/{id}/labels`.
|
||||
|
||||
**Where it departs from the design below, and why.**
|
||||
|
||||
- Domains come from labels alone; there is no facility file declaring them.
|
||||
Budgets are in `server.yaml`, the one file the control plane already reads.
|
||||
A DCIM export would generate that block.
|
||||
- Feeds are not modelled. The cap given is what one feed carries alone,
|
||||
derated — the figure the design says matters — so the operator gives the
|
||||
one number instead of llmgw deriving it from two.
|
||||
- The manual hold of step 4 is built now, without conditions: it needs no
|
||||
sensor data and answers the commonest facility event, planned maintenance.
|
||||
Its command is `ctl facility hold`, with a `--drain` the design did not have.
|
||||
- `keep_within` is new: the request that a multi-node replica stay in one rack
|
||||
where the cabling requires it.
|
||||
- Spreading is an ordering of candidates, not the scoring of the design; power
|
||||
headroom does not yet order racks ("level load across racks"), and
|
||||
multi-node replicas are not spread across racks.
|
||||
- No `llmgw_domain_*` metrics or alerts yet; `ctl facility` and the API carry
|
||||
the same figures.
|
||||
|
||||
## Why
|
||||
|
||||
@@ -260,16 +356,17 @@ Each step ships on its own and is useful without the next:
|
||||
0. **Node sensors, observe-only (built).** GPU heat, power and throttling,
|
||||
CPU heat and power, inlet air where the board has a sensor; published and
|
||||
shown, no decision changed.
|
||||
1. **Location and spreading.** Well-known labels, domains from labels, replicas
|
||||
1. **Location and spreading (built).** Well-known labels, domains from labels, replicas
|
||||
spread across racks and PDUs, locations on the node views. No facility data
|
||||
needed.
|
||||
2. **Power budgets from a static file.** Caps and margins, estimated draw per
|
||||
2. **Power budgets from a static file (built, without headroom
|
||||
scoring).** Caps and margins, estimated draw per
|
||||
replica (declared or derived), hard limit in placement and headroom.
|
||||
3. **Readings, observe-only.** The Prometheus source beside the agents',
|
||||
conditions with hysteresis (throttling first among them), measured power
|
||||
folded into headroom; decisions shown, not enforced.
|
||||
4. **Thermal enforcement.** `warm` scored down, `hot` refused, manual hold and
|
||||
release.
|
||||
4. **Thermal enforcement.** `warm` scored down, `hot` refused; the manual hold
|
||||
and release are built.
|
||||
5. **Shedding and tokens per watt.** Opt-in shedding through step 2's
|
||||
preemption; measured power in profile preference.
|
||||
|
||||
|
||||
+1022
-24
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,228 @@
|
||||
# llmgw and Kubernetes
|
||||
|
||||
The control plane runs in Kubernetes, from the Helm chart in
|
||||
`deploy/helm/llmgw`. The GPU nodes do not: they stay ordinary machines,
|
||||
joined with `llmgw node add` as on any other cluster. This page says why,
|
||||
and how the two meet.
|
||||
|
||||
## What goes where
|
||||
|
||||
| Part | Where | Why |
|
||||
|---|---|---|
|
||||
| Control plane: the API on 8080, the agents' port 7443, the scheduler | A StatefulSet, from the chart | A Go binary with a store and three ports: what Kubernetes runs well |
|
||||
| Store | A file on a PersistentVolumeClaim (SQLite), or your PostgreSQL | Either, as on a host |
|
||||
| GPU and CPU nodes | Outside, as hosts | See below |
|
||||
| Model mirror | Outside, on a machine with a large disk | Every node pulls tens of gigabytes from it over plain HTTP; a pod with a volume that size is a host in all but name |
|
||||
|
||||
### Why the nodes stay outside
|
||||
|
||||
The agent on a node is not a service that happens to use a GPU. It installs
|
||||
the engines on the machine — the llama.cpp build for its driver, vLLM in a
|
||||
Python environment — checks them against their publisher's checksums and
|
||||
runs them; it chooses which GPUs each replica gets, by index and by NVLink
|
||||
topology; it starts engines as processes that outlive its own restarts, so a
|
||||
node upgrades while it serves; it writes the machine's firewall; and it
|
||||
replaces its own binary when the cluster upgrades. All of that is root on
|
||||
the host, which is exactly what a container is built to prevent.
|
||||
|
||||
Run as a DaemonSet it would need to be privileged, with the host's network,
|
||||
process namespace and filesystem, and the NVIDIA device plugin would have to
|
||||
be kept off its GPUs — or the two would hand the same card to two owners.
|
||||
What is left is the host agent with a container's indirection around it, and
|
||||
none of the scheduling, isolation or restart guarantees that make a pod
|
||||
worth having. So the chart does not ship one, and this is the
|
||||
recommendation:
|
||||
|
||||
- **Keep GPU machines out of Kubernetes**, and add them with `node add`.
|
||||
- **If they are already Kubernetes workers**, dedicate them: taint them so
|
||||
no other pod lands there, keep the NVIDIA device plugin off them (most
|
||||
installs select nodes by label — leave the label off), and run the llmgw
|
||||
agent on the host, where `node add` puts it. llmgw then owns the GPUs, and
|
||||
Kubernetes schedules nothing that would want them.
|
||||
|
||||
## The image
|
||||
|
||||
The project publishes binaries, not an image. Build one from the repository
|
||||
and push it where the cluster pulls from — at an offline site, the internal
|
||||
registry:
|
||||
|
||||
```
|
||||
docker build -f deploy/container/Dockerfile --build-arg VERSION=v0.11.1 \
|
||||
-t registry.internal/llmgw:v0.11.1 .
|
||||
docker push registry.internal/llmgw:v0.11.1
|
||||
```
|
||||
|
||||
It is the static binary on a distroless base: no shell, running as user
|
||||
65532, with a read-only root filesystem in the pod.
|
||||
|
||||
## The agent port's certificate
|
||||
|
||||
Agents and the control plane authenticate each other with certificates from
|
||||
llmgw's own authority, and the TLS ends in the pod — so the authority's key
|
||||
stays outside the cluster, on the machine you will add nodes from, and the
|
||||
pod is given only its own certificate.
|
||||
|
||||
Decide first the address agents will dial: the `-agents` Service is a
|
||||
LoadBalancer, so give it a fixed `agentService.loadBalancerIP` or a DNS name
|
||||
that points at it. That address has to be in the certificate:
|
||||
|
||||
```
|
||||
llmgw ctl cert init-ca --dir ./pki
|
||||
llmgw ctl cert issue-server llmgw-ctl --host 10.0.0.200 --host llmgw-agents.example.com \
|
||||
--dir ./pki --out ./pki
|
||||
kubectl -n llmgw create secret generic llmgw-agent-tls \
|
||||
--from-file=ca.pem=pki/ca.pem \
|
||||
--from-file=server.pem=pki/server.pem \
|
||||
--from-file=server-key.pem=pki/server-key.pem
|
||||
```
|
||||
|
||||
Keep `pki/ca-key.pem` as you would on a host: whoever holds it can make any
|
||||
node's identity.
|
||||
|
||||
## Installing
|
||||
|
||||
```yaml
|
||||
# values.yaml
|
||||
image:
|
||||
repository: registry.internal/llmgw
|
||||
tag: v0.11.1
|
||||
agentTLS:
|
||||
existingSecret: llmgw-agent-tls
|
||||
agentService:
|
||||
loadBalancerIP: 10.0.0.200
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
hosts: [{host: llm.example.com, paths: [{path: /, pathType: Prefix}]}]
|
||||
tls: [{secretName: llm-example-com, hosts: [llm.example.com]}]
|
||||
config:
|
||||
mirror:
|
||||
api: http://models.internal:8082
|
||||
# The address the router reaches nodes' engines from is a Kubernetes
|
||||
# node's, once the pod's traffic leaves the cluster: the nodes' firewalls
|
||||
# must let it in.
|
||||
firewall_networks: ["10.0.1.0/24"]
|
||||
```
|
||||
|
||||
```
|
||||
helm install llmgw deploy/helm/llmgw -n llmgw -f values.yaml
|
||||
```
|
||||
|
||||
`config` is `server.yaml`: any key of [reference.md](reference.md), laid
|
||||
under what the chart sets itself — the listeners, where the certificates,
|
||||
the admin token and the store are mounted. A changed `config` restarts the
|
||||
pod.
|
||||
|
||||
**The store.** By default SQLite, on a 10 GiB claim. For PostgreSQL, put its
|
||||
address in a Secret and point the chart at it:
|
||||
|
||||
```
|
||||
kubectl -n llmgw create secret generic llmgw-store \
|
||||
--from-literal=dsn='postgres://llmgw:…@pg.internal:5432/llmgw?sslmode=verify-full'
|
||||
```
|
||||
|
||||
```yaml
|
||||
store:
|
||||
type: postgres
|
||||
postgres:
|
||||
existingSecret: llmgw-store
|
||||
```
|
||||
|
||||
**One control plane.** The chart runs one replica. Two against PostgreSQL
|
||||
would elect a leader and keep a standby, but a standby serves nothing and is
|
||||
never ready, so a StatefulSet rollout would wait on it for ever. Kubernetes
|
||||
replaces the one pod within seconds when it goes, and agents reconnect on
|
||||
their own; the replicas on the nodes keep serving meanwhile.
|
||||
|
||||
**Probes.** Alive is `/health`. Ready is `/leader`, which on PostgreSQL waits
|
||||
for the lease of the pod it replaced to run out — not `/ready`, which waits
|
||||
for a model replica, and would keep a cluster with no node yet from ever
|
||||
accepting one.
|
||||
|
||||
**Monitoring.** The metrics port, 9091, serves metrics and nothing else;
|
||||
`serviceMonitor.enabled: true` makes a ServiceMonitor for the Prometheus
|
||||
Operator, and `deploy/monitoring` holds the rules and dashboards.
|
||||
|
||||
## Using it
|
||||
|
||||
The admin API listens on the pod's loopback, as on a host — it can dump keys
|
||||
from the heap when profiling is on. Reach it through the pod:
|
||||
|
||||
```
|
||||
kubectl -n llmgw exec -it statefulset/llmgw -- llmgw users create you@example.com --password '…'
|
||||
kubectl -n llmgw exec -it statefulset/llmgw -- llmgw users role you@example.com admin
|
||||
kubectl -n llmgw exec -it statefulset/llmgw -- llmgw ctl status
|
||||
```
|
||||
|
||||
or from your machine, through a port-forward:
|
||||
|
||||
```
|
||||
kubectl -n llmgw port-forward statefulset/llmgw 9090:9090 &
|
||||
export LLMGW_ADMIN_TOKEN=$(kubectl -n llmgw get secret llmgw-admin -o jsonpath='{.data.admin-token}' | base64 -d)
|
||||
llmgw ctl status
|
||||
```
|
||||
|
||||
The token is made by the chart and kept across upgrades
|
||||
(`adminToken.existingSecret` brings your own).
|
||||
|
||||
## Adding nodes
|
||||
|
||||
From the machine holding `pki/`, with the port-forward above running and
|
||||
`LLMGW_ADMIN_TOKEN` set:
|
||||
|
||||
```
|
||||
sudo -E llmgw node add ubuntu@gpu01 \
|
||||
--server https://10.0.0.200:7443 --pki ./pki --admin 127.0.0.1:9090
|
||||
```
|
||||
|
||||
`--server` is the address in the certificate. The node is installed, checked
|
||||
and started over ssh exactly as on any cluster ([node-onboarding.md](node-onboarding.md)),
|
||||
and dials the control plane in the pod. Its firewall comes from
|
||||
`firewall_networks` in the server configuration `node add` reads (`--config`,
|
||||
`/etc/llmgw/server.yaml` by default): copy the chart's out of the cluster
|
||||
first, or give `--no-firewall` and keep the engines' ports open to the
|
||||
Kubernetes nodes by hand.
|
||||
|
||||
```
|
||||
kubectl -n llmgw get configmap llmgw -o jsonpath='{.data.server\.yaml}' > server.yaml
|
||||
sudo -E llmgw node add ubuntu@gpu01 --config ./server.yaml --server https://10.0.0.200:7443 \
|
||||
--pki ./pki --admin 127.0.0.1:9090
|
||||
```
|
||||
|
||||
## Offline
|
||||
|
||||
An offline site ([install.md](install.md), "Offline sites") works the same
|
||||
way with the control plane in a pod. Import the bundle on the mirror's
|
||||
machine with `llmgw bundle import`, record its engines' checksums in a
|
||||
file, and give that file to the chart as a ConfigMap:
|
||||
|
||||
```
|
||||
llmgw bundle trust llmgw-bundle.tar --sha256 3f2a… --file ./offline.sha256
|
||||
kubectl -n llmgw create configmap llmgw-offline --from-file=offline.sha256
|
||||
```
|
||||
|
||||
```yaml
|
||||
offlineChecksums:
|
||||
configMap: llmgw-offline
|
||||
config:
|
||||
offline:
|
||||
mirror: http://models.internal:8081
|
||||
```
|
||||
|
||||
A later bundle: `bundle trust` into the same file, and replace the ConfigMap
|
||||
(`kubectl create configmap … --dry-run=client -o yaml | kubectl apply -f -`).
|
||||
The control plane reads the file again when it changes; there is no restart.
|
||||
|
||||
## What has and has not been tried
|
||||
|
||||
The chart is checked with `helm lint` and `helm template` for SQLite,
|
||||
PostgreSQL, an Ingress, a ServiceMonitor and an offline cluster, and refuses
|
||||
what would not work — no image, no certificate, a PostgreSQL store without
|
||||
its address, more than one replica. The image has been run the way the
|
||||
chart runs it — read-only root, user 65532, the same files mounted at the
|
||||
same paths, SQLite on a volume — and answered `/health`, `/leader` and
|
||||
`/metrics`, with `llmgw ctl` and `llmgw users` working through `exec`.
|
||||
|
||||
It has **not** been installed on a Kubernetes cluster, and no node has yet
|
||||
joined a control plane running in one. Until it has, a control plane on a
|
||||
host is the well-trodden path.
|
||||
@@ -65,6 +65,11 @@ model already in it:
|
||||
Responses API, which the gateway translates at `/v1/responses`.
|
||||
- **Cline** — four settings to paste into its own screen, since it keeps them
|
||||
in VS Code's secret storage where no file reaches.
|
||||
- **Claude Code** — not on the page yet; it speaks Anthropic's Messages API,
|
||||
which the gateway translates at `/v1/messages`:
|
||||
`ANTHROPIC_BASE_URL=https://<gateway> ANTHROPIC_AUTH_TOKEN=<key>
|
||||
ANTHROPIC_MODEL=<model> ANTHROPIC_SMALL_FAST_MODEL=<model> claude`. It
|
||||
needs a model that calls tools well.
|
||||
|
||||
For Continue and Codex there is a one-line command,
|
||||
`curl -fsSL <gateway>/setup/<tool>?model=… | sh`. Its script is served without
|
||||
@@ -304,6 +309,28 @@ shown as text. Other schemes are never linked — configuration is not always
|
||||
written by whoever runs the gateway, and a `javascript:` href on a page served to
|
||||
every visitor is a short path to a stored XSS.
|
||||
|
||||
## The docs portal
|
||||
|
||||
The gateway also serves its manual at `/docs`: these pages, rendered, with
|
||||
[clients.md](clients.md) — how to use the gateway from the official OpenAI
|
||||
and Anthropic SDKs — first on its index. The landing page and the account
|
||||
page link to it, so a user's questions about streaming, tools or the Anthropic
|
||||
SDK have an answer that is not you.
|
||||
|
||||
It is public, like the landing page. The client guide is for the person who
|
||||
has no account yet, and the operator documents describe llmgw in general —
|
||||
no address, model, node or key of this installation — which is what the
|
||||
project's repository publishes anyway. A site that would rather not say even
|
||||
that turns sign-in on:
|
||||
|
||||
```yaml
|
||||
landing:
|
||||
docs_sign_in: true
|
||||
```
|
||||
|
||||
A visitor is then sent to sign in first. On a gateway with API keys and no
|
||||
accounts, the portal asks for a key instead, like the API.
|
||||
|
||||
## What the user sees
|
||||
|
||||
They open the link, press the button, and get the key once. The page shows them
|
||||
|
||||
+677
-9
@@ -43,6 +43,17 @@ rather than repeated.
|
||||
| `batch_size` | `int` | [Auth](#auth) |
|
||||
| `buffer_size` | `int` | [Auth](#auth) |
|
||||
| `usage_retention` | `time.Duration` | [Auth](#auth) |
|
||||
| `max_file_bytes` | `int64` | [Batch](#batch) |
|
||||
| `max_lines` | `int` | [Batch](#batch) |
|
||||
| `concurrency` | `int` | [Batch](#batch) |
|
||||
| `retain_days` | `int` | [Batch](#batch) |
|
||||
| `max_bytes` | `int64` | [Cache](#cache) |
|
||||
| `max_entry_bytes` | `int64` | [Cache](#cache) |
|
||||
| `model` | `string` | [Canary](#canary) |
|
||||
| `percent` | `int` | [Canary](#canary) |
|
||||
| `min_requests` | `int` | [Canary](#canary) |
|
||||
| `max_error_increase` | `float64` | [Canary](#canary) |
|
||||
| `max_ttft_ratio` | `float64` | [Canary](#canary) |
|
||||
| `tools` | `bool` | [Capabilities](#capabilities) |
|
||||
| `vision` | `bool` | [Capabilities](#capabilities) |
|
||||
| `embeddings` | `bool` | [Capabilities](#capabilities) |
|
||||
@@ -53,6 +64,8 @@ rather than repeated.
|
||||
| `lost_after` | `time.Duration` | [Control](#control) |
|
||||
| `port_range` | `[]int` | [Control](#control) |
|
||||
| `mgmt_interface` | `string` | [Control](#control) |
|
||||
| `timezone` | `string` | [Control](#control) |
|
||||
| `eval_dir` | `string` | [Control](#control) |
|
||||
| `enabled` | `bool` | [Control](#control) |
|
||||
| `lease_ttl` | `time.Duration` | [Control](#control) |
|
||||
| `id` | `string` | [Endpoint](#endpoint) |
|
||||
@@ -67,9 +80,24 @@ rather than repeated.
|
||||
| `nodes` | `[]string` | [EngineOverride](#engineoverride) |
|
||||
| `labels` | `map[string]string` | [EngineOverride](#engineoverride) |
|
||||
| `engines` | `map[string]string` | [EngineOverride](#engineoverride) |
|
||||
| `suite` | `string` | [EvalGate](#evalgate) |
|
||||
| `min_score` | `float64` | [EvalGate](#evalgate) |
|
||||
| `judge` | `string` | [EvalGate](#evalgate) |
|
||||
| `url` | `string` | [External](#external) |
|
||||
| `model` | `string` | [External](#external) |
|
||||
| `api_key_file` | `string` | [External](#external) |
|
||||
| `peer` | `string` | [External](#external) |
|
||||
| `budgets` | `[]FacilityBudget` | [Facility](#facility) |
|
||||
| `margin` | `float64` | [Facility](#facility) |
|
||||
| `gpu_watts` | `float64` | [Facility](#facility) |
|
||||
| `cpu_core_watts` | `float64` | [Facility](#facility) |
|
||||
| `node_watts` | `float64` | [Facility](#facility) |
|
||||
| `measured_fresh` | `time.Duration` | [Facility](#facility) |
|
||||
| `domain` | `string` | [FacilityBudget](#facilitybudget) |
|
||||
| `cap_watts` | `float64` | [FacilityBudget](#facilitybudget) |
|
||||
| `other_watts` | `float64` | [FacilityBudget](#facilitybudget) |
|
||||
| `name` | `string` | [Federation](#federation) |
|
||||
| `interval` | `time.Duration` | [Federation](#federation) |
|
||||
| `format` | `string` | [GuardModel](#guardmodel) |
|
||||
| `categories` | `[]string` | [GuardModel](#guardmodel) |
|
||||
| `model` | `string` | [JudgePolicy](#judgepolicy) |
|
||||
@@ -77,8 +105,13 @@ rather than repeated.
|
||||
| `output` | `string` | [JudgePolicy](#judgepolicy) |
|
||||
| `categories` | `[]string` | [JudgePolicy](#judgepolicy) |
|
||||
| `latency_budget` | `time.Duration` | [JudgePolicy](#judgepolicy) |
|
||||
| `tokenize_timeout` | `time.Duration` | [KVIndex](#kvindex) |
|
||||
| `min_blocks` | `int` | [KVIndex](#kvindex) |
|
||||
| `max_blocks` | `int` | [KVIndex](#kvindex) |
|
||||
| `contact` | `string` | [Landing](#landing) |
|
||||
| `notice` | `string` | [Landing](#landing) |
|
||||
| `language` | `string` | [Landing](#landing) |
|
||||
| `docs_sign_in` | `bool` | [Landing](#landing) |
|
||||
| `bin` | `string` | [LlamaCppConfig](#llamacppconfig) |
|
||||
| `parallel` | `int` | [LlamaCppConfig](#llamacppconfig) |
|
||||
| `threads` | `int` | [LlamaCppConfig](#llamacppconfig) |
|
||||
@@ -97,7 +130,10 @@ rather than repeated.
|
||||
| `owner` | `string` | [Model](#model) |
|
||||
| `external` | `*External` | [Model](#model) |
|
||||
| `adapters` | `[]Adapter` | [Model](#model) |
|
||||
| `max_loaded_adapters` | `int` | [Model](#model) |
|
||||
| `fallbacks` | `[]string` | [Model](#model) |
|
||||
| `canary` | `*Canary` | [Model](#model) |
|
||||
| `eval` | `*EvalGate` | [Model](#model) |
|
||||
| `routing_profile` | `string` | [Model](#model) |
|
||||
| `slo` | `SLO` | [Model](#model) |
|
||||
| `context_length` | `int` | [Model](#model) |
|
||||
@@ -120,6 +156,8 @@ rather than repeated.
|
||||
| `roles` | `map[string][]string` | [OIDC](#oidc) |
|
||||
| `memberships` | `map[string]string` | [OIDC](#oidc) |
|
||||
| `no_passwords` | `bool` | [OIDC](#oidc) |
|
||||
| `mirror` | `string` | [Offline](#offline) |
|
||||
| `checksums` | `string` | [Offline](#offline) |
|
||||
| `nvidia_smi` | `string` | [Options](#options) |
|
||||
| `ib_root` | `string` | [Options](#options) |
|
||||
| `prefer_nvml` | `bool` | [Options](#options) |
|
||||
@@ -175,9 +213,12 @@ rather than repeated.
|
||||
| `cpu_cores` | `int` | [Profile](#profile) |
|
||||
| `min_disk_gb` | `int` | [Profile](#profile) |
|
||||
| `node_selector` | `map[string]string` | [Profile](#profile) |
|
||||
| `power_watts` | `float64` | [Profile](#profile) |
|
||||
| `keep_within` | `string` | [Profile](#profile) |
|
||||
| `weight` | `float64` | [Profile](#profile) |
|
||||
| `priority` | `int` | [Profile](#profile) |
|
||||
| `startup_timeout` | `time.Duration` | [Profile](#profile) |
|
||||
| `kv_events` | `bool` | [Profile](#profile) |
|
||||
| `activation_wait` | `time.Duration` | [Router](#router) |
|
||||
| `scrape_interval` | `time.Duration` | [Router](#router) |
|
||||
| `scrape_timeout` | `time.Duration` | [Router](#router) |
|
||||
@@ -187,10 +228,14 @@ rather than repeated.
|
||||
| `failure_threshold` | `int` | [Router](#router) |
|
||||
| `default_profile` | `string` | [Router](#router) |
|
||||
| `prefix` | `Prefix` | [Router](#router) |
|
||||
| `kv_index` | `KVIndex` | [Router](#router) |
|
||||
| `session_header` | `string` | [Router](#router) |
|
||||
| `inject_usage` | `bool` | [Router](#router) |
|
||||
| `tenant_label` | `string` | [Router](#router) |
|
||||
| `tag_labels` | `[]string` | [Router](#router) |
|
||||
| `max_body_bytes` | `int64` | [Router](#router) |
|
||||
| `batch` | `Batch` | [Router](#router) |
|
||||
| `cache` | `Cache` | [Router](#router) |
|
||||
| `trusted_proxies` | `[]string` | [Router](#router) |
|
||||
| `timeouts` | `Timeouts` | [Router](#router) |
|
||||
| `scoring` | `Scoring` | [Router](#router) |
|
||||
@@ -203,13 +248,22 @@ rather than repeated.
|
||||
| `python` | `string` | [SGLangConfig](#sglangconfig) |
|
||||
| `ttft_p99` | `time.Duration` | [SLO](#slo) |
|
||||
| `tpot_p99` | `time.Duration` | [SLO](#slo) |
|
||||
| `days` | `[]string` | [ScaleWindow](#scalewindow) |
|
||||
| `from` | `string` | [ScaleWindow](#scalewindow) |
|
||||
| `to` | `string` | [ScaleWindow](#scalewindow) |
|
||||
| `min` | `int` | [ScaleWindow](#scalewindow) |
|
||||
| `max` | `int` | [ScaleWindow](#scalewindow) |
|
||||
| `min` | `int` | [Scaling](#scaling) |
|
||||
| `max` | `int` | [Scaling](#scaling) |
|
||||
| `idle_timeout` | `time.Duration` | [Scaling](#scaling) |
|
||||
| `schedule` | `[]ScaleWindow` | [Scaling](#scaling) |
|
||||
| `prewarm` | `time.Duration` | [Scaling](#scaling) |
|
||||
| `target_waiting` | `float64` | [Scoring](#scoring) |
|
||||
| `target_inflight` | `float64` | [Scoring](#scoring) |
|
||||
| `kv_ceiling` | `float64` | [Scoring](#scoring) |
|
||||
| `session_load_factor` | `float64` | [Scoring](#scoring) |
|
||||
| `vault` | `secrets.Vault` | [Secrets](#secrets) |
|
||||
| `master_key` | `string` | [Secrets](#secrets) |
|
||||
| `listen` | `string` | [Server](#server) |
|
||||
| `admin_listen` | `string` | [Server](#server) |
|
||||
| `metrics_listen` | `string` | [Server](#server) |
|
||||
@@ -224,21 +278,28 @@ rather than repeated.
|
||||
| `debug_pprof` | `bool` | [Server](#server) |
|
||||
| `agent_insecure` | `bool` | [Server](#server) |
|
||||
| `monitoring` | `Monitoring` | [Server](#server) |
|
||||
| `tracing` | `Tracing` | [Server](#server) |
|
||||
| `tracing` | `obs.Tracing` | [Server](#server) |
|
||||
| `mirror` | `Mirror` | [Server](#server) |
|
||||
| `offline` | `Offline` | [Server](#server) |
|
||||
| `engines` | `map[string]string` | [Server](#server) |
|
||||
| `engine_overrides` | `[]EngineOverride` | [Server](#server) |
|
||||
| `backup_dir` | `string` | [Server](#server) |
|
||||
| `guard` | `guard.Config` | [Server](#server) |
|
||||
| `secrets` | `Secrets` | [Server](#server) |
|
||||
| `notify` | `notify.Config` | [Server](#server) |
|
||||
| `firewall_networks` | `[]string` | [Server](#server) |
|
||||
| `backup_recipients` | `[]string` | [Server](#server) |
|
||||
| `backup_copy_to` | `[]string` | [Server](#server) |
|
||||
| `backup_copy_key` | `string` | [Server](#server) |
|
||||
| `releases` | `string` | [Server](#server) |
|
||||
| `router` | `Router` | [Server](#server) |
|
||||
| `control` | `Control` | [Server](#server) |
|
||||
| `models` | `[]catalog.Model` | [Server](#server) |
|
||||
| `facility` | `Facility` | [Server](#server) |
|
||||
| `federation` | `Federation` | [Server](#server) |
|
||||
| `endpoints` | `[]Endpoint` | [Server](#server) |
|
||||
| `bin` | `string` | [SimConfig](#simconfig) |
|
||||
| `python` | `string` | [TRTLLMConfig](#trtllmconfig) |
|
||||
| `store` | `string` | [Threads](#threads) |
|
||||
| `retain_hours` | `int` | [Threads](#threads) |
|
||||
| `dial` | `time.Duration` | [Timeouts](#timeouts) |
|
||||
@@ -257,6 +318,12 @@ rather than repeated.
|
||||
| `bin` | `string` | [VLLMConfig](#vllmconfig) |
|
||||
| `launch_mode` | `string` | [VLLMConfig](#vllmconfig) |
|
||||
| `ray_bin` | `string` | [VLLMConfig](#vllmconfig) |
|
||||
| `addr` | `string` | [Vault](#vault) |
|
||||
| `token_file` | `string` | [Vault](#vault) |
|
||||
| `role_id_file` | `string` | [Vault](#vault) |
|
||||
| `secret_id_file` | `string` | [Vault](#vault) |
|
||||
| `ca_file` | `string` | [Vault](#vault) |
|
||||
| `namespace` | `string` | [Vault](#vault) |
|
||||
| `url` | `string` | [Webhook](#webhook) |
|
||||
| `format` | `string` | [Webhook](#webhook) |
|
||||
| `events` | `[]string` | [Webhook](#webhook) |
|
||||
@@ -291,6 +358,7 @@ rather than repeated.
|
||||
| `discovery` | `discovery.Options` | [agent.Config](#agentconfig) |
|
||||
| `engines` | `engines.Config` | [agent.Config](#agentconfig) |
|
||||
| `supervisor` | `supervisor.Config` | [agent.Config](#agentconfig) |
|
||||
| `tracing` | `obs.Tracing` | [agent.Config](#agentconfig) |
|
||||
| `name` | `string` | [config.Band](#configband) |
|
||||
| `priority` | `int` | [config.Band](#configband) |
|
||||
| `saturation_ceiling` | `float64` | [config.Band](#configband) |
|
||||
@@ -300,6 +368,7 @@ rather than repeated.
|
||||
| `vllm` | `VLLMConfig` | [engines.Config](#enginesconfig) |
|
||||
| `sglang` | `SGLangConfig` | [engines.Config](#enginesconfig) |
|
||||
| `llamacpp` | `LlamaCppConfig` | [engines.Config](#enginesconfig) |
|
||||
| `trtllm` | `TRTLLMConfig` | [engines.Config](#enginesconfig) |
|
||||
| `sim` | `SimConfig` | [engines.Config](#enginesconfig) |
|
||||
| `default` | `[]string` | [guard.Config](#guardconfig) |
|
||||
| `policies` | `map[string]Policy` | [guard.Config](#guardconfig) |
|
||||
@@ -329,8 +398,10 @@ Name is what clients ask for, like a model name.
|
||||
|
||||
`string`
|
||||
|
||||
Source is the adapter file (GGUF for llama.cpp), fetched by each node
|
||||
as the model's weights are.
|
||||
Source is the adapter: a GGUF file for llama.cpp; for vLLM a PEFT
|
||||
adapter directory (a mirror version ending in "/", a path on the node,
|
||||
or a Hugging Face repository id). Fetched by each node as the model's
|
||||
weights are.
|
||||
|
||||
### `scale`
|
||||
|
||||
@@ -510,6 +581,83 @@ five-minute sums kept beside the records, which are not pruned, so this
|
||||
bounds the table that grows by a row a request without changing any
|
||||
figure a page shows. At least a day when set.
|
||||
|
||||
## Batch
|
||||
|
||||
### `max_file_bytes`
|
||||
|
||||
`int64`
|
||||
|
||||
MaxFileBytes bounds one uploaded file; 100 MB unless set.
|
||||
|
||||
### `max_lines`
|
||||
|
||||
`int`
|
||||
|
||||
MaxLines bounds the requests in one batch; 50 000 unless set.
|
||||
|
||||
### `concurrency`
|
||||
|
||||
`int`
|
||||
|
||||
Concurrency is how many of one batch's requests are in flight at
|
||||
once; 4 unless set. They queue in the lowest admission band, behind
|
||||
every interactive request.
|
||||
|
||||
### `retain_days`
|
||||
|
||||
`int`
|
||||
|
||||
RetainDays is how long a batch's answer and error files are kept;
|
||||
30 unless set. Uploaded files are kept until deleted.
|
||||
|
||||
## Cache
|
||||
|
||||
### `max_bytes`
|
||||
|
||||
`int64`
|
||||
|
||||
MaxBytes bounds every project's answers together; 128 MB unless set.
|
||||
Past it, the answers used longest ago go first.
|
||||
|
||||
### `max_entry_bytes`
|
||||
|
||||
`int64`
|
||||
|
||||
MaxEntryBytes bounds one answer; a longer one is not kept. 1 MB
|
||||
unless set.
|
||||
|
||||
## Canary
|
||||
|
||||
### `model`
|
||||
|
||||
`string`
|
||||
|
||||
Model is the candidate: a catalog model, usually this one at newer
|
||||
weights, which clients cannot name themselves.
|
||||
|
||||
### `percent`
|
||||
|
||||
`int`
|
||||
|
||||
Percent of requests go to it, 0 to 100.
|
||||
|
||||
### `min_requests`
|
||||
|
||||
`int`
|
||||
|
||||
The candidate is taken out — rolled back — when, over at least
|
||||
MinRequests of its own, its error rate is MaxErrorIncrease above
|
||||
this model's (0.05 is five points), or its mean time to the first
|
||||
token is MaxTTFTRatio times this model's. Zero is 50, 0.05 and 1.5.
|
||||
|
||||
### `max_error_increase`
|
||||
|
||||
`float64`
|
||||
|
||||
### `max_ttft_ratio`
|
||||
|
||||
`float64`
|
||||
|
||||
## Capabilities
|
||||
|
||||
### `tools`
|
||||
@@ -566,6 +714,22 @@ PortRange is the per-node range for engine HTTP and dist-init ports.
|
||||
|
||||
MgmtInterface is the ethernet interface NCCL bootstraps over.
|
||||
|
||||
### `timezone`
|
||||
|
||||
`string`
|
||||
|
||||
Timezone is where models' scaling schedules are read, an IANA name
|
||||
like Europe/Istanbul; empty is the control plane's own.
|
||||
|
||||
### `eval_dir`
|
||||
|
||||
`string`
|
||||
|
||||
EvalDir is where quality suites are read from by name, for `llmgw ctl
|
||||
eval MODEL --suite NAME`, a model's eval gate and the console. The
|
||||
suites the binary carries (arithmetic, json-format) are found when it
|
||||
has none of the name; a suite here of the same name replaces one.
|
||||
|
||||
### `enabled`
|
||||
|
||||
`bool`
|
||||
@@ -659,6 +823,28 @@ Labels picks nodes carrying all of these.
|
||||
|
||||
Engines are laid over the cluster's: a version, or "" for none.
|
||||
|
||||
## EvalGate
|
||||
|
||||
### `suite`
|
||||
|
||||
`string`
|
||||
|
||||
Suite is a suite's name in control.eval_dir, or one the binary
|
||||
carries (arithmetic, json-format).
|
||||
|
||||
### `min_score`
|
||||
|
||||
`float64`
|
||||
|
||||
MinScore is the score, 0 to 1, to pass at; zero is the suite's own
|
||||
threshold.
|
||||
|
||||
### `judge`
|
||||
|
||||
`string`
|
||||
|
||||
Judge grades the suite's rubric cases, instead of the judge it names.
|
||||
|
||||
## External
|
||||
|
||||
### `url`
|
||||
@@ -681,6 +867,102 @@ APIKeyFile holds the provider's key, on the control plane. A file
|
||||
rather than the key itself, so the key is in neither the catalog, the
|
||||
store nor the audit log; empty for a provider that asks for none.
|
||||
|
||||
### `peer`
|
||||
|
||||
`string`
|
||||
|
||||
Peer names the federated llmgw cluster this model is offered by, for
|
||||
a model that federation added (`llmgw ctl federation add`) rather
|
||||
than one written by hand. Such a model is named PEER/MODEL, comes and
|
||||
goes with the peer's own list, and is sent only while the peer is up.
|
||||
|
||||
## Facility
|
||||
|
||||
### `budgets`
|
||||
|
||||
`[]FacilityBudget`
|
||||
|
||||
Budgets are the domains with a power cap.
|
||||
|
||||
### `margin`
|
||||
|
||||
`float64`
|
||||
|
||||
Margin is the share of every cap kept free, 0.1 for ten percent. Zero
|
||||
keeps none, for caps already given derated.
|
||||
|
||||
### `gpu_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
GPUWatts is a card's draw when it does not report its power limit:
|
||||
an agent without nvidia-smi's power fields, or a node that has not
|
||||
sent a heartbeat yet. Zero counts such a card as drawing nothing.
|
||||
|
||||
### `cpu_core_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
CPUCoreWatts is the draw of a core reserved by a replica with no GPU
|
||||
(cpu_cores). Zero counts such replicas as drawing nothing.
|
||||
|
||||
### `node_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
NodeWatts is what a node draws besides its cards and reserved cores —
|
||||
idle CPUs, memory, fans, disks — counted for every node in a capped
|
||||
domain, busy or not.
|
||||
|
||||
### `measured_fresh`
|
||||
|
||||
`time.Duration`
|
||||
|
||||
MeasuredFresh is how old a node's power reading may be and still be
|
||||
counted against its domains. Zero takes two minutes.
|
||||
|
||||
## FacilityBudget
|
||||
|
||||
### `domain`
|
||||
|
||||
`string`
|
||||
|
||||
Domain is level:name, as the nodes' labels give it: rack:r12-07,
|
||||
pdu:r12-07-a, row:12.
|
||||
|
||||
### `cap_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
CapWatts is what the domain may draw. For a dual-fed rack it is what
|
||||
one feed carries alone, derated as the facility derates it (usually
|
||||
80%), since that is what the rack has to survive.
|
||||
|
||||
### `other_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
OtherWatts is drawn in the domain by what llmgw does not place on:
|
||||
switches, storage, machines outside the cluster.
|
||||
|
||||
## Federation
|
||||
|
||||
### `name`
|
||||
|
||||
`string`
|
||||
|
||||
Name is this cluster as a peer reads it, in the federated_from tag
|
||||
sent with a request to a peer set to receive tags (`ctl federation add
|
||||
--send-tags`). Empty is this machine's host name.
|
||||
|
||||
### `interval`
|
||||
|
||||
`time.Duration`
|
||||
|
||||
Interval is how often each peer is asked whether it is ready, timed,
|
||||
and what it offers. A peer that does not answer is taken out of
|
||||
routing until it does. Zero is 10s.
|
||||
|
||||
## GuardModel
|
||||
|
||||
### `format`
|
||||
@@ -731,6 +1013,33 @@ codes (S1, S10) or the names the model reports.
|
||||
LatencyBudget is how long the judge is waited for before the policy's
|
||||
fail applies. Zero is 250ms.
|
||||
|
||||
## KVIndex
|
||||
|
||||
### `tokenize_timeout`
|
||||
|
||||
`time.Duration`
|
||||
|
||||
TokenizeTimeout bounds the call that turns a request into token ids,
|
||||
made to one of the model's replicas before the request is placed. Past
|
||||
it the request is routed as tier 1 would. Zero takes 250ms.
|
||||
|
||||
### `min_blocks`
|
||||
|
||||
`int`
|
||||
|
||||
MinBlocks is the fewest leading blocks a replica must hold to be
|
||||
preferred for them; fewer is coincidence — a chat template's opening
|
||||
tokens — rather than a prefix worth following. Zero takes 4, which is
|
||||
64 tokens at vLLM's usual block size of 16.
|
||||
|
||||
### `max_blocks`
|
||||
|
||||
`int`
|
||||
|
||||
MaxBlocks bounds how many of a prompt's blocks are hashed and looked
|
||||
up. Beyond it a longer match still helps, but the difference no longer
|
||||
decides anything. Zero takes 4096.
|
||||
|
||||
## Landing
|
||||
|
||||
### `contact`
|
||||
@@ -747,6 +1056,25 @@ channel name. Rendered as a link when it is one, as text otherwise.
|
||||
Notice is an optional line of your own, for whatever the reader needs to
|
||||
know that this page cannot guess.
|
||||
|
||||
### `language`
|
||||
|
||||
`string`
|
||||
|
||||
Language is what the web portal speaks to someone who has not chosen
|
||||
a language with the switcher at the foot of every page and whose
|
||||
browser asks for none it speaks: "en" or "tr". Empty is English.
|
||||
|
||||
### `docs_sign_in`
|
||||
|
||||
`bool`
|
||||
|
||||
DocsSignIn serves the docs portal at /docs only to someone signed in.
|
||||
Off, the portal is public like this page: its client guide is for the
|
||||
person who has no account yet, and the operator documents describe
|
||||
llmgw in general — no address, model or key of this installation —
|
||||
which the project's repository publishes anyway. On, a visitor is sent
|
||||
to sign in, and without accounts the portal needs an API key.
|
||||
|
||||
## LlamaCppConfig
|
||||
|
||||
### `bin`
|
||||
@@ -909,12 +1237,45 @@ Takes a [External](#external) block.
|
||||
|
||||
Adapters are LoRA adapters served on this model's replicas, each asked
|
||||
for by its own name as though it were a model. Every replica loads
|
||||
every adapter, applying one only to a request that names it.
|
||||
every adapter, applying one only to a request that names it — unless
|
||||
MaxLoadedAdapters is set.
|
||||
|
||||
### `max_loaded_adapters`
|
||||
|
||||
`int`
|
||||
|
||||
MaxLoadedAdapters, above zero, has each replica hold at most this many
|
||||
adapters at once, loaded when a request first asks for one and unloaded
|
||||
least recently used first to make room. The router sends a request for
|
||||
an adapter to a replica that already holds it while that one has room
|
||||
to take it. vLLM profiles only: llama-server loads adapters at start
|
||||
and cannot load one afterwards. Zero loads every adapter on every
|
||||
replica at start.
|
||||
|
||||
### `fallbacks`
|
||||
|
||||
`[]string`
|
||||
|
||||
### `canary`
|
||||
|
||||
`*Canary`
|
||||
|
||||
Canary sends a share of this model's requests to another catalog
|
||||
model — the same model at new weights — to compare the two before
|
||||
moving to it (`llmgw ctl model canary`).
|
||||
|
||||
Takes a [Canary](#canary) block.
|
||||
|
||||
### `eval`
|
||||
|
||||
`*EvalGate`
|
||||
|
||||
Eval is a quality suite new weights must pass before they replace
|
||||
this model's: `llmgw ctl model update` and `model promote` run it
|
||||
against them first, and stop below its score.
|
||||
|
||||
Takes a [EvalGate](#evalgate) block.
|
||||
|
||||
### `routing_profile`
|
||||
|
||||
`string`
|
||||
@@ -1084,6 +1445,29 @@ PasswordSignIn off refuses passwords on the sign-in form: people come
|
||||
in through the provider only. Administrators still can, so a broken
|
||||
provider does not lock everybody out.
|
||||
|
||||
## Offline
|
||||
|
||||
### `mirror`
|
||||
|
||||
`string`
|
||||
|
||||
Mirror is the mirror's file address, as nodes reach it:
|
||||
http://10.0.0.5:8081 — the port model files are served on, not the
|
||||
management API. Set, the cluster is offline: nodes install engines
|
||||
from it and never from their publishers, releases come from it unless
|
||||
releases names another place, and no registry is asked whether a
|
||||
model has newer weights. Python engines (vLLM, SGLang) come from PyPI,
|
||||
which no bundle carries; on an offline node they are installed by hand.
|
||||
|
||||
### `checksums`
|
||||
|
||||
`string`
|
||||
|
||||
Checksums is the file of engine checksums this control plane trusts,
|
||||
kept by llmgw bundle import and llmgw bundle trust; every engine file
|
||||
a node fetches from the mirror is checked against it. Read again
|
||||
whenever it changes. Empty is /etc/llmgw/offline.sha256.
|
||||
|
||||
## Options
|
||||
|
||||
### `nvidia_smi`
|
||||
@@ -1449,6 +1833,27 @@ in the inventory says how much memory a node has, so the operator says
|
||||
which nodes are meant for a model instead of the scheduler inferring it.
|
||||
Agents have reported labels since the beginning; this is what reads them.
|
||||
|
||||
### `power_watts`
|
||||
|
||||
`float64`
|
||||
|
||||
PowerWatts is what one replica of this profile draws, in watts, split
|
||||
evenly over its nodes, counted against the power cap of every rack,
|
||||
PDU or other domain its nodes are in (facility.budgets in server.yaml).
|
||||
Zero derives it: each card at the power limit it reports, each
|
||||
reserved core at facility.cpu_core_watts. Only matters where a domain
|
||||
has a cap.
|
||||
|
||||
### `keep_within`
|
||||
|
||||
`string`
|
||||
|
||||
KeepWithin keeps a multi-node replica's nodes inside one rack, row,
|
||||
room or site, read from their llmgw.io/rack (and so on) labels: for a
|
||||
fabric whose leaves do not reach across racks, or cables that do not.
|
||||
Nodes without the label are passed over for such a profile. Empty is
|
||||
no constraint.
|
||||
|
||||
### `weight`
|
||||
|
||||
`float64`
|
||||
@@ -1469,6 +1874,23 @@ Priority orders profiles during placement; highest that fits wins.
|
||||
StartupTimeout bounds model loading. A 70B model across two nodes takes
|
||||
tens of minutes, so this is per profile rather than global.
|
||||
|
||||
### `kv_events`
|
||||
|
||||
`bool`
|
||||
|
||||
KVEvents has vLLM publish what its prefix cache holds, and the router
|
||||
route this model's requests by it: to the replica holding the most of
|
||||
a prompt's leading blocks (plan §7.5 tier 2). vLLM only.
|
||||
|
||||
Off by default, because it costs something on every request: the
|
||||
router asks a replica to tokenize the prompt before placing it, a
|
||||
round trip and the chat template run twice. It pays where prompts
|
||||
share long prefixes that the approximate tree guesses wrong — many
|
||||
replicas, conversations that move between them, evictions. The engine
|
||||
is started with sha256_cbor block hashing and a fixed PYTHONHASHSEED,
|
||||
which the router's hashing assumes; arguments overriding either leave
|
||||
the index empty, and the agent says so in its log.
|
||||
|
||||
## Router
|
||||
|
||||
### `activation_wait`
|
||||
@@ -1534,6 +1956,16 @@ the win for multi-turn traffic.
|
||||
|
||||
Takes a [Prefix](#prefix) block.
|
||||
|
||||
### `kv_index`
|
||||
|
||||
`KVIndex`
|
||||
|
||||
KVIndex tunes the precise KV index (plan §7.5 tier 2). Which models
|
||||
use it is the catalog's to say, by kv_events on a vLLM profile; this
|
||||
is only how.
|
||||
|
||||
Takes a [KVIndex](#kvindex) block.
|
||||
|
||||
### `session_header`
|
||||
|
||||
`string`
|
||||
@@ -1557,12 +1989,42 @@ labelled by — llmgw_tenant_requests_total and its siblings: "org",
|
||||
on a cluster of thousands is more series than Prometheus wants, and a
|
||||
team is what an alert is usually about; "team" is the default.
|
||||
|
||||
### `tag_labels`
|
||||
|
||||
`[]string`
|
||||
|
||||
TagLabels are the request tags (metadata, x-llmgw-tags) counted in
|
||||
llmgw_tagged_requests_total and llmgw_tagged_tokens_total, by value.
|
||||
Only these: a tag is the client's to set, and every value of one is
|
||||
a series. The first 100 values of each are counted apart, the rest as
|
||||
"other". Empty counts none; the usage records keep every tag anyway.
|
||||
|
||||
### `max_body_bytes`
|
||||
|
||||
`int64`
|
||||
|
||||
MaxBodyBytes bounds the request body the router will read.
|
||||
|
||||
### `batch`
|
||||
|
||||
`Batch`
|
||||
|
||||
Batch is the Files and Batch APIs (/v1/files, /v1/batches): a file of
|
||||
requests served at the lowest priority, its answers written to
|
||||
another. Needs the store.
|
||||
|
||||
Takes a [Batch](#batch) block.
|
||||
|
||||
### `cache`
|
||||
|
||||
`Cache`
|
||||
|
||||
Cache bounds the answers kept for the projects that reuse them
|
||||
(llmgw keys cache). Which projects do, and for how long, is theirs
|
||||
to set; this is only how much memory it may take.
|
||||
|
||||
Takes a [Cache](#cache) block.
|
||||
|
||||
### `trusted_proxies`
|
||||
|
||||
`[]string`
|
||||
@@ -1642,10 +2104,45 @@ point and avoids depending on the script being on PATH.
|
||||
|
||||
`time.Duration`
|
||||
|
||||
TTFTp99 is the time to the first token 99 requests in 100 are within.
|
||||
|
||||
### `tpot_p99`
|
||||
|
||||
`time.Duration`
|
||||
|
||||
TPOTp99 is the time per output token, after the first, 99 streamed
|
||||
requests in 100 are within.
|
||||
|
||||
## ScaleWindow
|
||||
|
||||
### `days`
|
||||
|
||||
`[]string`
|
||||
|
||||
Days are mon … sun, or weekdays, weekends; empty is every day.
|
||||
|
||||
### `from`
|
||||
|
||||
`string`
|
||||
|
||||
From and To are HH:MM; a window whose To is before its From runs
|
||||
past midnight.
|
||||
|
||||
### `to`
|
||||
|
||||
`string`
|
||||
|
||||
### `min`
|
||||
|
||||
`int`
|
||||
|
||||
### `max`
|
||||
|
||||
`int`
|
||||
|
||||
Max, when set, is the window's ceiling for load scaling; zero keeps
|
||||
the model's own.
|
||||
|
||||
## Scaling
|
||||
|
||||
### `min`
|
||||
@@ -1668,6 +2165,24 @@ KV cache prefix routing spent its effort filling, and a model that flaps
|
||||
in and out loses that entirely — so the saving has to be worth more than
|
||||
the cache, which it only is over a real idle period.
|
||||
|
||||
### `schedule`
|
||||
|
||||
`[]ScaleWindow`
|
||||
|
||||
Schedule changes min and max by the time of day, in the control
|
||||
plane's control.timezone: more replicas kept through working hours,
|
||||
fewer at night, an on-demand model kept loaded while people are at
|
||||
work. The first window that holds now wins; outside them all, Min and
|
||||
Max apply.
|
||||
|
||||
### `prewarm`
|
||||
|
||||
`time.Duration`
|
||||
|
||||
Prewarm starts a window this long before it opens, so its replicas
|
||||
have loaded by then: loading a model is minutes, and the people who
|
||||
arrive at nine are the reason for the window.
|
||||
|
||||
## Scoring
|
||||
|
||||
### `target_waiting`
|
||||
@@ -1686,6 +2201,27 @@ the cache, which it only is over a real idle period.
|
||||
|
||||
`float64`
|
||||
|
||||
## Secrets
|
||||
|
||||
### `vault`
|
||||
|
||||
`secrets.Vault`
|
||||
|
||||
Vault is how vault: references and vault-transit: are reached.
|
||||
|
||||
Takes a [Vault](#vault) block.
|
||||
|
||||
### `master_key`
|
||||
|
||||
`string`
|
||||
|
||||
MasterKey seals the secrets the store keeps for itself — what every
|
||||
engine's key is derived from — so a copy of the store, or of a backup,
|
||||
does not hold them: vault-transit:KEY seals with Vault's transit engine,
|
||||
which never lets the key out; otherwise a reference to 32 random bytes
|
||||
(openssl rand -hex 32), which then must be kept as safely as the store.
|
||||
Values from before it was set are sealed the first time they are read.
|
||||
|
||||
## Server
|
||||
|
||||
### `listen`
|
||||
@@ -1817,10 +2353,11 @@ Takes a [Monitoring](#monitoring) block.
|
||||
|
||||
### `tracing`
|
||||
|
||||
`Tracing`
|
||||
`obs.Tracing`
|
||||
|
||||
Tracing sends a trace of each inference request to an OpenTelemetry
|
||||
collector. Off unless an endpoint is set here or in
|
||||
Tracing sends traces to an OpenTelemetry collector: each inference
|
||||
request, and on a control plane each placement, replica start and
|
||||
model job. Off unless an endpoint is set here or in
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT.
|
||||
|
||||
Takes a [Tracing](#tracing) block.
|
||||
@@ -1834,6 +2371,16 @@ Empty means there is none, and /admin/mirror stays unmounted.
|
||||
|
||||
Takes a [Mirror](#mirror) block.
|
||||
|
||||
### `offline`
|
||||
|
||||
`Offline`
|
||||
|
||||
Offline is a cluster that reaches nothing outside itself: its nodes
|
||||
install engines, and upgrades fetch releases, from the mirror, out of
|
||||
a bundle carried in (llmgw bundle create, llmgw bundle import).
|
||||
|
||||
Takes a [Offline](#offline) block.
|
||||
|
||||
### `engines`
|
||||
|
||||
`map[string]string`
|
||||
@@ -1875,6 +2422,15 @@ guard.default, and to parts of the tenancy tree by attaching them
|
||||
|
||||
Takes a [guard.Config](#guardconfig) block.
|
||||
|
||||
### `secrets`
|
||||
|
||||
`Secrets`
|
||||
|
||||
Secrets is where secrets kept outside files are read from, and the key
|
||||
the store's own secrets are sealed under.
|
||||
|
||||
Takes a [Secrets](#secrets) block.
|
||||
|
||||
### `notify`
|
||||
|
||||
`notify.Config`
|
||||
@@ -1905,6 +2461,23 @@ the certificate authority's key and every secret in the store, and is
|
||||
copied off the machine; encrypted, the copy is safe wherever it lands.
|
||||
Empty writes archives unencrypted, readable by root only.
|
||||
|
||||
### `backup_copy_to`
|
||||
|
||||
`[]string`
|
||||
|
||||
BackupCopyTo is where each archive is copied once written, so it
|
||||
survives this machine: a directory (a mounted share, another disk) or
|
||||
ssh://user@host[:port]/path, reached with BackupCopyKey and checked
|
||||
against /etc/llmgw/backup_known_hosts, which learns a host the first
|
||||
time. The same number of archives is kept there as here. Refused
|
||||
without backup_recipients: an archive leaves the machine encrypted.
|
||||
|
||||
### `backup_copy_key`
|
||||
|
||||
`string`
|
||||
|
||||
BackupCopyKey is the SSH private key for ssh:// copies.
|
||||
|
||||
### `releases`
|
||||
|
||||
`string`
|
||||
@@ -1929,6 +2502,27 @@ Takes a [Control](#control) block.
|
||||
|
||||
`[]catalog.Model`
|
||||
|
||||
### `facility`
|
||||
|
||||
`Facility`
|
||||
|
||||
Facility is the power caps of racks, PDUs and other domains, and how
|
||||
a replica's draw is estimated against them. Where a node is comes from
|
||||
its llmgw.io/site, room, row, rack and pdu labels; holding a domain for
|
||||
maintenance is `llmgw ctl facility hold`, not configuration.
|
||||
|
||||
Takes a [Facility](#facility) block.
|
||||
|
||||
### `federation`
|
||||
|
||||
`Federation`
|
||||
|
||||
Federation is how this cluster takes part in federation with other
|
||||
llmgw clusters. The peers themselves are added at runtime, with
|
||||
`llmgw ctl federation add`, and kept in the store.
|
||||
|
||||
Takes a [Federation](#federation) block.
|
||||
|
||||
### `endpoints`
|
||||
|
||||
`[]Endpoint`
|
||||
@@ -1946,6 +2540,21 @@ against sim-engines possible without a control plane.
|
||||
Bin is the llmgw binary itself; the engine is one of its subcommands.
|
||||
Empty means whatever started this agent, which is right almost always.
|
||||
|
||||
## TRTLLMConfig
|
||||
|
||||
### `python`
|
||||
|
||||
`string`
|
||||
|
||||
Python is the interpreter of the environment TensorRT-LLM is installed
|
||||
in: <venv>/bin/python for a virtual environment, python3 in NVIDIA's
|
||||
container. Naming it is what makes this node offer the engine; empty
|
||||
offers nothing.
|
||||
|
||||
The interpreter rather than trtllm-serve, because llmgw starts the
|
||||
server through a few lines of its own that make it demand the
|
||||
gateway's key, which trtllm-serve has no option for.
|
||||
|
||||
## Threads
|
||||
|
||||
### `store`
|
||||
@@ -2044,8 +2653,10 @@ Empty falls back to OTEL_EXPORTER_OTLP_ENDPOINT, and to no tracing.
|
||||
|
||||
`float64`
|
||||
|
||||
SampleRatio is the share of requests traced, 0 to 1, when the caller
|
||||
did not decide it with a sampled traceparent of its own. Zero takes 1.
|
||||
SampleRatio is the share of traces kept, 0 to 1, of those nobody
|
||||
upstream already decided. Zero takes 1. A request with a sampled
|
||||
traceparent of its own is kept, and an agent keeps every start the
|
||||
control plane kept, whatever their own ratio says.
|
||||
|
||||
## VLLMConfig
|
||||
|
||||
@@ -2073,6 +2684,42 @@ node and has not been checked against a real cluster.
|
||||
|
||||
RayBin is used when LaunchMode is "ray".
|
||||
|
||||
## Vault
|
||||
|
||||
### `addr`
|
||||
|
||||
`string`
|
||||
|
||||
Addr is Vault's address, like https://vault.internal:8200; empty
|
||||
takes VAULT_ADDR.
|
||||
|
||||
### `token_file`
|
||||
|
||||
`string`
|
||||
|
||||
TokenFile holds a token; empty takes VAULT_TOKEN, or logs in with
|
||||
AppRole when RoleIDFile and SecretIDFile are set.
|
||||
|
||||
### `role_id_file`
|
||||
|
||||
`string`
|
||||
|
||||
### `secret_id_file`
|
||||
|
||||
`string`
|
||||
|
||||
### `ca_file`
|
||||
|
||||
`string`
|
||||
|
||||
CAFile verifies Vault's certificate; empty uses the system's.
|
||||
|
||||
### `namespace`
|
||||
|
||||
`string`
|
||||
|
||||
Namespace is Vault Enterprise's or OpenBao's namespace.
|
||||
|
||||
## Webhook
|
||||
|
||||
### `url`
|
||||
@@ -2316,6 +2963,18 @@ Takes a [engines.Config](#enginesconfig) block.
|
||||
|
||||
Takes a [supervisor.Config](#supervisorconfig) block.
|
||||
|
||||
### `tracing`
|
||||
|
||||
`obs.Tracing`
|
||||
|
||||
Tracing sends this node's part of each replica start — the weights
|
||||
fetched, the engine launched, the wait for it to answer — to an
|
||||
OpenTelemetry collector, inside the control plane's trace of that
|
||||
start. Give it the collector server.yaml's tracing names. Off unless
|
||||
an endpoint is set here or in OTEL_EXPORTER_OTLP_ENDPOINT.
|
||||
|
||||
Takes a [Tracing](#tracing) block.
|
||||
|
||||
## config.Band
|
||||
|
||||
### `name`
|
||||
@@ -2368,6 +3027,15 @@ Takes a [SGLangConfig](#sglangconfig) block.
|
||||
|
||||
Takes a [LlamaCppConfig](#llamacppconfig) block.
|
||||
|
||||
### `trtllm`
|
||||
|
||||
`TRTLLMConfig`
|
||||
|
||||
TRTLLM is TensorRT-LLM, which the agent does not install: a node
|
||||
offers it only when its interpreter is named here.
|
||||
|
||||
Takes a [TRTLLMConfig](#trtllmconfig) block.
|
||||
|
||||
### `sim`
|
||||
|
||||
`SimConfig`
|
||||
|
||||
@@ -12,6 +12,7 @@ require (
|
||||
github.com/charmbracelet/x/ansi v0.11.6
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/go-jose/go-jose/v4 v4.1.4
|
||||
github.com/go-zeromq/zmq4 v0.17.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.1
|
||||
github.com/knadh/koanf/providers/env/v2 v2.0.1
|
||||
@@ -22,6 +23,7 @@ require (
|
||||
github.com/prometheus/client_model v0.6.3
|
||||
github.com/prometheus/common v0.71.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1
|
||||
github.com/yuin/goldmark v1.8.6
|
||||
go.opentelemetry.io/otel v1.46.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0
|
||||
@@ -55,6 +57,7 @@ require (
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/go-zeromq/goczmq/v4 v4.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
@@ -77,6 +80,7 @@ require (
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/spf13/pflag v1.0.9 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
|
||||
|
||||
@@ -55,6 +55,10 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/go-zeromq/goczmq/v4 v4.2.2 h1:HAJN+i+3NW55ijMJJhk7oWxHKXgAuSBkoFfvr8bYj4U=
|
||||
github.com/go-zeromq/goczmq/v4 v4.2.2/go.mod h1:Sm/lxrfxP/Oxqs0tnHD6WAhwkWrx+S+1MRrKzcxoaYE=
|
||||
github.com/go-zeromq/zmq4 v0.17.0 h1:r12/XdqPeRbuaF4C3QZJeWCt7a5vpJbslDH1rTXF+Kc=
|
||||
github.com/go-zeromq/zmq4 v0.17.0/go.mod h1:EQxjJD92qKnrsVMzAnx62giD6uJIPi1dMGZ781iCDtY=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -136,6 +140,10 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
|
||||
|
||||
+114
-9
@@ -23,6 +23,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"golang.org/x/net/http2"
|
||||
|
||||
llmgwv1 "gitea.mynodes.xyz/ilker/llmgw/api/gen/llmgw/v1"
|
||||
@@ -33,6 +35,8 @@ import (
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/supervisor"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/weights"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/agentsvc"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/kvevents"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/tlsconf"
|
||||
)
|
||||
|
||||
@@ -117,6 +121,12 @@ type Agent struct {
|
||||
// — eight shards starting together produce one download — and all eight
|
||||
// are waiting, so all eight should say so.
|
||||
fetchWatchers map[string][]func(weights.Progress)
|
||||
|
||||
// kv mirrors the KV caches of the engines that publish events, for the
|
||||
// router's precise index; kvSubs are their listeners by shard, guarded
|
||||
// by mu.
|
||||
kv *kvevents.Mirror
|
||||
kvSubs map[string]*kvevents.Subscriber
|
||||
}
|
||||
|
||||
// connectHTTPClient is the HTTP client connect uses; an interface so tests can
|
||||
@@ -159,6 +169,8 @@ func New(cfg Config, httpClient connectHTTPClient, log *slog.Logger) (*Agent, er
|
||||
sensors: discovery.NewSensorSampler(),
|
||||
wear: discovery.NewHealthSampler(),
|
||||
serverList: loadControlPlanes(cfg.Servers, cfg.TLS.Enabled()),
|
||||
kv: kvevents.NewMirror(),
|
||||
kvSubs: map[string]*kvevents.Subscriber{},
|
||||
}
|
||||
a.prov = &provision.Installer{Root: cfg.EnginesDir, Log: log, OnStatus: a.provisionStatus}
|
||||
return a, nil
|
||||
@@ -277,6 +289,12 @@ func (a *Agent) recoverOrphans() {
|
||||
a.mu.Lock()
|
||||
a.shardReplica[o.ShardID] = o.ReplicaID
|
||||
a.mu.Unlock()
|
||||
// The engine is still publishing to the port the last agent
|
||||
// listened on; listen there again.
|
||||
if o.Spec.KVEventsPort > 0 {
|
||||
spec := o.Spec
|
||||
a.listenKV(&spec, o.Spec.KVEventsPort)
|
||||
}
|
||||
a.log.Info("adopted a running engine",
|
||||
"shard", o.ShardID, "replica", o.ReplicaID, "pid", o.PID)
|
||||
go a.settleAdopted(sh, o)
|
||||
@@ -419,6 +437,17 @@ func int32Slice(v []int) []int32 {
|
||||
return out
|
||||
}
|
||||
|
||||
func int32Ints(v []int32) []int {
|
||||
out := make([]int, len(v))
|
||||
for i, x := range v {
|
||||
out[i] = int(x)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// tracerName names the spans the agent opens.
|
||||
const tracerName = "gitea.mynodes.xyz/ilker/llmgw/internal/agent"
|
||||
|
||||
// scan refreshes the node's hardware inventory.
|
||||
func (a *Agent) scan(ctx context.Context) error {
|
||||
// Carried from the agent's own configuration rather than duplicated into
|
||||
@@ -519,6 +548,7 @@ func (a *Agent) session(ctx context.Context, server string) error {
|
||||
}()
|
||||
defer wg.Wait()
|
||||
go a.watchExits(ctx, out)
|
||||
go a.forwardKV(ctx, out)
|
||||
|
||||
for {
|
||||
msg, err := stream.Receive()
|
||||
@@ -786,15 +816,23 @@ func (a *Agent) removeWeights(paths []string) {
|
||||
}
|
||||
|
||||
func (a *Agent) handle(ctx context.Context, msg *llmgwv1.ControlMessage, out chan<- *llmgwv1.AgentMessage) {
|
||||
// The control plane's span that sent this, when it is tracing: what is
|
||||
// done here for a start or a stop goes into the same trace.
|
||||
tctx := obs.Extract(ctx, msg.GetTrace())
|
||||
switch m := msg.Msg.(type) {
|
||||
case *llmgwv1.ControlMessage_Start:
|
||||
go a.startShard(ctx, m.Start, out)
|
||||
go a.startShard(tctx, m.Start, out)
|
||||
case *llmgwv1.ControlMessage_Stop:
|
||||
go a.stopShard(ctx, m.Stop.GetShardId(), out)
|
||||
go a.stopShard(tctx, m.Stop.GetShardId(), out)
|
||||
case *llmgwv1.ControlMessage_Drain:
|
||||
if err := a.sup.Drain(m.Drain.GetShardId()); err != nil {
|
||||
_, span := obs.Tracer(tracerName).Start(tctx, "drain shard",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(attribute.String("llmgw.shard", m.Drain.GetShardId())))
|
||||
err := a.sup.Drain(m.Drain.GetShardId())
|
||||
if err != nil {
|
||||
a.log.Warn("draining failed", "shard", m.Drain.GetShardId(), "err", err)
|
||||
}
|
||||
obs.End(span, err)
|
||||
case *llmgwv1.ControlMessage_RemoveWeights:
|
||||
a.removeWeights(m.RemoveWeights.GetPaths())
|
||||
case *llmgwv1.ControlMessage_Provision:
|
||||
@@ -927,6 +965,25 @@ func localAddr(ip netip.Addr) bool {
|
||||
func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<- *llmgwv1.AgentMessage) {
|
||||
shardID, replicaID := m.GetShardId(), m.GetReplicaId()
|
||||
|
||||
// This node's whole part of the start, from the command arriving to the
|
||||
// engine answering, beneath the control plane's span that sent it. The
|
||||
// steps — weights, launch, readiness — are its children.
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "start shard",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("llmgw.node", a.cfg.NodeID),
|
||||
attribute.String("llmgw.replica", replicaID),
|
||||
attribute.String("llmgw.shard", shardID),
|
||||
attribute.Int("llmgw.rank", int(m.GetRank())),
|
||||
attribute.String("llmgw.model", m.GetProfile().GetServedModelName()),
|
||||
attribute.String("llmgw.profile", m.GetProfile().GetName()),
|
||||
attribute.String("llmgw.engine", m.GetProfile().GetEngine()),
|
||||
attribute.String("llmgw.gpu_class", m.GetProfile().GetGpuClass()),
|
||||
attribute.IntSlice("llmgw.gpus", int32Ints(m.GetGpuIndices())),
|
||||
))
|
||||
var failed error
|
||||
defer func() { obs.End(span, failed) }()
|
||||
|
||||
a.mu.Lock()
|
||||
a.shardReplica[shardID] = replicaID
|
||||
a.mu.Unlock()
|
||||
@@ -939,6 +996,9 @@ func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<
|
||||
}
|
||||
}
|
||||
report := func(st supervisor.State, errMsg string, tail []string) {
|
||||
if st == supervisor.Failed {
|
||||
failed = errors.New(errMsg)
|
||||
}
|
||||
send(&llmgwv1.ShardStatus{
|
||||
State: agentsvc.StateToWire(st), Error: errMsg, LastOutput: tail,
|
||||
})
|
||||
@@ -1009,9 +1069,20 @@ func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<
|
||||
}
|
||||
spec.Profile.Adapters[i].Path = path
|
||||
}
|
||||
// Adapters that load on demand are loaded by the router, by a path that
|
||||
// has to mean the same file on every node: a link of the adapter's name
|
||||
// in the directory engines run in.
|
||||
if spec.Profile.RuntimeLoRA() {
|
||||
if err := engines.LinkRuntimeAdapters(a.sup.EngineDir(), spec.Profile.Adapters); err != nil {
|
||||
report(supervisor.Failed, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
a.listenKV(&spec, 0)
|
||||
cmds, err := eng.Commands(spec)
|
||||
if err != nil {
|
||||
a.stopKV(shardID, replicaID)
|
||||
report(supervisor.Failed, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
@@ -1024,6 +1095,7 @@ func (a *Agent) startShard(ctx context.Context, m *llmgwv1.StartShard, out chan<
|
||||
report(sh.Status().State, "", nil)
|
||||
return
|
||||
}
|
||||
a.stopKV(shardID, replicaID)
|
||||
report(supervisor.Failed, err.Error(), sh.Logs(10))
|
||||
return
|
||||
}
|
||||
@@ -1109,9 +1181,19 @@ func (a *Agent) stopShard(ctx context.Context, shardID string, out chan<- *llmgw
|
||||
delete(a.shardReplica, shardID)
|
||||
a.mu.Unlock()
|
||||
|
||||
if err := a.sup.Stop(ctx, shardID); err != nil {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "stop shard",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("llmgw.node", a.cfg.NodeID),
|
||||
attribute.String("llmgw.replica", replicaID),
|
||||
attribute.String("llmgw.shard", shardID),
|
||||
))
|
||||
err := a.sup.Stop(ctx, shardID)
|
||||
if err != nil {
|
||||
a.log.Warn("stopping a shard failed", "shard", shardID, "err", err)
|
||||
}
|
||||
a.stopKV(shardID, replicaID)
|
||||
obs.End(span, err)
|
||||
a.sup.Remove(shardID)
|
||||
|
||||
msg := &llmgwv1.AgentMessage{Msg: &llmgwv1.AgentMessage_Shard{Shard: &llmgwv1.ShardStatus{
|
||||
@@ -1202,18 +1284,20 @@ const (
|
||||
//
|
||||
// The interface NCCL bootstraps over is this node's, not the cluster's: the
|
||||
// control plane sends one name for every node, and a node whose management
|
||||
// network is on ens3 rather than eth0 would have NCCL bind nothing. And on
|
||||
// RoCE, which GID entry routes is a property of these adapters.
|
||||
// network is on ens3 rather than eth0 would have NCCL bind nothing. On RoCE,
|
||||
// which GID entry routes is a property of these adapters. And a MIG instance
|
||||
// is opened by its UUID, which only this node knows.
|
||||
func (a *Agent) localizeSpec(spec *engines.ShardSpec) {
|
||||
if a.cfg.MgmtInterface != "" {
|
||||
spec.MgmtInterface = a.cfg.MgmtInterface
|
||||
}
|
||||
a.mu.Lock()
|
||||
hcas, gpus := a.inv.HCAs, a.inv.GPUs
|
||||
a.mu.Unlock()
|
||||
spec.GPUUUIDs = migUUIDs(gpus, spec.GPUIndices)
|
||||
if len(spec.HCAs) == 0 {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
hcas := a.inv.HCAs
|
||||
a.mu.Unlock()
|
||||
want := map[string]bool{}
|
||||
for _, h := range spec.HCAs {
|
||||
want[h] = true
|
||||
@@ -1232,6 +1316,27 @@ func (a *Agent) localizeSpec(spec *engines.ShardSpec) {
|
||||
}
|
||||
}
|
||||
|
||||
// migUUIDs names a shard's devices by UUID when one of them is a MIG
|
||||
// instance, and is nil otherwise: whole cards keep being given by index, as
|
||||
// they always were. A device this node does not have is left to fail where
|
||||
// it always has, in the engine, rather than guessed at here.
|
||||
func migUUIDs(gpus []discovery.GPU, indices []int) []string {
|
||||
var out []string
|
||||
mig := false
|
||||
for _, i := range indices {
|
||||
k := slices.IndexFunc(gpus, func(g discovery.GPU) bool { return g.Index == i })
|
||||
if k < 0 || gpus[k].UUID == "" {
|
||||
return nil
|
||||
}
|
||||
mig = mig || gpus[k].IsMIG()
|
||||
out = append(out, gpus[k].UUID)
|
||||
}
|
||||
if !mig {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ResolveManagement is the address and interface this node's agent would use,
|
||||
// found the way normalize finds them, for a tool that reports them.
|
||||
func ResolveManagement(c Config) (addr, iface string) {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/engines"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/supervisor"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/inventory"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/tlsconf"
|
||||
)
|
||||
|
||||
@@ -94,6 +95,13 @@ type Config struct {
|
||||
Engines engines.Config `koanf:"engines"`
|
||||
Superv supervisor.Config `koanf:"supervisor"`
|
||||
|
||||
// Tracing sends this node's part of each replica start — the weights
|
||||
// fetched, the engine launched, the wait for it to answer — to an
|
||||
// OpenTelemetry collector, inside the control plane's trace of that
|
||||
// start. Give it the collector server.yaml's tracing names. Off unless
|
||||
// an endpoint is set here or in OTEL_EXPORTER_OTLP_ENDPOINT.
|
||||
Tracing obs.Tracing `koanf:"tracing"`
|
||||
|
||||
Version string
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,11 @@ type GPU struct {
|
||||
Fabric *GPUFabric `json:"fabric,omitempty"`
|
||||
// Health carries anything that should keep the GPU out of placement.
|
||||
Health GPUHealth `json:"health"`
|
||||
// MIG is set when this is a MIG instance rather than a whole card: its
|
||||
// Index is then MIGIndex's, its UUID the instance's (MIG-…), and its
|
||||
// memory the instance's share. Utilisation stays unreported, because no
|
||||
// driver measures it per instance.
|
||||
MIG *MIGDevice `json:"mig,omitempty"`
|
||||
}
|
||||
|
||||
// GPUHealth records conditions that make a GPU unsafe to schedule onto.
|
||||
@@ -94,8 +99,30 @@ func (g GPU) Class() string {
|
||||
}
|
||||
|
||||
// Round to the nearest GiB: vendors report 81559 MiB for an "80GB" card.
|
||||
gb := int(math.Round(float64(g.MemoryTotalMB) / 1024))
|
||||
return fmt.Sprintf("%s-%dg", model, gb)
|
||||
// A MIG instance is named from its card's memory and then its profile,
|
||||
// so two instances are one class only when both the card and the slice
|
||||
// are the same.
|
||||
mem := g.MemoryTotalMB
|
||||
if g.MIG != nil {
|
||||
mem = g.MIG.ParentMemoryTotalMB
|
||||
}
|
||||
gb := int(math.Round(float64(mem) / 1024))
|
||||
class := fmt.Sprintf("%s-%dg", model, gb)
|
||||
if g.MIG != nil {
|
||||
return migClass(class, g.MIG.Profile)
|
||||
}
|
||||
return class
|
||||
}
|
||||
|
||||
// normalizeBusID makes bus ids comparable: NVML reports them uppercase from one
|
||||
// call and lowercase from another, and sometimes with a shortened domain.
|
||||
func normalizeBusID(s string) string {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
// "0000:1b:00.0" and "00000000:1B:00.0" are the same device.
|
||||
if i := strings.Index(s, ":"); i > 0 {
|
||||
s = strings.TrimLeft(s[:i], "0") + s[i:]
|
||||
}
|
||||
return strings.TrimPrefix(s, ":")
|
||||
}
|
||||
|
||||
// MarshalJSON adds the derived class, so a consumer of the JSON does not have
|
||||
|
||||
@@ -14,7 +14,6 @@ package discovery
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/NVIDIA/go-nvml/pkg/nvml"
|
||||
)
|
||||
@@ -83,11 +82,18 @@ func DiscoverGPUsNVML(_ context.Context) ([]GPU, error) {
|
||||
}
|
||||
|
||||
assessHealth(&g)
|
||||
gpus = append(gpus, g)
|
||||
// A card in MIG mode is its instances, not itself: CUDA will not
|
||||
// open the whole card while MIG is on.
|
||||
devs, _ := migFromNVML(g, nvmlCard{dev})
|
||||
gpus = append(gpus, devs...)
|
||||
}
|
||||
|
||||
// A second pass, because a link's remote end may be a GPU enumerated later.
|
||||
// A second pass, because a link's remote end may be a GPU enumerated
|
||||
// later. MIG instances have no NVLink of their own to use.
|
||||
for i := range gpus {
|
||||
if gpus[i].IsMIG() {
|
||||
continue
|
||||
}
|
||||
dev, ret := nvml.DeviceGetHandleByIndex(gpus[i].Index)
|
||||
if ret != nvml.SUCCESS {
|
||||
continue
|
||||
@@ -136,13 +142,73 @@ func busIDString(b []int8) string {
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
// normalizeBusID makes bus ids comparable: NVML reports them uppercase from one
|
||||
// call and lowercase from another, and sometimes with a shortened domain.
|
||||
func normalizeBusID(s string) string {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
// "0000:1b:00.0" and "00000000:1B:00.0" are the same device.
|
||||
if i := strings.Index(s, ":"); i > 0 {
|
||||
s = strings.TrimLeft(s[:i], "0") + s[i:]
|
||||
// nvmlCard adapts an NVML device to what MIG discovery reads of it.
|
||||
type nvmlCard struct{ dev nvml.Device }
|
||||
|
||||
func (c nvmlCard) MIGMode() (current, pending, ok bool) {
|
||||
cur, pend, ret := c.dev.GetMigMode()
|
||||
if ret != nvml.SUCCESS {
|
||||
// NOT_SUPPORTED on a card without MIG, which is most of them.
|
||||
return false, false, false
|
||||
}
|
||||
return strings.TrimPrefix(s, ":")
|
||||
return cur == nvml.DEVICE_MIG_ENABLE, pend == nvml.DEVICE_MIG_ENABLE, true
|
||||
}
|
||||
|
||||
func (c nvmlCard) MaxMIGDevices() int {
|
||||
n, ret := c.dev.GetMaxMigDeviceCount()
|
||||
if ret != nvml.SUCCESS {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (c nvmlCard) MIGDevice(i int) (nvmlMIGInstance, bool) {
|
||||
h, ret := c.dev.GetMigDeviceHandleByIndex(i)
|
||||
if ret != nvml.SUCCESS {
|
||||
// NOT_FOUND for an index with no instance: the count is the most a
|
||||
// card can hold, not how many it has.
|
||||
return nil, false
|
||||
}
|
||||
return nvmlMIG{h}, true
|
||||
}
|
||||
|
||||
// nvmlMIG adapts a MIG device handle.
|
||||
type nvmlMIG struct{ dev nvml.Device }
|
||||
|
||||
func (m nvmlMIG) UUID() string {
|
||||
u, _ := m.dev.GetUUID()
|
||||
return u
|
||||
}
|
||||
|
||||
func (m nvmlMIG) Name() string {
|
||||
n, _ := m.dev.GetName()
|
||||
return n
|
||||
}
|
||||
|
||||
func (m nvmlMIG) Memory() (totalMB, usedMB int, ok bool) {
|
||||
mem, ret := m.dev.GetMemoryInfo()
|
||||
if ret != nvml.SUCCESS {
|
||||
return 0, 0, false
|
||||
}
|
||||
return int(mem.Total / (1 << 20)), int(mem.Used / (1 << 20)), true
|
||||
}
|
||||
|
||||
func (m nvmlMIG) Instances() (gpuInstance, computeInstance int) {
|
||||
gi, ret := m.dev.GetGpuInstanceId()
|
||||
if ret != nvml.SUCCESS {
|
||||
gi = -1
|
||||
}
|
||||
ci, ret := m.dev.GetComputeInstanceId()
|
||||
if ret != nvml.SUCCESS {
|
||||
ci = -1
|
||||
}
|
||||
return gi, ci
|
||||
}
|
||||
|
||||
func (m nvmlMIG) Attributes() (slices, memoryMB int, ok bool) {
|
||||
a, ret := m.dev.GetAttributes()
|
||||
if ret != nvml.SUCCESS {
|
||||
return 0, 0, false
|
||||
}
|
||||
return int(a.GpuInstanceSliceCount), int(a.MemorySizeMB), true
|
||||
}
|
||||
@@ -60,7 +60,33 @@ func DiscoverGPUsSMI(ctx context.Context, binary string) ([]GPU, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("running %s: %w", binary, err)
|
||||
}
|
||||
return parseSMI(string(out))
|
||||
cards, err := parseSMI(string(out))
|
||||
if err != nil || len(cards) == 0 {
|
||||
return cards, err
|
||||
}
|
||||
// The query lists whole cards, MIG mode or not. A card in MIG mode is
|
||||
// replaced by its instances, which only -L names and only the full
|
||||
// report sizes; asked only when some card could be in MIG mode, since
|
||||
// the report is the slowest thing nvidia-smi does.
|
||||
if !anyMIGCapable(cards) {
|
||||
return cards, nil
|
||||
}
|
||||
listed, report := readMIG(ctx, binary)
|
||||
return expandMIG(cards, listed, report), nil
|
||||
}
|
||||
|
||||
// anyMIGCapable reports whether any card could be in MIG mode: MIG began
|
||||
// with compute capability 8.0 (the A100). The consumer cards of the same
|
||||
// generations have none, but telling them apart by name is guesswork, and
|
||||
// asking one costs only two more nvidia-smi runs at registration.
|
||||
func anyMIGCapable(cards []GPU) bool {
|
||||
for _, c := range cards {
|
||||
major, _, _ := strings.Cut(c.ComputeCapability, ".")
|
||||
if n, err := strconv.Atoi(major); err == nil && n >= 8 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parseSMI(out string) ([]GPU, error) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -34,9 +35,16 @@ func GPUProcesses(ctx context.Context, binary string) (map[int][]int, error) {
|
||||
return parseGPUProcesses(out)
|
||||
}
|
||||
|
||||
// GPUMemory is one card's memory as nvidia-smi reports it at a moment: what
|
||||
// GPUMemory is one device's memory as nvidia-smi reports it at a moment: what
|
||||
// is allocated on it, and which processes hold how much of that.
|
||||
//
|
||||
// A device is what discovery reports: a whole card, or each MIG instance of a
|
||||
// card in MIG mode, in the same order, so the readings line up with the
|
||||
// inventory one for one.
|
||||
type GPUMemory struct {
|
||||
// Index is the device's number as placement knows it: the card's
|
||||
// nvidia-smi index, or MIGIndex's for an instance.
|
||||
Index int
|
||||
UsedMB int
|
||||
Procs []GPUProcess
|
||||
}
|
||||
@@ -66,48 +74,62 @@ func GPUMemoryByProcess(ctx context.Context, binary string) ([]GPUMemory, error)
|
||||
return parseGPUMemory(out)
|
||||
}
|
||||
|
||||
// smiLog is the part of nvidia-smi's XML report this reads: each GPU, in
|
||||
// index order, its memory and the processes on it.
|
||||
type smiLog struct {
|
||||
GPUs []struct {
|
||||
Used string `xml:"fb_memory_usage>used"`
|
||||
Processes []struct {
|
||||
PID string `xml:"pid"`
|
||||
Type string `xml:"type"`
|
||||
UsedMB string `xml:"used_memory"`
|
||||
} `xml:"processes>process_info"`
|
||||
} `xml:"gpu"`
|
||||
}
|
||||
|
||||
// parseGPUProcesses reads the report. GPUs are listed in index order, which
|
||||
// is nvidia-smi's own numbering — the one placement assigns by.
|
||||
// parseGPUProcesses reads the report, by device as placement numbers them:
|
||||
// nvidia-smi's index for a whole card, MIGIndex's for a MIG instance.
|
||||
func parseGPUProcesses(report []byte) (map[int][]int, error) {
|
||||
mem, err := parseGPUMemory(report)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[int][]int{}
|
||||
for i, g := range mem {
|
||||
for _, g := range mem {
|
||||
for _, p := range g.Procs {
|
||||
out[i] = append(out[i], p.PID)
|
||||
out[g.Index] = append(out[g.Index], p.PID)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseGPUMemory reads the report into each GPU's memory and its holders.
|
||||
// parseGPUMemory reads the report into each device's memory and its holders.
|
||||
//
|
||||
// Cards are listed in index order, which is nvidia-smi's own numbering. A
|
||||
// card in MIG mode is read as its instances, each with its own memory and
|
||||
// the processes nvidia-smi attributes to its GPU and compute instance: a
|
||||
// process on one instance is not on its neighbours, and the card's total
|
||||
// would have charged every instance with all of them.
|
||||
func parseGPUMemory(report []byte) ([]GPUMemory, error) {
|
||||
var log smiLog
|
||||
var log migLog
|
||||
if err := xml.Unmarshal(report, &log); err != nil {
|
||||
return nil, fmt.Errorf("reading nvidia-smi's report: %w", err)
|
||||
}
|
||||
out := make([]GPUMemory, len(log.GPUs))
|
||||
out := make([]GPUMemory, 0, len(log.GPUs))
|
||||
for i, g := range log.GPUs {
|
||||
out[i].UsedMB = mib(g.Used)
|
||||
for _, p := range g.Processes {
|
||||
if pid, err := strconv.Atoi(strings.TrimSpace(p.PID)); err == nil {
|
||||
out[i].Procs = append(out[i].Procs, GPUProcess{PID: pid, UsedMB: mib(p.UsedMB)})
|
||||
procs := func(gi, ci int) []GPUProcess {
|
||||
var ps []GPUProcess
|
||||
for _, p := range g.Processes {
|
||||
pid, err := strconv.Atoi(strings.TrimSpace(p.PID))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if gi >= 0 && (atoiOr(p.GPUInstance, -1) != gi || atoiOr(p.ComputeInstance, -1) != ci) {
|
||||
continue
|
||||
}
|
||||
ps = append(ps, GPUProcess{PID: pid, UsedMB: mib(p.UsedMB)})
|
||||
}
|
||||
return ps
|
||||
}
|
||||
if !enabled(g.Current) || len(g.Devices) == 0 {
|
||||
out = append(out, GPUMemory{Index: i, UsedMB: mib(g.Used), Procs: procs(-1, -1)})
|
||||
continue
|
||||
}
|
||||
devs := slices.Clone(g.Devices)
|
||||
slices.SortFunc(devs, func(a, b migLogDevice) int { return atoiOr(a.Index, -1) - atoiOr(b.Index, -1) })
|
||||
for _, d := range devs {
|
||||
out = append(out, GPUMemory{
|
||||
Index: MIGIndex(i, atoiOr(d.Index, 0)),
|
||||
UsedMB: mib(d.Used),
|
||||
Procs: procs(atoiOr(d.GPUInstance, -1), atoiOr(d.ComputeInstance, -1)),
|
||||
})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
|
||||
@@ -57,8 +57,8 @@ func TestGPUMemoryIsReadPerProcess(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []GPUMemory{
|
||||
{UsedMB: 14514, Procs: []GPUProcess{{PID: 71315, UsedMB: 4932}, {PID: 4100, UsedMB: 9500}}},
|
||||
{},
|
||||
{Index: 0, UsedMB: 14514, Procs: []GPUProcess{{PID: 71315, UsedMB: 4932}, {PID: 4100, UsedMB: 9500}}},
|
||||
{Index: 1},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %+v, want %+v", got, want)
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
package discovery
|
||||
|
||||
// MIG — Multi-Instance GPU — carves one A100, H100 or later card into up to
|
||||
// seven instances, each with its own memory, its own share of the
|
||||
// multiprocessors and its own UUID. To CUDA an instance is a device of its
|
||||
// own, and to placement it is one too: a card in MIG mode is reported as its
|
||||
// instances instead of as the whole card, each a GPU of a class named from
|
||||
// the card's and the instance's profile ("a100-80g-mig-3g.40gb").
|
||||
//
|
||||
// llmgw does not create instances. Which split a card gets is an operator's
|
||||
// decision, made with nvidia-smi mig; discovery reads what is there.
|
||||
//
|
||||
// Two facts about MIG shape everything below. A process is given one MIG
|
||||
// device: CUDA enumerates a single instance however many are made visible.
|
||||
// And instances have no NVLink or peer-to-peer access between them. A replica
|
||||
// on MIG therefore runs on exactly one instance, never a tensor-parallel group
|
||||
// of them, and the catalog refuses a profile that asks for more.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"math"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MIGDevice is what a MIG instance carries beyond any GPU's fields: which
|
||||
// card it is carved from, and how.
|
||||
type MIGDevice struct {
|
||||
// ParentIndex is the card's nvidia-smi index, which is what its sensors,
|
||||
// topology and wear are reported by.
|
||||
ParentIndex int `json:"parent_index"`
|
||||
ParentUUID string `json:"parent_uuid,omitempty"`
|
||||
// ParentMemoryTotalMB is the whole card's memory: the class is named from
|
||||
// the card, so an instance of an 80 GB card is not mistaken for one of a
|
||||
// 40 GB card that happens to have the same profile name.
|
||||
ParentMemoryTotalMB int `json:"parent_memory_total_mb"`
|
||||
// Device is the instance's number on its card, as nvidia-smi -L lists it.
|
||||
Device int `json:"device"`
|
||||
// Profile is NVIDIA's name for the slice, like "3g.40gb": three of the
|
||||
// card's seven compute slices and forty gigabytes of its memory.
|
||||
Profile string `json:"profile"`
|
||||
// GPUInstance and ComputeInstance are the instance's ids in nvidia-smi
|
||||
// mig -lgi and -lci, which is how nvidia-smi attributes processes to it.
|
||||
GPUInstance int `json:"gpu_instance"`
|
||||
ComputeInstance int `json:"compute_instance"`
|
||||
}
|
||||
|
||||
// migIndexBase starts the numbers MIG instances are given.
|
||||
//
|
||||
// Placement, the agent protocol and every running shard name a node's devices
|
||||
// by an integer, which for a whole card is its nvidia-smi index. An instance
|
||||
// has none of its own, so it is given 1000 + 100 × card + device: card 0's
|
||||
// instance 2 is 1002, card 3's instance 0 is 1300. Readable, stable while the
|
||||
// instances are, and never one a whole card could have.
|
||||
const migIndexBase = 1000
|
||||
|
||||
// MIGIndex is the device number placement knows a MIG instance by.
|
||||
func MIGIndex(card, device int) int { return migIndexBase + 100*card + device }
|
||||
|
||||
// IsMIGIndex reports whether a device number names a MIG instance.
|
||||
func IsMIGIndex(i int) bool { return i >= migIndexBase }
|
||||
|
||||
// DeviceLabel is how a device number is shown to people: "3" for a whole
|
||||
// card, "0/mig2" for card 0's MIG instance 2.
|
||||
func DeviceLabel(i int) string {
|
||||
if !IsMIGIndex(i) {
|
||||
return strconv.Itoa(i)
|
||||
}
|
||||
i -= migIndexBase
|
||||
return fmt.Sprintf("%d/mig%d", i/100, i%100)
|
||||
}
|
||||
|
||||
// DeviceLabels is DeviceLabel for each of a list.
|
||||
func DeviceLabels(is []int) []string {
|
||||
out := make([]string, len(is))
|
||||
for k, i := range is {
|
||||
out[k] = DeviceLabel(i)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// IsMIG reports whether this GPU is a MIG instance rather than a whole card.
|
||||
func (g GPU) IsMIG() bool { return g.MIG != nil }
|
||||
|
||||
// CardIndex is the nvidia-smi index of the physical card this GPU is on: its
|
||||
// own index for a whole card, its parent's for a MIG instance.
|
||||
func (g GPU) CardIndex() int {
|
||||
if g.MIG != nil {
|
||||
return g.MIG.ParentIndex
|
||||
}
|
||||
return g.Index
|
||||
}
|
||||
|
||||
// migClassMarker joins a card's class to an instance's profile in a MIG
|
||||
// class: "a100-80g" + "-mig-" + "3g.40gb".
|
||||
const migClassMarker = "-mig-"
|
||||
|
||||
// IsMIGClass reports whether a GPU class names MIG instances.
|
||||
func IsMIGClass(class string) bool { return strings.Contains(class, migClassMarker) }
|
||||
|
||||
// migProfileClean keeps a profile name to what a class may hold: "1g.10gb+me"
|
||||
// becomes "1g.10gb-me".
|
||||
var migProfileClean = regexp.MustCompile(`[^a-z0-9.]+`)
|
||||
|
||||
// migClass is the class of a MIG instance: the card's class and the profile.
|
||||
func migClass(parentClass, profile string) string {
|
||||
p := migProfileClean.ReplaceAllString(strings.ToLower(strings.TrimSpace(profile)), "-")
|
||||
return parentClass + migClassMarker + strings.Trim(p, "-")
|
||||
}
|
||||
|
||||
// MIGProfileMemoryGB reads the memory out of a MIG class or profile:
|
||||
// 40 from "a100-80g-mig-3g.40gb" or "3g.40gb". Zero when there is none.
|
||||
func MIGProfileMemoryGB(s string) int {
|
||||
if i := strings.LastIndex(s, migClassMarker); i >= 0 {
|
||||
s = s[i+len(migClassMarker):]
|
||||
}
|
||||
m := migProfileMemory.FindStringSubmatch(strings.ToLower(s))
|
||||
if m == nil {
|
||||
return 0
|
||||
}
|
||||
gb, _ := strconv.Atoi(m[1])
|
||||
return gb
|
||||
}
|
||||
|
||||
var migProfileMemory = regexp.MustCompile(`^\d+g\.(\d+)gb`)
|
||||
|
||||
// --- nvidia-smi -L ---
|
||||
|
||||
// listedMIG is one MIG instance as nvidia-smi -L lists it.
|
||||
type listedMIG struct {
|
||||
Device int
|
||||
Profile string
|
||||
UUID string
|
||||
}
|
||||
|
||||
var (
|
||||
// "GPU 0: NVIDIA A100-SXM4-80GB (UUID: GPU-5d5ba0d6-...)"
|
||||
smiListGPU = regexp.MustCompile(`^GPU (\d+):`)
|
||||
// " MIG 3g.40gb Device 0: (UUID: MIG-c6d4f1ef-...)". Drivers before
|
||||
// R470 name the instance MIG-GPU-<card uuid>/<gi>/<ci>, which CUDA of that
|
||||
// era takes in the same place, so the UUID is read as whatever it is.
|
||||
smiListMIG = regexp.MustCompile(`^\s+MIG\s+(\S+)\s+Device\s+(\d+):\s*\(UUID:\s*([^)\s]+)\)`)
|
||||
)
|
||||
|
||||
// parseSMIList reads nvidia-smi -L into each card's MIG instances, by the
|
||||
// card's index, in device order. A card with none is absent.
|
||||
func parseSMIList(out string) map[int][]listedMIG {
|
||||
res := map[int][]listedMIG{}
|
||||
card := -1
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if m := smiListGPU.FindStringSubmatch(line); m != nil {
|
||||
card, _ = strconv.Atoi(m[1])
|
||||
continue
|
||||
}
|
||||
m := smiListMIG.FindStringSubmatch(line)
|
||||
if m == nil || card < 0 {
|
||||
continue
|
||||
}
|
||||
dev, _ := strconv.Atoi(m[2])
|
||||
res[card] = append(res[card], listedMIG{Device: dev, Profile: m[1], UUID: m[3]})
|
||||
}
|
||||
for c := range res {
|
||||
slices.SortFunc(res[c], func(a, b listedMIG) int { return a.Device - b.Device })
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// --- nvidia-smi -q -x ---
|
||||
|
||||
// migLog is the part of nvidia-smi's XML report MIG is read from: each card's
|
||||
// mode, and each instance's ids and memory.
|
||||
type migLog struct {
|
||||
GPUs []migLogGPU `xml:"gpu"`
|
||||
}
|
||||
|
||||
type migLogGPU struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Current string `xml:"mig_mode>current_mig"`
|
||||
Pending string `xml:"mig_mode>pending_mig"`
|
||||
Devices []migLogDevice `xml:"mig_devices>mig_device"`
|
||||
// Processes carry the GPU and compute instance they run in on a card
|
||||
// in MIG mode, and "N/A" for both otherwise.
|
||||
Processes []struct {
|
||||
GPUInstance string `xml:"gpu_instance_id"`
|
||||
ComputeInstance string `xml:"compute_instance_id"`
|
||||
PID string `xml:"pid"`
|
||||
UsedMB string `xml:"used_memory"`
|
||||
} `xml:"processes>process_info"`
|
||||
Used string `xml:"fb_memory_usage>used"`
|
||||
}
|
||||
|
||||
type migLogDevice struct {
|
||||
Index string `xml:"index"`
|
||||
GPUInstance string `xml:"gpu_instance_id"`
|
||||
ComputeInstance string `xml:"compute_instance_id"`
|
||||
Total string `xml:"fb_memory_usage>total"`
|
||||
Used string `xml:"fb_memory_usage>used"`
|
||||
}
|
||||
|
||||
// migState is one card's MIG mode and instances from the report.
|
||||
type migState struct {
|
||||
BusID string
|
||||
Enabled bool
|
||||
PendingEnabled bool
|
||||
Devices []migReported
|
||||
}
|
||||
|
||||
// migReported is one instance as the report describes it.
|
||||
type migReported struct {
|
||||
Device, GPUInstance, ComputeInstance int
|
||||
TotalMB, UsedMB int
|
||||
}
|
||||
|
||||
// enabled reads nvidia-smi's mode words: "Enabled", "Disabled", "N/A".
|
||||
func enabled(s string) bool { return strings.EqualFold(strings.TrimSpace(s), "Enabled") }
|
||||
|
||||
func atoiOr(s string, def int) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(s))
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// parseMIGReport reads each card's MIG state from the XML report, in the
|
||||
// report's order, which is nvidia-smi's index order.
|
||||
func parseMIGReport(report []byte) ([]migState, error) {
|
||||
var log migLog
|
||||
if err := xml.Unmarshal(report, &log); err != nil {
|
||||
return nil, fmt.Errorf("reading nvidia-smi's report: %w", err)
|
||||
}
|
||||
out := make([]migState, len(log.GPUs))
|
||||
for i, g := range log.GPUs {
|
||||
out[i] = migState{BusID: g.ID, Enabled: enabled(g.Current), PendingEnabled: enabled(g.Pending)}
|
||||
for _, d := range g.Devices {
|
||||
out[i].Devices = append(out[i].Devices, migReported{
|
||||
Device: atoiOr(d.Index, -1), GPUInstance: atoiOr(d.GPUInstance, -1),
|
||||
ComputeInstance: atoiOr(d.ComputeInstance, -1),
|
||||
TotalMB: mib(d.Total), UsedMB: mib(d.Used),
|
||||
})
|
||||
}
|
||||
slices.SortFunc(out[i].Devices, func(a, b migReported) int { return a.Device - b.Device })
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// --- putting it together ---
|
||||
|
||||
// migProblemNoInstances keeps a card in MIG mode with nothing carved from it
|
||||
// out of placement: CUDA cannot use the whole card while MIG is on, and
|
||||
// there is no instance to use instead.
|
||||
const migProblemNoInstances = "MIG is enabled with no instances created: nothing can run on it " +
|
||||
"until instances are created (nvidia-smi mig -cgi … -C) or MIG is turned off"
|
||||
|
||||
// migProblemUnnamed is a card whose instances exist but could not be named:
|
||||
// an engine is given an instance by its UUID, and without one it cannot be.
|
||||
const migProblemUnnamed = "MIG is enabled and has instances, but nvidia-smi -L did not name them, " +
|
||||
"so none can be given to an engine"
|
||||
|
||||
// expandMIG replaces each card in MIG mode with its instances.
|
||||
//
|
||||
// listed is nvidia-smi -L's instances by card, which names them; report is
|
||||
// the XML report's state per card, which gives their memory and ids. Either
|
||||
// may be missing: -L alone still says which instances exist, and the report
|
||||
// alone still says a card is in MIG mode, so a card it says has instances
|
||||
// that -L did not name is kept as the whole card with the reason, rather
|
||||
// than placed as a card CUDA will not open.
|
||||
func expandMIG(cards []GPU, listed map[int][]listedMIG, report []migState) []GPU {
|
||||
if len(listed) == 0 && !slices.ContainsFunc(report, func(s migState) bool { return s.Enabled }) {
|
||||
return cards
|
||||
}
|
||||
byBus := map[string]migState{}
|
||||
for _, s := range report {
|
||||
byBus[normalizeBusID(s.BusID)] = s
|
||||
}
|
||||
out := make([]GPU, 0, len(cards))
|
||||
for pos, c := range cards {
|
||||
st, ok := byBus[normalizeBusID(c.PCIBusID)]
|
||||
if !ok && pos < len(report) {
|
||||
st = report[pos]
|
||||
}
|
||||
devs := listed[c.Index]
|
||||
if !st.Enabled && len(devs) == 0 {
|
||||
out = append(out, c)
|
||||
continue
|
||||
}
|
||||
if len(devs) == 0 {
|
||||
p := migProblemNoInstances
|
||||
if len(st.Devices) > 0 {
|
||||
p = migProblemUnnamed
|
||||
}
|
||||
c.Health.Problems = append(c.Health.Problems, p)
|
||||
out = append(out, c)
|
||||
continue
|
||||
}
|
||||
for _, d := range devs {
|
||||
var rep migReported
|
||||
found := false
|
||||
for _, r := range st.Devices {
|
||||
if r.Device == d.Device {
|
||||
rep, found = r, true
|
||||
}
|
||||
}
|
||||
mig := migInstance(c, d.Device, d.Profile, d.UUID)
|
||||
if found {
|
||||
mig.MIG.GPUInstance, mig.MIG.ComputeInstance = rep.GPUInstance, rep.ComputeInstance
|
||||
mig.MemoryTotalMB, mig.MemoryUsedMB = rep.TotalMB, rep.UsedMB
|
||||
}
|
||||
if mig.MemoryTotalMB == 0 {
|
||||
// The profile says it to the gigabyte, which is close enough
|
||||
// to place by when the report could not be read.
|
||||
mig.MemoryTotalMB = MIGProfileMemoryGB(d.Profile) * 1024
|
||||
}
|
||||
assessHealth(&mig)
|
||||
out = append(out, mig)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// migInstance builds a MIG instance of card: everything about the card that
|
||||
// is shared — driver, compute capability, NUMA node, bus, temperature and
|
||||
// ECC errors — and nothing that is not. Not NVLink, which an instance cannot
|
||||
// use; not utilisation, which no driver reports per instance; and not the
|
||||
// card's memory or problems, which the instance's own replace.
|
||||
func migInstance(card GPU, device int, profile, uuid string) GPU {
|
||||
g := GPU{
|
||||
Index: MIGIndex(card.Index, device), UUID: uuid,
|
||||
Name: strings.TrimSpace(card.Name + " MIG " + profile),
|
||||
ComputeCapability: card.ComputeCapability, NUMANode: card.NUMANode,
|
||||
PCIBusID: card.PCIBusID, DriverVersion: card.DriverVersion, CUDAVersion: card.CUDAVersion,
|
||||
NICPaths: card.NICPaths, Fabric: card.Fabric,
|
||||
Health: GPUHealth{ECCErrors: card.Health.ECCErrors, TemperatureC: card.Health.TemperatureC},
|
||||
MIG: &MIGDevice{
|
||||
ParentIndex: card.Index, ParentUUID: card.UUID, ParentMemoryTotalMB: card.MemoryTotalMB,
|
||||
Device: device, Profile: profile, GPUInstance: -1, ComputeInstance: -1,
|
||||
},
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// readMIG asks nvidia-smi for what expandMIG needs. A failure of either
|
||||
// command leaves its half empty, which expandMIG is written to take.
|
||||
func readMIG(ctx context.Context, binary string) (map[int][]listedMIG, []migState) {
|
||||
var listed map[int][]listedMIG
|
||||
if out, err := exec.CommandContext(ctx, binary, "-L").Output(); err == nil {
|
||||
listed = parseSMIList(string(out))
|
||||
}
|
||||
var report []migState
|
||||
if out, err := exec.CommandContext(ctx, binary, "-q", "-x").Output(); err == nil {
|
||||
report, _ = parseMIGReport(out)
|
||||
}
|
||||
return listed, report
|
||||
}
|
||||
|
||||
// --- NVML ---
|
||||
|
||||
// nvmlMIGCard is the part of an NVML device MIG discovery reads, behind an
|
||||
// interface so the logic is tested without a driver: gpu_nvml.go adapts
|
||||
// nvml.Device to it.
|
||||
type nvmlMIGCard interface {
|
||||
// MIGMode is nvmlDeviceGetMigMode; ok is false on a card without MIG.
|
||||
MIGMode() (current, pending, ok bool)
|
||||
// MaxMIGDevices is nvmlDeviceGetMaxMigDeviceCount.
|
||||
MaxMIGDevices() int
|
||||
// MIGDevice is nvmlDeviceGetMigDeviceHandleByIndex; ok is false for an
|
||||
// index with no instance behind it, which is how NVML says so.
|
||||
MIGDevice(i int) (nvmlMIGInstance, bool)
|
||||
}
|
||||
|
||||
// nvmlMIGInstance is one MIG device handle.
|
||||
type nvmlMIGInstance interface {
|
||||
UUID() string
|
||||
// Name is "NVIDIA A100-SXM4-80GB MIG 3g.40gb" on the drivers that name
|
||||
// MIG devices, which is where the profile is read from.
|
||||
Name() string
|
||||
Memory() (totalMB, usedMB int, ok bool)
|
||||
Instances() (gpuInstance, computeInstance int)
|
||||
// Slices and MemoryMB are the instance's attributes, which name the
|
||||
// profile on a driver whose device name does not.
|
||||
Attributes() (slices, memoryMB int, ok bool)
|
||||
}
|
||||
|
||||
var nvmlMIGName = regexp.MustCompile(`MIG\s+(\S+)\s*$`)
|
||||
|
||||
// migFromNVML is what one card is to placement under NVML: its instances if
|
||||
// it is in MIG mode, itself if it is not. isMIG says which.
|
||||
func migFromNVML(card GPU, dev nvmlMIGCard) (out []GPU, isMIG bool) {
|
||||
current, _, ok := dev.MIGMode()
|
||||
if !ok || !current {
|
||||
return []GPU{card}, false
|
||||
}
|
||||
n := dev.MaxMIGDevices()
|
||||
for i := range n {
|
||||
h, ok := dev.MIGDevice(i)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
profile := ""
|
||||
if m := nvmlMIGName.FindStringSubmatch(h.Name()); m != nil {
|
||||
profile = m[1]
|
||||
} else if n, mem, ok := h.Attributes(); ok {
|
||||
// The convention NVIDIA's names follow: compute slices, then the
|
||||
// memory in whole gigabytes.
|
||||
profile = fmt.Sprintf("%dg.%dgb", n, int(math.Round(float64(mem)/1024)))
|
||||
}
|
||||
g := migInstance(card, i, profile, h.UUID())
|
||||
g.MIG.GPUInstance, g.MIG.ComputeInstance = h.Instances()
|
||||
if total, used, ok := h.Memory(); ok {
|
||||
g.MemoryTotalMB, g.MemoryUsedMB = total, used
|
||||
} else {
|
||||
g.MemoryTotalMB = MIGProfileMemoryGB(profile) * 1024
|
||||
}
|
||||
assessHealth(&g)
|
||||
out = append(out, g)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
card.Health.Problems = append(card.Health.Problems, migProblemNoInstances)
|
||||
return []GPU{card}, true
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// --- what the doctor reports ---
|
||||
|
||||
// MIGCard is one card's MIG state, as `llmgw doctor` reports it.
|
||||
type MIGCard struct {
|
||||
Index int `json:"index"`
|
||||
Name string `json:"name,omitempty"`
|
||||
// Enabled is the mode in force; PendingEnabled the mode after the next
|
||||
// reset of the card, which differs from it until the card is reset.
|
||||
Enabled bool `json:"enabled"`
|
||||
PendingEnabled bool `json:"pending_enabled"`
|
||||
// Instances are the MIG devices an engine can be given, as nvidia-smi -L
|
||||
// lists them.
|
||||
Instances []MIGListed `json:"instances,omitempty"`
|
||||
// GPUInstances and ComputeInstances are nvidia-smi mig -lgi and -lci: a
|
||||
// GPU instance with no compute instance in it is not a device yet.
|
||||
GPUInstances []MIGInstance `json:"gpu_instances,omitempty"`
|
||||
ComputeInstances []MIGInstance `json:"compute_instances,omitempty"`
|
||||
}
|
||||
|
||||
// MIGListed is one instance an engine can be given.
|
||||
type MIGListed struct {
|
||||
Device int `json:"device"`
|
||||
Profile string `json:"profile"`
|
||||
UUID string `json:"uuid"`
|
||||
}
|
||||
|
||||
// MIGInstance is one row of nvidia-smi mig -lgi or -lci.
|
||||
type MIGInstance struct {
|
||||
GPU int `json:"gpu"`
|
||||
Profile string `json:"profile"`
|
||||
// ProfileID is NVIDIA's number for the profile.
|
||||
ProfileID int `json:"profile_id"`
|
||||
// GPUInstance is the GPU instance's id; ComputeInstance the compute
|
||||
// instance's within it, -1 in a -lgi row.
|
||||
GPUInstance int `json:"gpu_instance"`
|
||||
ComputeInstance int `json:"compute_instance"`
|
||||
Placement string `json:"placement,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
// -lgi: "| 0 MIG 3g.40gb 9 2 4:4 |"
|
||||
migLGIRow = regexp.MustCompile(`^\|\s*(\d+)\s+MIG\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+:\d+)\s*\|`)
|
||||
// -lci: "| 0 1 MIG 3g.40gb 2 0 0:3 |"
|
||||
migLCIRow = regexp.MustCompile(`^\|\s*(\d+)\s+(\d+)\s+MIG\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+:\d+)\s*\|`)
|
||||
)
|
||||
|
||||
// ParseMIGInstances reads nvidia-smi mig -lgi or -lci, whichever it is
|
||||
// given: the two tables differ by the GPU instance column -lci adds. "No GPU
|
||||
// instances found" and the like are no rows, not an error.
|
||||
func ParseMIGInstances(out string) []MIGInstance {
|
||||
var res []MIGInstance
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if m := migLCIRow.FindStringSubmatch(line); m != nil {
|
||||
res = append(res, MIGInstance{
|
||||
GPU: atoiOr(m[1], -1), GPUInstance: atoiOr(m[2], -1), Profile: m[3],
|
||||
ProfileID: atoiOr(m[4], -1), ComputeInstance: atoiOr(m[5], -1), Placement: m[6],
|
||||
})
|
||||
continue
|
||||
}
|
||||
if m := migLGIRow.FindStringSubmatch(line); m != nil {
|
||||
res = append(res, MIGInstance{
|
||||
GPU: atoiOr(m[1], -1), Profile: m[2], ProfileID: atoiOr(m[3], -1),
|
||||
GPUInstance: atoiOr(m[4], -1), ComputeInstance: -1, Placement: m[5],
|
||||
})
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// DiscoverMIG reads every card's MIG state for the doctor: the mode from the
|
||||
// XML report, the devices from -L, the instances from nvidia-smi mig. Only
|
||||
// cards that support MIG are listed, and an error is returned only when the
|
||||
// report itself cannot be read.
|
||||
func DiscoverMIG(ctx context.Context, binary string) ([]MIGCard, error) {
|
||||
out, err := exec.CommandContext(ctx, binary, "-q", "-x").Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("running %s -q -x: %w", binary, err)
|
||||
}
|
||||
var list, lgi, lci string
|
||||
if b, err := exec.CommandContext(ctx, binary, "-L").Output(); err == nil {
|
||||
list = string(b)
|
||||
}
|
||||
// nvidia-smi mig exits non-zero when there is nothing to list, with the
|
||||
// table or the reason on its output either way.
|
||||
b, _ := exec.CommandContext(ctx, binary, "mig", "-lgi").CombinedOutput()
|
||||
lgi = string(b)
|
||||
b, _ = exec.CommandContext(ctx, binary, "mig", "-lci").CombinedOutput()
|
||||
lci = string(b)
|
||||
return buildMIGCards(out, list, lgi, lci)
|
||||
}
|
||||
|
||||
// buildMIGCards is DiscoverMIG from the commands' output.
|
||||
func buildMIGCards(report []byte, list, lgi, lci string) ([]MIGCard, error) {
|
||||
var log struct {
|
||||
GPUs []struct {
|
||||
Name string `xml:"product_name"`
|
||||
Current string `xml:"mig_mode>current_mig"`
|
||||
Pending string `xml:"mig_mode>pending_mig"`
|
||||
} `xml:"gpu"`
|
||||
}
|
||||
if err := xml.Unmarshal(report, &log); err != nil {
|
||||
return nil, fmt.Errorf("reading nvidia-smi's report: %w", err)
|
||||
}
|
||||
listed := parseSMIList(list)
|
||||
gis, cis := ParseMIGInstances(lgi), ParseMIGInstances(lci)
|
||||
var out []MIGCard
|
||||
for i, g := range log.GPUs {
|
||||
cur, pend := strings.TrimSpace(g.Current), strings.TrimSpace(g.Pending)
|
||||
// A card without MIG says N/A, or nothing on a driver that predates
|
||||
// it; neither is worth a line.
|
||||
if !enabled(cur) && !enabled(pend) && !strings.EqualFold(cur, "Disabled") {
|
||||
continue
|
||||
}
|
||||
c := MIGCard{Index: i, Name: strings.TrimSpace(g.Name), Enabled: enabled(cur), PendingEnabled: enabled(pend)}
|
||||
for _, l := range listed[i] {
|
||||
c.Instances = append(c.Instances, MIGListed(l))
|
||||
}
|
||||
for _, gi := range gis {
|
||||
if gi.GPU == i && gi.ComputeInstance < 0 {
|
||||
c.GPUInstances = append(c.GPUInstances, gi)
|
||||
}
|
||||
}
|
||||
for _, ci := range cis {
|
||||
if ci.GPU == i && ci.ComputeInstance >= 0 {
|
||||
c.ComputeInstances = append(c.ComputeInstances, ci)
|
||||
}
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Two A100 80GB cards: card 0 in MIG mode, cut into two 3g.40gb instances,
|
||||
// card 1 whole. What nvidia-smi prints for that machine, by command. None of
|
||||
// it is from real MIG hardware, which this was written without; the shapes
|
||||
// follow NVIDIA's documentation and the output of drivers R470 to R550.
|
||||
const (
|
||||
migQuery = `0, GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77, NVIDIA A100-SXM4-80GB, 81920, 0, 8.0, 00000000:07:00.0, 550.54.15, 31, 0, [N/A]
|
||||
1, GPU-1f2e3d4c-5b6a-7980-a1b2-c3d4e5f60718, NVIDIA A100-SXM4-80GB, 81920, 0, 8.0, 00000000:0F:00.0, 550.54.15, 33, 0, 0
|
||||
`
|
||||
migList = `GPU 0: NVIDIA A100-SXM4-80GB (UUID: GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77)
|
||||
MIG 3g.40gb Device 0: (UUID: MIG-c6d4f1ef-42e4-5de3-91c7-45d71c87eb3f)
|
||||
MIG 3g.40gb Device 1: (UUID: MIG-0f7c3a2e-9d1b-5a8e-b3c4-1e2f3a4b5c6d)
|
||||
GPU 1: NVIDIA A100-SXM4-80GB (UUID: GPU-1f2e3d4c-5b6a-7980-a1b2-c3d4e5f60718)
|
||||
`
|
||||
migReport = `<?xml version="1.0" ?>
|
||||
<nvidia_smi_log>
|
||||
<driver_version>550.54.15</driver_version>
|
||||
<gpu id="00000000:07:00.0">
|
||||
<product_name>NVIDIA A100-SXM4-80GB</product_name>
|
||||
<mig_mode><current_mig>Enabled</current_mig><pending_mig>Enabled</pending_mig></mig_mode>
|
||||
<mig_devices>
|
||||
<mig_device>
|
||||
<index>1</index>
|
||||
<gpu_instance_id>1</gpu_instance_id>
|
||||
<compute_instance_id>0</compute_instance_id>
|
||||
<device_attributes><shared><multiprocessor_count>42</multiprocessor_count></shared></device_attributes>
|
||||
<fb_memory_usage><total>40192 MiB</total><reserved>0 MiB</reserved><used>21000 MiB</used><free>19192 MiB</free></fb_memory_usage>
|
||||
</mig_device>
|
||||
<mig_device>
|
||||
<index>0</index>
|
||||
<gpu_instance_id>2</gpu_instance_id>
|
||||
<compute_instance_id>0</compute_instance_id>
|
||||
<fb_memory_usage><total>40192 MiB</total><reserved>0 MiB</reserved><used>37 MiB</used><free>40155 MiB</free></fb_memory_usage>
|
||||
</mig_device>
|
||||
</mig_devices>
|
||||
<fb_memory_usage><total>81920 MiB</total><used>21037 MiB</used></fb_memory_usage>
|
||||
<processes>
|
||||
<process_info>
|
||||
<gpu_instance_id>1</gpu_instance_id>
|
||||
<compute_instance_id>0</compute_instance_id>
|
||||
<pid>4100</pid><type>C</type><process_name>vllm</process_name>
|
||||
<used_memory>20900 MiB</used_memory>
|
||||
</process_info>
|
||||
</processes>
|
||||
</gpu>
|
||||
<gpu id="00000000:0F:00.0">
|
||||
<product_name>NVIDIA A100-SXM4-80GB</product_name>
|
||||
<mig_mode><current_mig>Disabled</current_mig><pending_mig>Disabled</pending_mig></mig_mode>
|
||||
<mig_devices>None</mig_devices>
|
||||
<fb_memory_usage><total>81920 MiB</total><used>300 MiB</used></fb_memory_usage>
|
||||
<processes>
|
||||
<process_info>
|
||||
<gpu_instance_id>N/A</gpu_instance_id>
|
||||
<compute_instance_id>N/A</compute_instance_id>
|
||||
<pid>5200</pid><type>C</type><used_memory>250 MiB</used_memory>
|
||||
</process_info>
|
||||
</processes>
|
||||
</gpu>
|
||||
</nvidia_smi_log>`
|
||||
migLGI = `+-------------------------------------------------------+
|
||||
| GPU instances: |
|
||||
| GPU Name Profile Instance Placement |
|
||||
| ID ID Start:Size |
|
||||
|=======================================================|
|
||||
| 0 MIG 3g.40gb 9 1 4:4 |
|
||||
+-------------------------------------------------------+
|
||||
| 0 MIG 3g.40gb 9 2 0:4 |
|
||||
+-------------------------------------------------------+
|
||||
`
|
||||
migLCI = `+--------------------------------------------------------------------+
|
||||
| Compute instances: |
|
||||
| GPU GPU Name Profile Instance Placement |
|
||||
| Instance ID ID Start:Size |
|
||||
| ID |
|
||||
|====================================================================|
|
||||
| 0 1 MIG 3g.40gb 2 0 0:3 |
|
||||
+--------------------------------------------------------------------+
|
||||
| 0 2 MIG 3g.40gb 2 0 0:3 |
|
||||
+--------------------------------------------------------------------+
|
||||
`
|
||||
)
|
||||
|
||||
func migMachine(t *testing.T) []GPU {
|
||||
t.Helper()
|
||||
cards, err := parseSMI(migQuery)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
report, err := parseMIGReport([]byte(migReport))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return expandMIG(cards, parseSMIList(migList), report)
|
||||
}
|
||||
|
||||
func TestACardInMIGModeIsReportedAsItsInstancesInsteadOfItself(t *testing.T) {
|
||||
gpus := migMachine(t)
|
||||
var got []string
|
||||
for _, g := range gpus {
|
||||
got = append(got, DeviceLabel(g.Index)+" "+g.Class())
|
||||
}
|
||||
want := []string{"0/mig0 a100-80g-mig-3g.40gb", "0/mig1 a100-80g-mig-3g.40gb", "1 a100-80g"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("devices = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
mig := gpus[1]
|
||||
if mig.Index != 1001 || mig.UUID != "MIG-0f7c3a2e-9d1b-5a8e-b3c4-1e2f3a4b5c6d" {
|
||||
t.Errorf("instance 1 is %d %s; an engine is given it by that UUID", mig.Index, mig.UUID)
|
||||
}
|
||||
if mig.MemoryTotalMB != 40192 || mig.MemoryUsedMB != 21000 {
|
||||
t.Errorf("instance 1 memory %d/%d, want its own 21000/40192 rather than the card's",
|
||||
mig.MemoryUsedMB, mig.MemoryTotalMB)
|
||||
}
|
||||
if m := mig.MIG; m == nil || m.ParentIndex != 0 || m.Device != 1 || m.Profile != "3g.40gb" ||
|
||||
m.GPUInstance != 1 || m.ComputeInstance != 0 || m.ParentUUID != "GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77" {
|
||||
t.Errorf("instance 1's parentage: %+v", mig.MIG)
|
||||
}
|
||||
if mig.ComputeCapability != "8.0" || mig.DriverVersion != "550.54.15" || mig.Health.TemperatureC != 31 {
|
||||
t.Errorf("what the card and its instances share was not carried: %+v", mig)
|
||||
}
|
||||
// Twenty gigabytes in use on an instance is a foreign tenant there, and
|
||||
// only there: instance 0 next to it is free.
|
||||
if mig.Health.OK() || !gpus[0].Health.OK() {
|
||||
t.Errorf("foreign memory judged per instance: 0 %v, 1 %v", gpus[0].Health.Problems, mig.Health.Problems)
|
||||
}
|
||||
// No driver reports utilisation per instance, and none is made up.
|
||||
if mig.UtilizationPercent != 0 {
|
||||
t.Errorf("an instance reported utilisation %d", mig.UtilizationPercent)
|
||||
}
|
||||
if gpus[2].IsMIG() || gpus[2].Index != 1 || gpus[2].CardIndex() != 1 || gpus[0].CardIndex() != 0 {
|
||||
t.Errorf("the whole card beside it changed: %+v", gpus[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMIGInstanceSurvivesTheTripToTheControlPlaneWithItsClass(t *testing.T) {
|
||||
g := migMachine(t)[0]
|
||||
b, err := json.Marshal(g)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(b), `"class":"a100-80g-mig-3g.40gb"`) {
|
||||
t.Errorf("the JSON carries no class for the instance: %s", b)
|
||||
}
|
||||
var back GPU
|
||||
if err := json.Unmarshal(b, &back); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Class() != g.Class() || !reflect.DeepEqual(back.MIG, g.MIG) {
|
||||
t.Errorf("came back as %s %+v", back.Class(), back.MIG)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMIGClassesAreNamedFromTheCardAndTheProfile(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
cardMB int
|
||||
profile string
|
||||
want string
|
||||
}{
|
||||
{"NVIDIA A100-SXM4-80GB MIG 3g.40gb", 81920, "3g.40gb", "a100-80g-mig-3g.40gb"},
|
||||
// The same profile name on a 40 GB card is another class: its
|
||||
// instance is the same size, but the card is not, and neither is
|
||||
// the set of profiles that card can be cut to.
|
||||
{"NVIDIA A100-SXM4-40GB MIG 3g.20gb", 40960, "3g.20gb", "a100-40g-mig-3g.20gb"},
|
||||
{"NVIDIA H100 80GB HBM3 MIG 1g.10gb+me", 81559, "1g.10gb+me", "h100-80g-mig-1g.10gb-me"},
|
||||
{"NVIDIA H100 80GB HBM3 MIG 7g.80gb", 81559, "7g.80gb", "h100-80g-mig-7g.80gb"},
|
||||
} {
|
||||
g := GPU{Name: c.name, MemoryTotalMB: 10000, MIG: &MIGDevice{ParentMemoryTotalMB: c.cardMB, Profile: c.profile}}
|
||||
if got := g.Class(); got != c.want {
|
||||
t.Errorf("%s -> %s, want %s", c.name, got, c.want)
|
||||
}
|
||||
if !IsMIGClass(g.Class()) {
|
||||
t.Errorf("%s is not recognised as a MIG class", g.Class())
|
||||
}
|
||||
}
|
||||
if IsMIGClass("a100-80g") || IsMIGClass("6000-24g") {
|
||||
t.Error("a whole card's class was taken for a MIG one")
|
||||
}
|
||||
if MIGProfileMemoryGB("a100-80g-mig-3g.40gb") != 40 || MIGProfileMemoryGB("1g.10gb+me") != 10 || MIGProfileMemoryGB("a100-80g") != 0 {
|
||||
t.Error("the instance's memory is misread from its profile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceNumbersAreShownAsCardAndInstance(t *testing.T) {
|
||||
for i, want := range map[int]string{0: "0", 7: "7", MIGIndex(0, 2): "0/mig2", MIGIndex(3, 0): "3/mig0", 1302: "3/mig2"} {
|
||||
if got := DeviceLabel(i); got != want {
|
||||
t.Errorf("DeviceLabel(%d) = %s, want %s", i, got, want)
|
||||
}
|
||||
}
|
||||
if IsMIGIndex(15) || !IsMIGIndex(MIGIndex(0, 0)) {
|
||||
t.Error("whole cards and instances are told apart wrongly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestACardInMIGModeWithNoInstancesIsKeptOutOfPlacement(t *testing.T) {
|
||||
cards, _ := parseSMI(migQuery)
|
||||
report, _ := parseMIGReport([]byte(strings.Replace(migReport,
|
||||
migReport[strings.Index(migReport, "<mig_devices>"):strings.Index(migReport, "</mig_devices>")+len("</mig_devices>")],
|
||||
"<mig_devices>None</mig_devices>", 1)))
|
||||
gpus := expandMIG(cards, parseSMIList("GPU 0: NVIDIA A100-SXM4-80GB (UUID: GPU-x)\nGPU 1: NVIDIA A100-SXM4-80GB (UUID: GPU-y)\n"), report)
|
||||
if len(gpus) != 2 || gpus[0].IsMIG() {
|
||||
t.Fatalf("got %+v", gpus)
|
||||
}
|
||||
// CUDA will not open the whole card while MIG is on, and there is no
|
||||
// instance to open instead: placing anything here fails at start.
|
||||
if gpus[0].Health.OK() || !strings.Contains(gpus[0].Health.Problems[0], "no instances") {
|
||||
t.Errorf("card 0's problems: %v", gpus[0].Health.Problems)
|
||||
}
|
||||
if !gpus[1].Health.OK() {
|
||||
t.Errorf("card 1, not in MIG mode, was flagged: %v", gpus[1].Health.Problems)
|
||||
}
|
||||
|
||||
// Instances the report sees but -L could not name cannot be given to an
|
||||
// engine either; the card says why.
|
||||
report, _ = parseMIGReport([]byte(migReport))
|
||||
gpus = expandMIG(cards, nil, report)
|
||||
if len(gpus) != 2 || gpus[0].Health.OK() || !strings.Contains(gpus[0].Health.Problems[0], "did not name") {
|
||||
t.Errorf("with -L failing: %+v", gpus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstancesAreFoundFromTheListAloneWhenTheReportCannotBeRead(t *testing.T) {
|
||||
cards, _ := parseSMI(migQuery)
|
||||
gpus := expandMIG(cards, parseSMIList(migList), nil)
|
||||
if len(gpus) != 3 || !gpus[0].IsMIG() || gpus[0].MemoryTotalMB != 40*1024 {
|
||||
t.Errorf("without the report: %+v", gpus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnOlderDriversInstanceUUIDIsTakenAsItIs(t *testing.T) {
|
||||
// R450 and R460 name an instance by its card and ids, and CUDA of that
|
||||
// era takes exactly that in CUDA_VISIBLE_DEVICES.
|
||||
l := parseSMIList("GPU 0: A100-SXM4-40GB (UUID: GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77)\n" +
|
||||
" MIG 1g.5gb Device 0: (UUID: MIG-GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77/7/0)\n")
|
||||
if len(l[0]) != 1 || l[0][0].UUID != "MIG-GPU-5d5ba0d6-d33d-2b2c-524d-9e3d8d2b8a77/7/0" || l[0][0].Profile != "1g.5gb" {
|
||||
t.Errorf("parsed %+v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessesOnAMIGCardAreChargedToTheirOwnInstance(t *testing.T) {
|
||||
mem, err := parseGPUMemory([]byte(migReport))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []GPUMemory{
|
||||
{Index: 1000, UsedMB: 37},
|
||||
{Index: 1001, UsedMB: 21000, Procs: []GPUProcess{{PID: 4100, UsedMB: 20900}}},
|
||||
{Index: 1, UsedMB: 300, Procs: []GPUProcess{{PID: 5200, UsedMB: 250}}},
|
||||
}
|
||||
if !reflect.DeepEqual(mem, want) {
|
||||
t.Errorf("got %+v\nwant %+v", mem, want)
|
||||
}
|
||||
// In the order discovery reports the devices, so a heartbeat's readings
|
||||
// line up with the inventory one for one.
|
||||
gpus := migMachine(t)
|
||||
for i := range gpus {
|
||||
if mem[i].Index != gpus[i].Index {
|
||||
t.Errorf("reading %d is for device %d, inventory has %d", i, mem[i].Index, gpus[i].Index)
|
||||
}
|
||||
}
|
||||
procs, _ := parseGPUProcesses([]byte(migReport))
|
||||
if !reflect.DeepEqual(procs, map[int][]int{1001: {4100}, 1: {5200}}) {
|
||||
t.Errorf("processes by device: %v", procs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMIGInstanceTakesItsCardsPlaceInTheTopologyButNoNVLink(t *testing.T) {
|
||||
gpus := migMachine(t)
|
||||
topo := Topology{
|
||||
NVLink: map[int]map[int]int{0: {1: 12}, 1: {0: 12}},
|
||||
NUMA: map[int]int{0: 0, 1: 1},
|
||||
NICPath: map[int]map[string]string{0: {"mlx5_0": "PIX"}},
|
||||
}
|
||||
topo.Apply(gpus)
|
||||
if len(gpus[0].NVLinkPeers) != 0 || len(gpus[1].NVLinkPeers) != 0 {
|
||||
t.Errorf("MIG instances were given NVLink peers: %v %v", gpus[0].NVLinkPeers, gpus[1].NVLinkPeers)
|
||||
}
|
||||
if gpus[1].NUMANode != 0 || gpus[1].NICPaths["mlx5_0"] != "PIX" {
|
||||
t.Errorf("instance 1 did not take its card's NUMA node and adapters: %+v", gpus[1])
|
||||
}
|
||||
if gpus[2].NUMANode != 1 || !slices.Equal(gpus[2].NVLinkPeers, []int{0}) {
|
||||
t.Errorf("the whole card's topology: %+v", gpus[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMIGInstancesAreDiscoveredThroughNvidiaSMI(t *testing.T) {
|
||||
// The real code path against a stub binary that answers each command as
|
||||
// the machine above would.
|
||||
dir := t.TempDir()
|
||||
stub := filepath.Join(dir, "nvidia-smi")
|
||||
script := "#!/bin/sh\ncase \"$1\" in\n" +
|
||||
"-L) cat <<'EOF'\n" + migList + "EOF\n;;\n" +
|
||||
"-q) cat <<'EOF'\n" + migReport + "\nEOF\n;;\n" +
|
||||
"*) cat <<'EOF'\n" + migQuery + "EOF\n;;\nesac\n"
|
||||
if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gpus, err := DiscoverGPUsSMI(t.Context(), stub)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inv := Inventory{GPUs: gpus}
|
||||
if !slices.Equal(inv.Classes(), []string{"a100-80g", "a100-80g-mig-3g.40gb"}) || len(gpus) != 3 {
|
||||
t.Errorf("classes %v from %d devices", inv.Classes(), len(gpus))
|
||||
}
|
||||
}
|
||||
|
||||
// fakeMIGCard is NVML's view of one card, as nvmlDeviceGetMigMode,
|
||||
// nvmlDeviceGetMaxMigDeviceCount and nvmlDeviceGetMigDeviceHandleByIndex
|
||||
// would give it.
|
||||
type fakeMIGCard struct {
|
||||
mode, pending, supported bool
|
||||
max int
|
||||
devs map[int]fakeMIGInstance
|
||||
}
|
||||
|
||||
func (c fakeMIGCard) MIGMode() (bool, bool, bool) { return c.mode, c.pending, c.supported }
|
||||
func (c fakeMIGCard) MaxMIGDevices() int { return c.max }
|
||||
func (c fakeMIGCard) MIGDevice(i int) (nvmlMIGInstance, bool) {
|
||||
d, ok := c.devs[i]
|
||||
return d, ok
|
||||
}
|
||||
|
||||
type fakeMIGInstance struct {
|
||||
uuid, name string
|
||||
total, used int
|
||||
gi, ci int
|
||||
slices, attrMem int
|
||||
}
|
||||
|
||||
func (m fakeMIGInstance) UUID() string { return m.uuid }
|
||||
func (m fakeMIGInstance) Name() string { return m.name }
|
||||
func (m fakeMIGInstance) Memory() (int, int, bool) {
|
||||
return m.total, m.used, m.total > 0
|
||||
}
|
||||
func (m fakeMIGInstance) Instances() (int, int) { return m.gi, m.ci }
|
||||
func (m fakeMIGInstance) Attributes() (int, int, bool) {
|
||||
return m.slices, m.attrMem, m.slices > 0
|
||||
}
|
||||
|
||||
func TestNVMLReportsACardInMIGModeAsItsInstances(t *testing.T) {
|
||||
card := GPU{Index: 2, UUID: "GPU-card", Name: "NVIDIA H100 80GB HBM3", MemoryTotalMB: 81559,
|
||||
ComputeCapability: "9.0", NUMANode: 1, Health: GPUHealth{TemperatureC: 40}}
|
||||
// Seven slots, three filled, one of them on a driver that does not put
|
||||
// the profile in the device's name.
|
||||
dev := fakeMIGCard{mode: true, pending: true, supported: true, max: 7, devs: map[int]fakeMIGInstance{
|
||||
0: {uuid: "MIG-aaa", name: "NVIDIA H100 80GB HBM3 MIG 3g.40gb", total: 40448, used: 10, gi: 2, ci: 0},
|
||||
1: {uuid: "MIG-bbb", name: "NVIDIA H100 80GB HBM3 MIG 3g.40gb", total: 40448, used: 10, gi: 1, ci: 0},
|
||||
4: {uuid: "MIG-ccc", name: "NVIDIA H100 80GB HBM3", total: 9984, gi: 9, ci: 0, slices: 1, attrMem: 9984},
|
||||
}}
|
||||
gpus, isMIG := migFromNVML(card, dev)
|
||||
if !isMIG || len(gpus) != 3 {
|
||||
t.Fatalf("got %d devices, MIG %v", len(gpus), isMIG)
|
||||
}
|
||||
var classes []string
|
||||
for _, g := range gpus {
|
||||
classes = append(classes, DeviceLabel(g.Index)+" "+g.UUID+" "+g.Class())
|
||||
}
|
||||
want := []string{"2/mig0 MIG-aaa h100-80g-mig-3g.40gb", "2/mig1 MIG-bbb h100-80g-mig-3g.40gb",
|
||||
"2/mig4 MIG-ccc h100-80g-mig-1g.10gb"}
|
||||
if !slices.Equal(classes, want) {
|
||||
t.Errorf("devices %q, want %q", classes, want)
|
||||
}
|
||||
if g := gpus[1]; g.MemoryTotalMB != 40448 || g.MIG.GPUInstance != 1 || g.NUMANode != 1 ||
|
||||
g.Health.TemperatureC != 40 || len(g.NVLinkPeers) != 0 {
|
||||
t.Errorf("instance 1: %+v", g)
|
||||
}
|
||||
|
||||
// MIG on and nothing carved: the card, kept out of placement.
|
||||
gpus, isMIG = migFromNVML(card, fakeMIGCard{mode: true, supported: true, max: 7})
|
||||
if !isMIG || len(gpus) != 1 || gpus[0].IsMIG() || gpus[0].Health.OK() {
|
||||
t.Errorf("an empty MIG card: %+v", gpus)
|
||||
}
|
||||
// MIG off, or a card without it: the card, as it always was.
|
||||
for _, d := range []fakeMIGCard{{supported: true, max: 7}, {}} {
|
||||
gpus, isMIG = migFromNVML(card, d)
|
||||
if isMIG || len(gpus) != 1 || !reflect.DeepEqual(gpus[0], card) {
|
||||
t.Errorf("a card not in MIG mode came back as %+v", gpus)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMIGInstanceTablesAreRead(t *testing.T) {
|
||||
gis := ParseMIGInstances(migLGI)
|
||||
if len(gis) != 2 || gis[0] != (MIGInstance{GPU: 0, Profile: "3g.40gb", ProfileID: 9, GPUInstance: 1,
|
||||
ComputeInstance: -1, Placement: "4:4"}) {
|
||||
t.Errorf("-lgi: %+v", gis)
|
||||
}
|
||||
cis := ParseMIGInstances(migLCI)
|
||||
if len(cis) != 2 || cis[1] != (MIGInstance{GPU: 0, GPUInstance: 2, Profile: "3g.40gb", ProfileID: 2,
|
||||
ComputeInstance: 0, Placement: "0:3"}) {
|
||||
t.Errorf("-lci: %+v", cis)
|
||||
}
|
||||
if got := ParseMIGInstances("No GPU instances found: Not Found\n"); len(got) != 0 {
|
||||
t.Errorf("nothing to list read as %+v", got)
|
||||
}
|
||||
|
||||
cards, err := buildMIGCards([]byte(migReport), migList, migLGI, migLCI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cards) != 2 || !cards[0].Enabled || len(cards[0].Instances) != 2 || len(cards[0].GPUInstances) != 2 ||
|
||||
len(cards[0].ComputeInstances) != 2 || cards[1].Enabled {
|
||||
t.Errorf("cards: %+v", cards)
|
||||
}
|
||||
}
|
||||
@@ -166,19 +166,25 @@ func splitTabs(l string) []string {
|
||||
|
||||
// Apply puts the topology on the GPUs it describes. What a GPU already knows
|
||||
// — NVLink peers from NVML, which is the more exact source — is kept.
|
||||
//
|
||||
// The matrix is of whole cards. A MIG instance takes its card's NUMA node and
|
||||
// adapters, and none of its NVLink: instances cannot reach each other or any
|
||||
// other card over it, and peers listed for one would draw a tensor-parallel
|
||||
// group onto it.
|
||||
func (t Topology) Apply(gpus []GPU) {
|
||||
for i := range gpus {
|
||||
g := &gpus[i]
|
||||
if len(g.NVLinkPeers) == 0 {
|
||||
for peer := range t.NVLink[g.Index] {
|
||||
card := g.CardIndex()
|
||||
if len(g.NVLinkPeers) == 0 && !g.IsMIG() {
|
||||
for peer := range t.NVLink[card] {
|
||||
g.NVLinkPeers = append(g.NVLinkPeers, peer)
|
||||
}
|
||||
sort.Ints(g.NVLinkPeers)
|
||||
}
|
||||
if n, ok := t.NUMA[g.Index]; ok {
|
||||
if n, ok := t.NUMA[card]; ok {
|
||||
g.NUMANode = n
|
||||
}
|
||||
if paths := t.NICPath[g.Index]; len(paths) > 0 {
|
||||
if paths := t.NICPath[card]; len(paths) > 0 {
|
||||
g.NICPaths = paths
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,9 @@ type Profile struct {
|
||||
// Adapters are LoRA adapters to load beside the model, in order: an
|
||||
// adapter's index is the id requests apply it by.
|
||||
Adapters []Adapter
|
||||
// KVEvents has the engine publish its KV cache events to the agent,
|
||||
// for the router's precise index. vLLM only.
|
||||
KVEvents bool `json:"kv_events,omitempty"`
|
||||
}
|
||||
|
||||
// ShardSpec is one shard of one replica on this node.
|
||||
@@ -62,6 +65,12 @@ type ShardSpec struct {
|
||||
|
||||
// GPUIndices are the local GPUs this shard uses.
|
||||
GPUIndices []int
|
||||
// GPUUUIDs name the same devices by UUID, in the same order, and are set
|
||||
// by the agent only when one of them is a MIG instance. An instance has
|
||||
// no index CUDA knows: CUDA_VISIBLE_DEVICES=MIG-<uuid> is the only way to
|
||||
// give a process one, and the indices placement uses for it (1000 and
|
||||
// up) mean nothing to CUDA.
|
||||
GPUUUIDs []string `json:"gpu_uuids,omitempty"`
|
||||
// HCAs are the adapters of the chosen fabric, and only that fabric. A shard
|
||||
// must never be given HCAs from two fabrics.
|
||||
HCAs []string
|
||||
@@ -84,6 +93,11 @@ type ShardSpec struct {
|
||||
// and accounting. Given to the engine in its environment rather than on
|
||||
// its command line, which every user on the node can read.
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
// KVEventsPort is the loopback port the agent receives this shard's KV
|
||||
// cache events on, chosen by the agent; zero when it publishes none.
|
||||
// Kept with the spec so an agent that restarts listens where the engine
|
||||
// it adopts is still sending.
|
||||
KVEventsPort int `json:"kv_events_port,omitempty"`
|
||||
// Threads is the CPU cores placement reserved for a shard with no GPU,
|
||||
// and so what its engine computes on. Zero leaves it to the engine's own
|
||||
// configuration.
|
||||
@@ -168,6 +182,13 @@ type CPUFallback interface {
|
||||
Devices(ctx context.Context) ([]string, error)
|
||||
}
|
||||
|
||||
// HelpCommand is an engine whose program is not asked for its help by
|
||||
// running the command's path with --help, because the path is an interpreter
|
||||
// starting it through a launcher.
|
||||
type HelpCommand interface {
|
||||
HelpCommand(c Command) (path string, args []string)
|
||||
}
|
||||
|
||||
// GPUInfo is the subset of GPU facts validation needs.
|
||||
type GPUInfo struct {
|
||||
Index int
|
||||
@@ -187,6 +208,7 @@ func NewRegistry(cfg Config) *Registry {
|
||||
r.Add(&VLLM{cfg: cfg.VLLM})
|
||||
r.Add(&SGLang{cfg: cfg.SGLang})
|
||||
r.Add(&LlamaCpp{cfg: cfg.LlamaCpp})
|
||||
r.Add(&TRTLLM{cfg: cfg.TRTLLM})
|
||||
r.Add(&Sim{cfg: cfg.Sim})
|
||||
return r
|
||||
}
|
||||
@@ -232,7 +254,10 @@ type Config struct {
|
||||
VLLM VLLMConfig `koanf:"vllm"`
|
||||
SGLang SGLangConfig `koanf:"sglang"`
|
||||
LlamaCpp LlamaCppConfig `koanf:"llamacpp"`
|
||||
Sim SimConfig `koanf:"sim"`
|
||||
// TRTLLM is TensorRT-LLM, which the agent does not install: a node
|
||||
// offers it only when its interpreter is named here.
|
||||
TRTLLM TRTLLMConfig `koanf:"trtllm"`
|
||||
Sim SimConfig `koanf:"sim"`
|
||||
}
|
||||
|
||||
// --- shared helpers ---
|
||||
@@ -257,7 +282,7 @@ func NCCLEnv(s ShardSpec) map[string]string { return baseEnv(s) }
|
||||
// one instead of timing out.
|
||||
func baseEnv(s ShardSpec) map[string]string {
|
||||
env := map[string]string{
|
||||
"CUDA_VISIBLE_DEVICES": joinInts(s.GPUIndices),
|
||||
"CUDA_VISIBLE_DEVICES": visibleDevices(s),
|
||||
// The indices above are nvidia-smi's, which counts by PCI bus. CUDA
|
||||
// counts fastest first unless told otherwise, and on a node with two
|
||||
// kinds of GPU the shard would get a different card than placement
|
||||
@@ -329,6 +354,21 @@ func materializeEnv(generated map[string]string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// visibleDevices is CUDA_VISIBLE_DEVICES for a shard: the indices placement
|
||||
// gave it, or their UUIDs when the agent named them, which it does for a MIG
|
||||
// instance.
|
||||
func visibleDevices(s ShardSpec) string {
|
||||
if len(s.GPUUUIDs) > 0 {
|
||||
return strings.Join(s.GPUUUIDs, ",")
|
||||
}
|
||||
return joinInts(s.GPUIndices)
|
||||
}
|
||||
|
||||
// OnMIG reports whether the shard was given a MIG instance.
|
||||
func (s ShardSpec) OnMIG() bool {
|
||||
return slices.ContainsFunc(s.GPUUUIDs, func(u string) bool { return strings.HasPrefix(u, "MIG-") })
|
||||
}
|
||||
|
||||
func joinInts(v []int) string {
|
||||
parts := make([]string, len(v))
|
||||
for i, n := range v {
|
||||
|
||||
@@ -366,6 +366,26 @@ func TestEnginesListenOnTheAddressTheyAreGiven(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSGLangIsStartedServingItsMetrics(t *testing.T) {
|
||||
// Without --enable-metrics SGLang has no /metrics, and every scrape of
|
||||
// the replica fails as though it were unreachable.
|
||||
if cmd := buildOne(t, &SGLang{}, singleNodeSpec()); !slices.Contains(cmd.Args, "--enable-metrics") {
|
||||
t.Errorf("not started with its metrics: %v", cmd.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSGLangIsAskedForItsHelpThroughItsModule(t *testing.T) {
|
||||
g := &SGLang{cfg: SGLangConfig{Python: "/opt/sglang/bin/python"}}
|
||||
g.UseInstalled("/opt/llmgw/engines/sglang/0.5.21-cu13/bin/python")
|
||||
path, args := g.HelpCommand(Command{})
|
||||
if path != "/opt/llmgw/engines/sglang/0.5.21-cu13/bin/python" {
|
||||
t.Errorf("asked %s, not the interpreter it was installed into", path)
|
||||
}
|
||||
if !slices.Equal(args, []string{"-m", "sglang.launch_server", "--help"}) {
|
||||
t.Errorf("asked %v", args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSGLangSingleNodeOmitsMultiNodeFlags(t *testing.T) {
|
||||
cmd := buildOne(t, &SGLang{}, singleNodeSpec())
|
||||
for _, flag := range []string{"--nnodes", "--node-rank", "--dist-init-addr"} {
|
||||
@@ -457,14 +477,14 @@ func TestValidateRequiresModelPath(t *testing.T) {
|
||||
|
||||
func TestRegistry(t *testing.T) {
|
||||
r := NewRegistry(Config{})
|
||||
if got := r.Names(); !slices.Equal(got, []string{"llamacpp", "sglang", "sim", "vllm"}) {
|
||||
if got := r.Names(); !slices.Equal(got, []string{"llamacpp", "sglang", "sim", "trtllm", "vllm"}) {
|
||||
t.Errorf("registry contents: %v", got)
|
||||
}
|
||||
if _, err := r.Get("vllm"); err != nil {
|
||||
t.Errorf("vllm missing: %v", err)
|
||||
}
|
||||
err := func() error { _, err := r.Get("nope"); return err }()
|
||||
if err == nil || !strings.Contains(err.Error(), "llamacpp, sglang, sim, vllm") {
|
||||
if err == nil || !strings.Contains(err.Error(), "llamacpp, sglang, sim, trtllm, vllm") {
|
||||
t.Errorf("an unknown engine should list what is available: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package engines
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAVLLMShardWithKVEventsPublishesToTheAgentOnLoopback(t *testing.T) {
|
||||
s := singleNodeSpec()
|
||||
s.Profile.KVEvents = true
|
||||
s.KVEventsPort = 5999
|
||||
s.Profile.Args = []string{"--max-model-len", "8192"}
|
||||
cmd := buildOne(t, &VLLM{}, s)
|
||||
|
||||
i := slices.Index(cmd.Args, "--kv-events-config")
|
||||
if i < 0 || !strings.Contains(cmd.Args[i+1], `"endpoint":"tcp://127.0.0.1:5999"`) {
|
||||
t.Fatalf("args %v should name the agent's loopback port", cmd.Args)
|
||||
}
|
||||
if j := slices.Index(cmd.Args, "--prefix-caching-hash-algo"); j < 0 || cmd.Args[j+1] != "sha256_cbor" {
|
||||
t.Fatalf("args %v should pin the hashing the router computes", cmd.Args)
|
||||
}
|
||||
if slices.Index(cmd.Args, "--max-model-len") < i {
|
||||
t.Fatal("profile arguments come last, so an operator can still override")
|
||||
}
|
||||
if !slices.Contains(cmd.Env, "PYTHONHASHSEED=1729") {
|
||||
t.Fatalf("env %v should fix the hash seed", cmd.Env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoKVEventsWithoutAPortOrOffTheLeader(t *testing.T) {
|
||||
s := singleNodeSpec()
|
||||
s.Profile.KVEvents = true // but the agent could not listen
|
||||
if cmd := buildOne(t, &VLLM{}, s); slices.Contains(cmd.Args, "--kv-events-config") {
|
||||
t.Fatal("an engine told to publish where nobody listens only fills a queue")
|
||||
}
|
||||
w := multiNodeSpec(1)
|
||||
w.Profile.KVEvents, w.KVEventsPort = true, 5999
|
||||
if cmd := buildEngine(t, &VLLM{}, w); slices.Contains(cmd.Args, "--kv-events-config") {
|
||||
t.Fatal("a headless worker has no scheduler to publish from")
|
||||
}
|
||||
off := singleNodeSpec()
|
||||
off.KVEventsPort = 5999
|
||||
if cmd := buildOne(t, &VLLM{}, off); slices.Contains(cmd.Args, "--kv-events-config") {
|
||||
t.Fatal("kv_events is opt-in")
|
||||
}
|
||||
}
|
||||
@@ -178,7 +178,11 @@ func (l *LlamaCpp) Commands(s ShardSpec) ([]Command, error) {
|
||||
// as the driver lists them, which on NVIDIA follows the same bus order
|
||||
// as nvidia-smi; were it not to, the shard would not hold memory on its
|
||||
// own GPUs, and starting it checks exactly that.
|
||||
if len(s.GPUIndices) > 0 {
|
||||
//
|
||||
// Not on a MIG instance, which Vulkan does not see at all: only CUDA
|
||||
// opens one, by the UUID CUDA_VISIBLE_DEVICES carries, and an index here
|
||||
// would name some other card.
|
||||
if len(s.GPUIndices) > 0 && !s.OnMIG() {
|
||||
env["GGML_VK_VISIBLE_DEVICES"] = joinInts(s.GPUIndices)
|
||||
}
|
||||
return []Command{{
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package engines
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RuntimeLoRAEnv is the variable that lets vLLM load and unload adapters
|
||||
// while it runs, through POST /v1/load_lora_adapter and
|
||||
// /v1/unload_lora_adapter. Without it those routes do not exist.
|
||||
//
|
||||
// It doubles as the mark that a profile's adapters load on demand: the
|
||||
// catalog sets it for a model with max_loaded_adapters and refuses it set by
|
||||
// hand anywhere else, so it cannot disagree with what the router does.
|
||||
const RuntimeLoRAEnv = "VLLM_ALLOW_RUNTIME_LORA_UPDATING"
|
||||
|
||||
// RuntimeLoRADir is where an agent links each adapter it fetched for a
|
||||
// replica whose adapters load on demand, under the adapter's name, relative
|
||||
// to the directory engines run in.
|
||||
//
|
||||
// Relative on purpose. The router asks the engine to load an adapter by a
|
||||
// path, and does not know where any node keeps its cache — each node may
|
||||
// keep it somewhere else, and a replica spanning nodes reads the adapter on
|
||||
// every one of them. vLLM resolves a relative path that exists against its
|
||||
// working directory, which on every node is the one the agent starts
|
||||
// engines in, and the agent links the adapter there before the engine
|
||||
// starts. So one path, the same everywhere, names the right file on each.
|
||||
const RuntimeLoRADir = "llmgw-lora"
|
||||
|
||||
// WithRuntimeLoRA has a vLLM profile with adapters start holding none of
|
||||
// them, ready to load up to limit at a time on demand: the engine is allowed
|
||||
// runtime loading, and --max-loras — how many adapters one batch may mix —
|
||||
// is the cap, unless the operator's arguments already say. Anything else is
|
||||
// returned as it is.
|
||||
func (p Profile) WithRuntimeLoRA(limit int) Profile {
|
||||
if limit <= 0 || p.Engine != "vllm" || len(p.Adapters) == 0 {
|
||||
return p
|
||||
}
|
||||
env := maps.Clone(p.Env)
|
||||
if env == nil {
|
||||
env = map[string]string{}
|
||||
}
|
||||
env[RuntimeLoRAEnv] = "True"
|
||||
p.Env = env
|
||||
if !hasFlag(p.Args, "--max-loras") {
|
||||
p.Args = append([]string{"--max-loras", strconv.Itoa(limit)}, p.Args...)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// RuntimeLoRA reports whether a profile's adapters load on demand rather
|
||||
// than at start.
|
||||
func (p Profile) RuntimeLoRA() bool {
|
||||
v, ok := p.Env[RuntimeLoRAEnv]
|
||||
return ok && v != "" && v != "0" && !strings.EqualFold(v, "false")
|
||||
}
|
||||
|
||||
// RuntimeLoRAPath is the lora_path the router gives vLLM to load an adapter
|
||||
// from: the link the agent made, or, for a Hugging Face repository id, the
|
||||
// id, which vLLM downloads itself and the agent leaves alone.
|
||||
func RuntimeLoRAPath(name, source string) string {
|
||||
if IsHubID(source) {
|
||||
return source
|
||||
}
|
||||
return RuntimeLoRADir + "/" + name
|
||||
}
|
||||
|
||||
// IsHubID reports whether a source is a bare Hugging Face repository id
|
||||
// ("org/repo") rather than a URL or a path: what the agent passes to an
|
||||
// engine untouched.
|
||||
func IsHubID(source string) bool {
|
||||
switch {
|
||||
case source == "",
|
||||
strings.HasPrefix(source, "/"), strings.HasPrefix(source, "./"), strings.HasPrefix(source, "../"),
|
||||
strings.HasPrefix(source, "~"),
|
||||
strings.HasPrefix(source, "http://"), strings.HasPrefix(source, "https://"),
|
||||
strings.HasPrefix(source, "hf:"):
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// LinkRuntimeAdapters makes RuntimeLoRADir under dir hold a link to each
|
||||
// fetched adapter, named as the adapter is. A link already there is
|
||||
// replaced, so a replica started after an adapter's source changed loads
|
||||
// the new one. Adapters still named by a repository id have nothing local
|
||||
// to link.
|
||||
func LinkRuntimeAdapters(dir string, ads []Adapter) error {
|
||||
if len(ads) == 0 {
|
||||
return nil
|
||||
}
|
||||
root := filepath.Join(dir, RuntimeLoRADir)
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
return fmt.Errorf("making the adapters' directory: %w", err)
|
||||
}
|
||||
for _, a := range ads {
|
||||
if IsHubID(a.Path) {
|
||||
continue
|
||||
}
|
||||
if a.Name == "" || strings.ContainsAny(a.Name, `/\`) || a.Name == "." || a.Name == ".." {
|
||||
return fmt.Errorf("adapter %q: not a name a file can have", a.Name)
|
||||
}
|
||||
target, err := filepath.Abs(a.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("adapter %s: %w", a.Name, err)
|
||||
}
|
||||
link := filepath.Join(root, a.Name)
|
||||
// Made beside the old one and renamed over it, so an engine loading
|
||||
// the adapter at this moment sees one or the other and never neither.
|
||||
tmp := link + ".new"
|
||||
_ = os.Remove(tmp)
|
||||
if err := os.Symlink(target, tmp); err != nil {
|
||||
return fmt.Errorf("adapter %s: %w", a.Name, err)
|
||||
}
|
||||
if err := os.Rename(tmp, link); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return fmt.Errorf("adapter %s: %w", a.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loraModules is vLLM's --lora-modules for adapters loaded at start: one
|
||||
// flag followed by every name=path, since vLLM keeps only the last of a
|
||||
// repeated flag.
|
||||
func loraModules(ads []Adapter) []string {
|
||||
out := []string{"--lora-modules"}
|
||||
for _, a := range ads {
|
||||
out = append(out, a.Name+"="+a.Path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package engines
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func adapterSpec() ShardSpec {
|
||||
s := singleNodeSpec()
|
||||
s.Profile.Engine = "vllm"
|
||||
s.Profile.Adapters = []Adapter{
|
||||
{Name: "sql", Path: "/cache/ab-sql"},
|
||||
{Name: "docs", Path: "/cache/cd-docs"},
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestVLLMLoadsEveryAdapterAtStartUnderOneFlag(t *testing.T) {
|
||||
cmd := buildOne(t, &VLLM{}, adapterSpec())
|
||||
if !slices.Contains(cmd.Args, "--enable-lora") {
|
||||
t.Errorf("LoRA not enabled: %v", cmd.Args)
|
||||
}
|
||||
// vLLM keeps only the last of a repeated --lora-modules, so both
|
||||
// adapters must follow one flag.
|
||||
i := slices.Index(cmd.Args, "--lora-modules")
|
||||
if i < 0 || !slices.Equal(cmd.Args[i+1:i+3], []string{"sql=/cache/ab-sql", "docs=/cache/cd-docs"}) {
|
||||
t.Errorf("adapters not registered at start: %v", cmd.Args)
|
||||
}
|
||||
if n := countFlag(cmd.Args, "--lora-modules"); n != 1 {
|
||||
t.Errorf("--lora-modules given %d times", n)
|
||||
}
|
||||
if _, set := envMap(cmd.Env)[RuntimeLoRAEnv]; set {
|
||||
t.Error("runtime loading was allowed for adapters loaded at start")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVLLMWithAdaptersOnDemandStartsHoldingNone(t *testing.T) {
|
||||
s := adapterSpec()
|
||||
s.Profile = s.Profile.WithRuntimeLoRA(3)
|
||||
cmd := buildOne(t, &VLLM{}, s)
|
||||
if slices.Contains(cmd.Args, "--lora-modules") {
|
||||
t.Errorf("adapters registered at start: %v", cmd.Args)
|
||||
}
|
||||
if !slices.Contains(cmd.Args, "--enable-lora") || argValue(cmd.Args, "--max-loras") != "3" {
|
||||
t.Errorf("want LoRA enabled with the cap as --max-loras: %v", cmd.Args)
|
||||
}
|
||||
if envMap(cmd.Env)[RuntimeLoRAEnv] != "True" {
|
||||
t.Errorf("the load and unload routes were not turned on: %v", cmd.Env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheOperatorsMaxLorasWinsOverTheCap(t *testing.T) {
|
||||
p := adapterSpec().Profile
|
||||
p.Args = []string{"--max-loras", "8"}
|
||||
got := p.WithRuntimeLoRA(3)
|
||||
if argValue(got.Args, "--max-loras") != "8" || countFlag(got.Args, "--max-loras") != 1 {
|
||||
t.Errorf("args %v", got.Args)
|
||||
}
|
||||
if p.Env != nil {
|
||||
t.Error("the profile's own env map was written to")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeLoRALeavesOtherProfilesAlone(t *testing.T) {
|
||||
llama := adapterSpec().Profile
|
||||
llama.Engine = "llamacpp"
|
||||
none := adapterSpec().Profile
|
||||
none.Adapters = nil
|
||||
for _, p := range []Profile{llama, none} {
|
||||
if got := p.WithRuntimeLoRA(2); got.RuntimeLoRA() || len(got.Args) != 0 {
|
||||
t.Errorf("%s with %d adapters: %+v", p.Engine, len(p.Adapters), got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRouterLoadsAnAdapterByItsLinkOrItsRepository(t *testing.T) {
|
||||
for source, want := range map[string]string{
|
||||
"http://mirror:8081/sql-lora/v1/": "llmgw-lora/sql",
|
||||
"/srv/adapters/sql": "llmgw-lora/sql",
|
||||
"hf:org/repo/adapter.gguf": "llmgw-lora/sql",
|
||||
"someone/sql-lora": "someone/sql-lora",
|
||||
"https://huggingface.co/someone/sql": "llmgw-lora/sql",
|
||||
} {
|
||||
if got := RuntimeLoRAPath("sql", source); got != want {
|
||||
t.Errorf("%s: %s, want %s", source, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptersAreLinkedUnderTheirNamesAndRelinkedWhenTheyChange(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
old := filepath.Join(dir, "old-sql")
|
||||
cur := filepath.Join(dir, "new-sql")
|
||||
for _, d := range []string{old, cur} {
|
||||
if err := os.Mkdir(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ads := []Adapter{{Name: "sql", Path: old}, {Name: "hub", Path: "someone/hub-lora"}}
|
||||
if err := LinkRuntimeAdapters(dir, ads); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ads[0].Path = cur
|
||||
if err := LinkRuntimeAdapters(dir, ads); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.Readlink(filepath.Join(dir, RuntimeLoRADir, "sql"))
|
||||
if err != nil || got != cur {
|
||||
t.Errorf("link to %q (%v), want %q", got, err, cur)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(dir, RuntimeLoRADir, "hub")); !os.IsNotExist(err) {
|
||||
t.Errorf("a repository id was linked: %v", err)
|
||||
}
|
||||
if err := LinkRuntimeAdapters(dir, []Adapter{{Name: "../escape", Path: cur}}); err == nil {
|
||||
t.Error("an adapter named like a path was linked")
|
||||
}
|
||||
}
|
||||
|
||||
func countFlag(args []string, flag string) int {
|
||||
n := 0
|
||||
for _, a := range args {
|
||||
if a == flag {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package engines
|
||||
|
||||
import "testing"
|
||||
|
||||
const migUUID = "MIG-c6d4f1ef-42e4-5de3-91c7-45d71c87eb3f"
|
||||
|
||||
func TestAShardOnAMIGInstanceIsGivenItByUUID(t *testing.T) {
|
||||
// Placement numbers card 0's instance 1 as 1001, which CUDA has never
|
||||
// heard of: CUDA_VISIBLE_DEVICES=1001 is no device at all, and =1 would
|
||||
// be the wrong card.
|
||||
s := singleNodeSpec()
|
||||
s.GPUIndices, s.GPUUUIDs = []int{1001}, []string{migUUID}
|
||||
s.Profile.TP = 1
|
||||
|
||||
env := envMap(buildOne(t, &VLLM{}, s).Env)
|
||||
if env["CUDA_VISIBLE_DEVICES"] != migUUID {
|
||||
t.Errorf("vLLM: CUDA_VISIBLE_DEVICES=%q, want the instance's UUID", env["CUDA_VISIBLE_DEVICES"])
|
||||
}
|
||||
|
||||
l := llamaSpec([]int{1001})
|
||||
l.GPUUUIDs = s.GPUUUIDs
|
||||
cmds, err := (&LlamaCpp{}).Commands(l)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env = envMap(cmds[0].Env)
|
||||
if env["CUDA_VISIBLE_DEVICES"] != migUUID {
|
||||
t.Errorf("llama.cpp: CUDA_VISIBLE_DEVICES=%q, want the instance's UUID", env["CUDA_VISIBLE_DEVICES"])
|
||||
}
|
||||
// Vulkan does not see MIG instances, and an index for it would name
|
||||
// some other card.
|
||||
if v, set := env["GGML_VK_VISIBLE_DEVICES"]; set {
|
||||
t.Errorf("GGML_VK_VISIBLE_DEVICES=%q on a MIG instance", v)
|
||||
}
|
||||
if v, _ := flagValue(cmds[0].Args, "--n-gpu-layers"); v != "999" {
|
||||
t.Errorf("the model was not offloaded to the instance: --n-gpu-layers %q", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAShardOnWholeCardsIsStillGivenThemByIndex(t *testing.T) {
|
||||
env := envMap(buildOne(t, &VLLM{}, singleNodeSpec()).Env)
|
||||
if env["CUDA_VISIBLE_DEVICES"] != "0,1,2,3" {
|
||||
t.Errorf("CUDA_VISIBLE_DEVICES=%q", env["CUDA_VISIBLE_DEVICES"])
|
||||
}
|
||||
cmds, _ := (&LlamaCpp{}).Commands(llamaSpec([]int{2}))
|
||||
if env := envMap(cmds[0].Env); env["GGML_VK_VISIBLE_DEVICES"] != "2" {
|
||||
t.Errorf("GGML_VK_VISIBLE_DEVICES=%q", env["GGML_VK_VISIBLE_DEVICES"])
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,15 @@ func (*SGLang) Name() string { return "sglang" }
|
||||
// HealthPath is SGLang's readiness endpoint.
|
||||
func (*SGLang) HealthPath() string { return "/health" }
|
||||
|
||||
// MetricsPath is SGLang's Prometheus endpoint.
|
||||
// HelpCommand is how to ask SGLang for its help: through its module, in the
|
||||
// environment it was installed into, since the command itself is llmgw's
|
||||
// launcher and the interpreter's own --help describes Python.
|
||||
func (g *SGLang) HelpCommand(Command) (string, []string) {
|
||||
return g.python(), []string{"-m", "sglang.launch_server", "--help"}
|
||||
}
|
||||
|
||||
// MetricsPath is SGLang's Prometheus endpoint, served only with
|
||||
// --enable-metrics.
|
||||
func (*SGLang) MetricsPath() string { return "/metrics" }
|
||||
|
||||
// Validate checks the profile against the GPUs it would run on.
|
||||
@@ -83,7 +91,13 @@ func (g *SGLang) serverCommand(s ShardSpec) (Command, error) {
|
||||
"--model-path", p.ModelPath,
|
||||
"--host", s.Host(),
|
||||
"--port", strconv.Itoa(s.HTTPPort),
|
||||
"--tp", strconv.Itoa(p.TP),
|
||||
// The flag's whole name: SGLang's documentation writes --tp, which
|
||||
// argparse accepts only as an abbreviation of --tp-size and only
|
||||
// while no other flag begins with it.
|
||||
"--tp-size", strconv.Itoa(p.TP),
|
||||
// Without it SGLang serves no /metrics at all, and the router has
|
||||
// nothing to schedule this replica by.
|
||||
"--enable-metrics",
|
||||
}
|
||||
if p.ServedModelName != "" {
|
||||
args = append(args, "--served-model-name", p.ServedModelName)
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package engines
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// TRTLLMConfig locates a TensorRT-LLM the operator installed.
|
||||
//
|
||||
// llmgw does not install TensorRT-LLM. It is a pip package pinned to one
|
||||
// CUDA, one PyTorch and an MPI the machine must provide, and NVIDIA's own
|
||||
// advice is its container; an installer that guessed at all of that would
|
||||
// fail on most machines it met, a long way into a large download. So it is
|
||||
// brought by the operator — a virtual environment, or NVIDIA's container —
|
||||
// and named here.
|
||||
type TRTLLMConfig struct {
|
||||
// Python is the interpreter of the environment TensorRT-LLM is installed
|
||||
// in: <venv>/bin/python for a virtual environment, python3 in NVIDIA's
|
||||
// container. Naming it is what makes this node offer the engine; empty
|
||||
// offers nothing.
|
||||
//
|
||||
// The interpreter rather than trtllm-serve, because llmgw starts the
|
||||
// server through a few lines of its own that make it demand the
|
||||
// gateway's key, which trtllm-serve has no option for.
|
||||
Python string `koanf:"python"`
|
||||
}
|
||||
|
||||
// TRTLLM builds TensorRT-LLM launch commands: its OpenAI-compatible server,
|
||||
// trtllm-serve, on one node.
|
||||
//
|
||||
// Written against TensorRT-LLM's documented command line and server, and not
|
||||
// yet run on hardware by anyone working on llmgw: no datacenter GPU was at
|
||||
// hand. `llmgw ctl engine-check trtllm` asks an installed one whether it
|
||||
// takes the flags built here.
|
||||
type TRTLLM struct{ cfg TRTLLMConfig }
|
||||
|
||||
// Name identifies the engine in the catalog.
|
||||
func (*TRTLLM) Name() string { return "trtllm" }
|
||||
|
||||
// HealthPath is trtllm-serve's liveness endpoint: 200 once the executor is
|
||||
// up, 503 while it is not. The supervisor's /v1/models step is what says the
|
||||
// model is being served.
|
||||
func (*TRTLLM) HealthPath() string { return "/health" }
|
||||
|
||||
// MetricsPath is trtllm-serve's Prometheus endpoint. Its /metrics is a
|
||||
// different thing — a JSON list of iteration statistics, drained by each
|
||||
// read — and a scrape there would both fail to parse and steal the numbers
|
||||
// from anyone else reading them.
|
||||
func (*TRTLLM) MetricsPath() string { return "/prometheus/metrics" }
|
||||
|
||||
// ServesHTTP reports whether this rank answers the API; a TensorRT-LLM
|
||||
// replica is one node, and so one rank.
|
||||
func (*TRTLLM) ServesHTTP(s ShardSpec) bool { return s.Leader() }
|
||||
|
||||
// Validate checks the profile against the GPUs it would run on.
|
||||
//
|
||||
// One node: trtllm-serve spans machines only when started under MPI or
|
||||
// Slurm from one of them (trtllm-llmapi-launch), and the agents each start
|
||||
// their own node's part, which is not that. Ampere or newer: the oldest
|
||||
// generation current TensorRT-LLM builds kernels for.
|
||||
func (*TRTLLM) Validate(p Profile, gpus []GPUInfo) error {
|
||||
if p.Nodes > 1 {
|
||||
return fmt.Errorf("profile %q: trtllm runs a replica on one node; "+
|
||||
"use vllm or sglang for a %d-node replica", p.Name, p.Nodes)
|
||||
}
|
||||
if err := validateCommon(p, gpus); err != nil {
|
||||
return err
|
||||
}
|
||||
return requireComputeCapability(p, gpus, 8.0, "TensorRT-LLM")
|
||||
}
|
||||
|
||||
// Commands returns the processes for one shard, which is one process. Tensor
|
||||
// and pipeline parallel ranks on the node are trtllm-serve's own MPI workers,
|
||||
// started by it.
|
||||
func (t *TRTLLM) Commands(s ShardSpec) ([]Command, error) {
|
||||
if s.NNodes > 1 {
|
||||
return nil, fmt.Errorf("trtllm: a replica spanning %d nodes is not something llmgw starts; "+
|
||||
"TensorRT-LLM runs one node per replica here", s.NNodes)
|
||||
}
|
||||
p := s.Profile
|
||||
args := []string{"-c", trtllmLauncher,
|
||||
// The subcommand by name: trtllm-serve takes a bare model as "serve",
|
||||
// but saying it costs nothing and does not depend on that default.
|
||||
"serve", p.ModelPath,
|
||||
"--host", s.Host(),
|
||||
"--port", strconv.Itoa(s.HTTPPort),
|
||||
"--tp_size", strconv.Itoa(p.TP),
|
||||
}
|
||||
if p.PP > 1 {
|
||||
args = append(args, "--pp_size", strconv.Itoa(p.PP))
|
||||
}
|
||||
if p.ServedModelName != "" {
|
||||
// Without it the model is named after its directory, and the agent's
|
||||
// readiness check, which looks for this name in /v1/models, never
|
||||
// finds it.
|
||||
args = append(args, "--served_model_name", p.ServedModelName)
|
||||
}
|
||||
// What makes the queue and the cache measurable: the options file the
|
||||
// launcher writes turns on the Prometheus endpoint and the iteration
|
||||
// statistics its gauges are set from. A placeholder here, so the flag is
|
||||
// one engine-check sees and checks; the launcher replaces it.
|
||||
args = append(args, "--extra_llm_api_options", trtllmOptionsPlaceholder)
|
||||
args = append(args, p.Args...)
|
||||
|
||||
env := baseEnv(s)
|
||||
if s.APIKey != "" {
|
||||
env[trtllmKeyEnv] = s.APIKey
|
||||
}
|
||||
// TensorRT-LLM reports usage to NVIDIA unless told not to. A gateway on
|
||||
// somebody's own network does not phone home on their behalf, and a
|
||||
// model's profile cannot make it: these are set after the profile's env.
|
||||
env["TRTLLM_NO_USAGE_STATS"] = "1"
|
||||
env["DO_NOT_TRACK"] = "1"
|
||||
return []Command{{Name: "trtllm-serve", Path: t.python(), Args: args, Env: materializeEnv(env)}}, nil
|
||||
}
|
||||
|
||||
// python is the interpreter to start trtllm-serve with.
|
||||
func (t *TRTLLM) python() string {
|
||||
if t.cfg.Python != "" {
|
||||
return t.cfg.Python
|
||||
}
|
||||
return "python3"
|
||||
}
|
||||
|
||||
// Configured reports whether the configuration names TensorRT-LLM's
|
||||
// interpreter, which is the only way a node offers it.
|
||||
func (t *TRTLLM) Configured() bool { return t.cfg.Python != "" }
|
||||
|
||||
// Probe reports the installed TensorRT-LLM's version.
|
||||
//
|
||||
// From the package's metadata rather than by importing it: the import loads
|
||||
// CUDA, MPI and PyTorch and takes longer than a probe may, while what
|
||||
// placement needs is whether the package is there. Whether it runs is
|
||||
// engine-check's question, and the replica's.
|
||||
func (t *TRTLLM) Probe(ctx context.Context) (string, error) {
|
||||
return versionOfModule(ctx, t.python(), "-c",
|
||||
"import importlib.metadata as m, importlib.util as u, sys\n"+
|
||||
"if u.find_spec('tensorrt_llm') is None: sys.exit(1)\n"+
|
||||
"sys.stdout.write(m.version('tensorrt_llm'))")
|
||||
}
|
||||
|
||||
// HelpCommand is how to ask trtllm-serve for its help: through its module,
|
||||
// since the command itself is llmgw's launcher.
|
||||
func (t *TRTLLM) HelpCommand(Command) (string, []string) {
|
||||
return t.python(), []string{"-m", "tensorrt_llm.commands.serve", "serve", "--help"}
|
||||
}
|
||||
|
||||
const (
|
||||
trtllmKeyEnv = "LLMGW_ENGINE_KEY"
|
||||
trtllmOptionsPlaceholder = "@llmgw-options"
|
||||
)
|
||||
|
||||
// trtllmLauncher starts trtllm-serve inside the process, after two things
|
||||
// trtllm-serve has no flag for.
|
||||
//
|
||||
// The key. trtllm-serve checks none, and an engine listens on the node's
|
||||
// management address, where without one anybody who can reach the port talks
|
||||
// to the model past the gateway's authentication, quotas and accounting. So
|
||||
// every FastAPI application the process makes — trtllm-serve's server is one
|
||||
// — is given a middleware demanding it, before trtllm-serve imports anything.
|
||||
// /health is left open: it says only up or down, and a supervisor of
|
||||
// TensorRT-LLM's own may ask it without a key. The key comes in the
|
||||
// environment and is taken out of it, so the MPI workers and anything else
|
||||
// started from here never hold it.
|
||||
//
|
||||
// The options. The Prometheus endpoint exists only with return_perf_metrics,
|
||||
// and its queue gauges move only with enable_iter_perf_stats; both are
|
||||
// settings of TensorRT-LLM's options file, not flags. The file is written to
|
||||
// an unnamed temporary file and passed by descriptor: nothing is left on disk
|
||||
// however the server ends.
|
||||
//
|
||||
// trtllm-serve can start further HTTP front ends as copies of its own command
|
||||
// line (--num_serve_frontends); those would not run this, so the flag is
|
||||
// refused in a profile, and a copy started anyway would be given a program
|
||||
// path that cannot exist — /dev/null is no directory — and fail rather than
|
||||
// serve without the key. Click names itself by the path's last element, so
|
||||
// trtllm-serve's messages still say trtllm-serve.
|
||||
const trtllmLauncher = `import hmac, os, sys, tempfile
|
||||
key = os.environ.pop("` + trtllmKeyEnv + `", "")
|
||||
if key:
|
||||
import fastapi
|
||||
want = ("Bearer " + key).encode()
|
||||
denied = b'{"error":{"message":"a valid API key is required","type":"invalid_request_error","code":"invalid_api_key"}}'
|
||||
class RequireKey:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] in ("http", "websocket") and scope.get("path") != "/health":
|
||||
got = b""
|
||||
for name, value in scope.get("headers") or ():
|
||||
if name == b"authorization":
|
||||
got = value
|
||||
if not hmac.compare_digest(got, want):
|
||||
if scope["type"] == "websocket":
|
||||
await send({"type": "websocket.close", "code": 1008})
|
||||
return
|
||||
await send({"type": "http.response.start", "status": 401,
|
||||
"headers": [(b"content-type", b"application/json")]})
|
||||
await send({"type": "http.response.body", "body": denied})
|
||||
return
|
||||
await self.app(scope, receive, send)
|
||||
plain_init = fastapi.FastAPI.__init__
|
||||
def init_with_key(self, *a, **kw):
|
||||
plain_init(self, *a, **kw)
|
||||
self.add_middleware(RequireKey)
|
||||
fastapi.FastAPI.__init__ = init_with_key
|
||||
args = sys.argv[1:]
|
||||
if "` + trtllmOptionsPlaceholder + `" in args:
|
||||
options = tempfile.TemporaryFile()
|
||||
options.write(b"return_perf_metrics: true\nenable_iter_perf_stats: true\n")
|
||||
options.flush()
|
||||
options.seek(0)
|
||||
args[args.index("` + trtllmOptionsPlaceholder + `")] = "/dev/fd/%d" % options.fileno()
|
||||
sys.argv = ["/dev/null/trtllm-serve"] + args
|
||||
from tensorrt_llm.commands.serve import main
|
||||
main()
|
||||
`
|
||||
@@ -0,0 +1,316 @@
|
||||
package engines
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func trtllmSpec() ShardSpec {
|
||||
s := singleNodeSpec()
|
||||
s.Profile.Engine = "trtllm"
|
||||
s.Profile.ServedModelName = "llama-3.1-70b"
|
||||
return s
|
||||
}
|
||||
|
||||
func TestTRTLLMRunsTrtllmServeWithTheFlagsItDocuments(t *testing.T) {
|
||||
s := trtllmSpec()
|
||||
s.BindAddr = "10.0.0.147"
|
||||
s.Profile.Args = []string{"--max_batch_size", "64"}
|
||||
cmd := buildOne(t, &TRTLLM{cfg: TRTLLMConfig{Python: "/opt/trtllm/bin/python"}}, s)
|
||||
|
||||
if cmd.Path != "/opt/trtllm/bin/python" {
|
||||
t.Errorf("Path=%q, expected the configured interpreter", cmd.Path)
|
||||
}
|
||||
if cmd.Args[0] != "-c" || !strings.Contains(cmd.Args[1], "from tensorrt_llm.commands.serve import main") {
|
||||
t.Fatalf("not started through the launcher: %v", cmd.Args[:2])
|
||||
}
|
||||
rest := cmd.Args[2:]
|
||||
if rest[0] != "serve" || rest[1] != "/models/llama" {
|
||||
t.Errorf("expected serve and the model first, got %v", rest[:2])
|
||||
}
|
||||
for flag, want := range map[string]string{
|
||||
"--host": "10.0.0.147", "--port": "20000", "--tp_size": "4",
|
||||
"--served_model_name": "llama-3.1-70b",
|
||||
"--extra_llm_api_options": trtllmOptionsPlaceholder,
|
||||
} {
|
||||
if got := argValue(rest, flag); got != want {
|
||||
t.Errorf("%s=%q, want %q (args %v)", flag, got, want, rest)
|
||||
}
|
||||
}
|
||||
// One pipeline stage is the default, and saying so would only be one
|
||||
// more flag for a version to rename.
|
||||
if slices.Contains(rest, "--pp_size") {
|
||||
t.Errorf("--pp_size given for a single stage: %v", rest)
|
||||
}
|
||||
// The profile's own, last, so a tuning flag is the operator's to set.
|
||||
if got := rest[len(rest)-2:]; !slices.Equal(got, []string{"--max_batch_size", "64"}) {
|
||||
t.Errorf("profile args are not last: %v", rest)
|
||||
}
|
||||
|
||||
s.Profile.TP, s.Profile.PP = 2, 2
|
||||
if got := argValue(buildOne(t, &TRTLLM{}, s).Args, "--pp_size"); got != "2" {
|
||||
t.Errorf("--pp_size=%q for two stages", got)
|
||||
}
|
||||
if got := buildOne(t, &TRTLLM{}, s).Path; got != "python3" {
|
||||
t.Errorf("unconfigured, the interpreter is %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMsKeyIsNotOnItsCommandLine(t *testing.T) {
|
||||
s := trtllmSpec()
|
||||
s.APIKey = "k1"
|
||||
cmd := buildOne(t, &TRTLLM{}, s)
|
||||
for _, a := range cmd.Args {
|
||||
if strings.Contains(a, "k1") && a != cmd.Args[1] {
|
||||
t.Errorf("the key is in the arguments: %v", cmd.Args)
|
||||
}
|
||||
}
|
||||
if envMap(cmd.Env)[trtllmKeyEnv] != "k1" {
|
||||
t.Error("the key is not in the environment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMDoesNotReportUsageToNVIDIA(t *testing.T) {
|
||||
s := trtllmSpec()
|
||||
s.Profile.Env = map[string]string{"TRTLLM_NO_USAGE_STATS": "0", "TRTLLM_ENABLE_PDL": "1"}
|
||||
env := envMap(buildOne(t, &TRTLLM{}, s).Env)
|
||||
if env["TRTLLM_NO_USAGE_STATS"] != "1" || env["DO_NOT_TRACK"] != "1" {
|
||||
t.Errorf("usage reporting is not off: %q %q", env["TRTLLM_NO_USAGE_STATS"], env["DO_NOT_TRACK"])
|
||||
}
|
||||
// Tuning still reaches it.
|
||||
if env["TRTLLM_ENABLE_PDL"] != "1" {
|
||||
t.Error("a profile's TensorRT-LLM tuning was dropped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMIsReadFromItsPrometheusEndpoint(t *testing.T) {
|
||||
// /metrics on trtllm-serve is JSON, and each read drains what it returns.
|
||||
if got := (&TRTLLM{}).MetricsPath(); got != "/prometheus/metrics" {
|
||||
t.Errorf("MetricsPath=%q", got)
|
||||
}
|
||||
if !(&TRTLLM{}).ServesHTTP(trtllmSpec()) {
|
||||
t.Error("the one rank of a replica serves its API")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMRunsAReplicaOnOneNode(t *testing.T) {
|
||||
p := trtllmSpec().Profile
|
||||
p.Nodes, p.GPUsPerNode, p.TP = 2, 4, 8
|
||||
err := (&TRTLLM{}).Validate(p, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "one node") {
|
||||
t.Errorf("a two-node profile was accepted: %v", err)
|
||||
}
|
||||
s := multiNodeSpec(0)
|
||||
s.Profile.Engine = "trtllm"
|
||||
if _, err := (&TRTLLM{}).Commands(s); err == nil {
|
||||
t.Error("a command was built for a shard of a two-node replica")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMNeedsAmpereOrNewer(t *testing.T) {
|
||||
p := trtllmSpec().Profile
|
||||
p.TP = 2
|
||||
v100 := []GPUInfo{{Index: 0, Name: "Tesla V100", ComputeCapability: "7.0"}, {Index: 1, Name: "Tesla V100", ComputeCapability: "7.0"}}
|
||||
if err := (&TRTLLM{}).Validate(p, v100); err == nil {
|
||||
t.Error("a V100 was accepted")
|
||||
}
|
||||
h100 := []GPUInfo{{Index: 0, Name: "H100", ComputeCapability: "9.0"}, {Index: 1, Name: "H100", ComputeCapability: "9.0"}}
|
||||
if err := (&TRTLLM{}).Validate(p, h100); err != nil {
|
||||
t.Errorf("two H100s were refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMProfilesMayNotOpenWhatTheAgentCloses(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"--trust_remote_code"},
|
||||
{"--num_serve_frontends", "4"},
|
||||
{"--grpc"},
|
||||
{"--config", "/etc/shadow"},
|
||||
{"--extra_llm_api_options=/tmp/x.yaml"},
|
||||
{"--served_model_name", "other"},
|
||||
{"--middleware", "evil.mw"},
|
||||
{"--tp_size", "8"},
|
||||
} {
|
||||
if err := UnsafeArgs("trtllm", args); err == nil {
|
||||
t.Errorf("%v was allowed", args)
|
||||
}
|
||||
}
|
||||
if err := UnsafeArgs("trtllm", []string{"--max_batch_size", "64", "--set", "kv_cache_config.enable_block_reuse=false",
|
||||
"--free_gpu_memory_fraction", "0.85"}); err != nil {
|
||||
t.Errorf("tuning was refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTRTLLMIsOfferedOnlyWhenItsPackageIsThere(t *testing.T) {
|
||||
there := script(t, "python3", `echo "1.3.0rc29"`)
|
||||
r := NewRegistry(Config{})
|
||||
r.engines = map[string]Engine{"trtllm": &TRTLLM{cfg: TRTLLMConfig{Python: there}}}
|
||||
if got := r.ProbeConfigured(t.Context()); got["trtllm"] != "1.3.0rc29" {
|
||||
t.Errorf("expected the version, got %v", got)
|
||||
}
|
||||
|
||||
// An interpreter without the package, which every machine has.
|
||||
absent := script(t, "python3", "exit 1")
|
||||
r.engines = map[string]Engine{"trtllm": &TRTLLM{cfg: TRTLLMConfig{Python: absent}}}
|
||||
if got := r.ProbeConfigured(t.Context()); len(got) != 0 {
|
||||
t.Errorf("reported without its package: %v", got)
|
||||
}
|
||||
|
||||
// Not named, not offered: python3 on PATH is nobody's TensorRT-LLM.
|
||||
r.engines = map[string]Engine{"trtllm": &TRTLLM{}}
|
||||
if got := r.ProbeConfigured(t.Context()); len(got) != 0 {
|
||||
t.Errorf("offered without being configured: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeTRTLLM is a Python path holding stand-ins for fastapi and
|
||||
// tensorrt_llm: enough of each for the launcher to do what it does in front
|
||||
// of the real server, and for the stand-in server to report what it saw.
|
||||
func fakeTRTLLM(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
files := map[string]string{
|
||||
"fastapi/__init__.py": `
|
||||
class FastAPI:
|
||||
def __init__(self, *a, **kw):
|
||||
self.user_middleware = []
|
||||
def add_middleware(self, cls, **kw):
|
||||
self.user_middleware.append(cls)
|
||||
`,
|
||||
"tensorrt_llm/__init__.py": "",
|
||||
"tensorrt_llm/commands/__init__.py": "",
|
||||
"tensorrt_llm/commands/serve.py": `
|
||||
import asyncio, json, os, sys
|
||||
import fastapi
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
with open(args[args.index("--extra_llm_api_options") + 1]) as f:
|
||||
options = f.read()
|
||||
app = fastapi.FastAPI()
|
||||
|
||||
async def server(scope, receive, send):
|
||||
await send({"type": "http.response.start", "status": 200, "headers": []})
|
||||
await send({"type": "http.response.body", "body": b"ok"})
|
||||
|
||||
handler = server
|
||||
for mw in reversed(app.user_middleware):
|
||||
handler = mw(handler)
|
||||
|
||||
async def ask(path, auth=None):
|
||||
headers = [(b"authorization", auth.encode())] if auth else []
|
||||
sent = []
|
||||
async def send(msg):
|
||||
sent.append(msg)
|
||||
async def receive():
|
||||
return {"type": "http.request"}
|
||||
await handler({"type": "http", "path": path, "headers": headers}, receive, send)
|
||||
return sent[0]["status"]
|
||||
|
||||
async def run():
|
||||
return {
|
||||
"health": await ask("/health"),
|
||||
"anonymous": await ask("/v1/chat/completions"),
|
||||
"wrong": await ask("/v1/models", "Bearer nope"),
|
||||
"keyed": await ask("/prometheus/metrics", "Bearer k1"),
|
||||
}
|
||||
|
||||
out = asyncio.run(run())
|
||||
out.update(options=options, argv0=sys.argv[0], args=args,
|
||||
key_left=os.environ.get("LLMGW_ENGINE_KEY"))
|
||||
print(json.dumps(out))
|
||||
`,
|
||||
}
|
||||
for name, body := range files {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
type launched struct {
|
||||
Health, Anonymous, Wrong, Keyed int
|
||||
Options, Argv0 string
|
||||
Args []string
|
||||
KeyLeft *string `json:"key_left"`
|
||||
}
|
||||
|
||||
func launch(t *testing.T, s ShardSpec) launched {
|
||||
t.Helper()
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("no python3 here to run the launcher with")
|
||||
}
|
||||
cmd := buildOne(t, &TRTLLM{cfg: TRTLLMConfig{Python: python}}, s)
|
||||
c := exec.Command(cmd.Path, cmd.Args...) //nolint:gosec // the command under test
|
||||
c.Env = append(cmd.Env, "PYTHONPATH="+fakeTRTLLM(t))
|
||||
out, err := c.Output()
|
||||
if err != nil {
|
||||
var stderr string
|
||||
if ee, ok := err.(*exec.ExitError); ok {
|
||||
stderr = string(ee.Stderr)
|
||||
}
|
||||
t.Fatalf("the launcher failed: %v\n%s", err, stderr)
|
||||
}
|
||||
var got launched
|
||||
if err := json.Unmarshal(out, &got); err != nil {
|
||||
t.Fatalf("%v: %s", err, out)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func TestTheTRTLLMLauncherDemandsTheKey(t *testing.T) {
|
||||
s := trtllmSpec()
|
||||
s.APIKey = "k1"
|
||||
got := launch(t, s)
|
||||
|
||||
if got.Anonymous != 401 || got.Wrong != 401 {
|
||||
t.Errorf("served without the key: anonymous %d, wrong key %d", got.Anonymous, got.Wrong)
|
||||
}
|
||||
if got.Keyed != 200 {
|
||||
t.Errorf("refused the key: %d", got.Keyed)
|
||||
}
|
||||
// Up or down is all /health says, and it is asked without one.
|
||||
if got.Health != 200 {
|
||||
t.Errorf("/health answered %d", got.Health)
|
||||
}
|
||||
// Taken out of the environment, so nothing the server starts holds it.
|
||||
if got.KeyLeft != nil {
|
||||
t.Errorf("the key was left in the environment: %q", *got.KeyLeft)
|
||||
}
|
||||
// A copy of this command line, as trtllm-serve's extra front ends are,
|
||||
// names no program that exists and so cannot serve without the key.
|
||||
if _, err := os.Stat(got.Argv0); err == nil || filepath.Base(got.Argv0) != "trtllm-serve" {
|
||||
t.Errorf("argv[0] is %q", got.Argv0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheTRTLLMLauncherTurnsOnTheMetricsTheRouterReads(t *testing.T) {
|
||||
got := launch(t, trtllmSpec())
|
||||
for _, want := range []string{"return_perf_metrics: true", "enable_iter_perf_stats: true"} {
|
||||
if !strings.Contains(got.Options, want) {
|
||||
t.Errorf("the options file lacks %q: %q", want, got.Options)
|
||||
}
|
||||
}
|
||||
path := argValue(got.Args, "--extra_llm_api_options")
|
||||
if !strings.HasPrefix(path, "/dev/fd/") {
|
||||
t.Errorf("the options were not passed by descriptor: %q", path)
|
||||
}
|
||||
if slices.Contains(got.Args, trtllmOptionsPlaceholder) {
|
||||
t.Error("the placeholder reached trtllm-serve")
|
||||
}
|
||||
// Without a key there is nothing to demand.
|
||||
if got.Anonymous != 200 {
|
||||
t.Errorf("with no key set, a request was refused: %d", got.Anonymous)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ var envFamilies = []string{
|
||||
"CUDA_", "NCCL_", "NVIDIA_", "NVTE_", "GLOO_", "UCX_", "TORCH_", "PYTORCH_",
|
||||
"VLLM_", "SGLANG_", "GGML_", "LLAMA_", "OMP_", "MKL_", "OPENBLAS_", "KMP_",
|
||||
"HF_", "TRANSFORMERS_", "TOKENIZERS_", "TRITON_", "FLASHINFER_",
|
||||
"TRTLLM_", "TLLM_",
|
||||
}
|
||||
|
||||
// envExact are single variables that are tuning too.
|
||||
@@ -118,6 +119,32 @@ var flagsNever = map[string]map[string]string{
|
||||
"--model-path": "is the model's source, set by the agent", "--served-model-name": "is set by the agent",
|
||||
"--lora-paths": "loads files", "--download-dir": "writes files",
|
||||
},
|
||||
// trtllm-serve spells its flags with underscores, so the shared list's
|
||||
// hyphenated names do not reach them.
|
||||
"trtllm": {
|
||||
"--trust_remote_code": "runs Python the model repository ships",
|
||||
"--served_model_name": "is set by the agent",
|
||||
"--config": "reads a file; the agent writes the options file itself",
|
||||
"--extra_llm_api_options": "reads a file; the agent writes the options file itself",
|
||||
"--tokenizer": "reads another repository or path",
|
||||
"--custom_tokenizer": "imports Python", "--post_processor_hook": "imports Python",
|
||||
"--custom_module_dirs": "imports Python", "--middleware": "imports Python",
|
||||
"--chat_template": "reads a file",
|
||||
"--metadata_server_config_file": "reads a file",
|
||||
"--visual_gen_args": "reads a file",
|
||||
"--report_addr": "writes a file",
|
||||
"--otlp_traces_endpoint": "sends request traces elsewhere",
|
||||
"--disagg_cluster_uri": "joins the server to another cluster",
|
||||
"--server_role": "makes the server part of another cluster",
|
||||
"--allow_request_chat_template": "lets a request supply the chat template",
|
||||
"--grpc": "serves without the key the agent sets",
|
||||
"--num_serve_frontends": "starts front ends that do not demand the key the agent sets",
|
||||
"--telemetry": "sends usage to NVIDIA",
|
||||
"--tensor_parallel_size": "is set by the agent from tp",
|
||||
"--tp_size": "is set by the agent from tp",
|
||||
"--pipeline_parallel_size": "is set by the agent from pp",
|
||||
"--pp_size": "is set by the agent from pp",
|
||||
},
|
||||
}
|
||||
|
||||
// unsafeFlag is why an engine may not be given a flag, or "".
|
||||
|
||||
@@ -2,8 +2,11 @@ package engines
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/kvevents"
|
||||
)
|
||||
|
||||
// VLLMConfig locates the vLLM installation and picks how it is launched.
|
||||
@@ -147,6 +150,28 @@ func (v *VLLM) serverCommand(s ShardSpec) (Command, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Adapters loaded at start are registered under their names, and a
|
||||
// request names one as its model. Adapters loaded on demand start
|
||||
// unregistered: the router loads each when a request first wants it
|
||||
// here, by the link the agent made (RuntimeLoRADir). --max-loras is
|
||||
// vLLM's default of one at start — raise it in the profile's arguments
|
||||
// to mix more adapters in a batch — and the cap on demand, which
|
||||
// WithRuntimeLoRA put in the arguments.
|
||||
if len(p.Adapters) > 0 {
|
||||
args = append(args, "--enable-lora")
|
||||
if !p.RuntimeLoRA() {
|
||||
args = append(args, loraModules(p.Adapters)...)
|
||||
}
|
||||
}
|
||||
|
||||
// The KV cache events, for the router's precise index: published to the
|
||||
// agent on loopback, hashed the way the router hashes. Only the leader
|
||||
// has a scheduler to publish from.
|
||||
if p.KVEvents && s.KVEventsPort > 0 && s.Leader() {
|
||||
args = append(args, kvevents.VLLMArgs(fmt.Sprintf("tcp://127.0.0.1:%d", s.KVEventsPort))...)
|
||||
maps.Copy(env, kvevents.VLLMEnv())
|
||||
}
|
||||
|
||||
// Profile arguments last, so an operator can override anything above.
|
||||
args = append(args, p.Args...)
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
llmgwv1 "gitea.mynodes.xyz/ilker/llmgw/api/gen/llmgw/v1"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/engines"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/agentsvc"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/kvevents"
|
||||
)
|
||||
|
||||
// kvFlushInterval is how often KV cache changes go up the stream. Often
|
||||
// enough that a prefix cached by one request is known before the next few
|
||||
// arrive; seldom enough that a busy engine's churn is sent as its net effect.
|
||||
const kvFlushInterval = 250 * time.Millisecond
|
||||
|
||||
// listenKV starts receiving a shard's KV cache events, when its profile asks
|
||||
// for them and this rank publishes any, and records the port in the spec for
|
||||
// the engine's arguments. port is the one to reuse, or 0 for any.
|
||||
//
|
||||
// A failure is logged and the engine started without events: the router then
|
||||
// routes the replica by tier 1, which is what it did before, rather than the
|
||||
// replica not starting at all for want of an optimisation.
|
||||
func (a *Agent) listenKV(spec *engines.ShardSpec, port int) {
|
||||
if !spec.Profile.KVEvents || spec.Profile.Engine != "vllm" || !spec.Leader() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
if sub, ok := a.kvSubs[spec.ShardID]; ok {
|
||||
a.mu.Unlock()
|
||||
// A repeated start command: the shard already has its listener.
|
||||
spec.KVEventsPort = sub.Port()
|
||||
return
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
sub, err := kvevents.Listen(spec.ReplicaID, port, a.kv, a.log)
|
||||
if err != nil {
|
||||
a.log.Warn("cannot receive kv cache events; the router will route this replica without them",
|
||||
"shard", spec.ShardID, "replica", spec.ReplicaID, "err", err)
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.kvSubs[spec.ShardID] = sub
|
||||
a.mu.Unlock()
|
||||
spec.KVEventsPort = sub.Port()
|
||||
}
|
||||
|
||||
// stopKV stops a shard's listener and tells the control plane its replica
|
||||
// holds nothing any more.
|
||||
func (a *Agent) stopKV(shardID, replicaID string) {
|
||||
a.mu.Lock()
|
||||
sub, ok := a.kvSubs[shardID]
|
||||
delete(a.kvSubs, shardID)
|
||||
a.mu.Unlock()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sub.Close()
|
||||
a.kv.Remove(replicaID)
|
||||
}
|
||||
|
||||
// forwardKV sends KV cache changes up one session's stream until it ends,
|
||||
// beginning with a full copy of every replica: the control plane at the other
|
||||
// end may have just started, or just taken over, and know nothing.
|
||||
func (a *Agent) forwardKV(ctx context.Context, out chan<- *llmgwv1.AgentMessage) {
|
||||
s := a.kv.Open()
|
||||
defer s.Close()
|
||||
t := time.NewTicker(kvFlushInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
for _, u := range s.Drain() {
|
||||
select {
|
||||
case out <- agentsvc.KVEventsMessage(u):
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-zeromq/zmq4"
|
||||
"github.com/vmihailenco/msgpack/v5"
|
||||
|
||||
llmgwv1 "gitea.mynodes.xyz/ilker/llmgw/api/gen/llmgw/v1"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/engines"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/kvevents"
|
||||
)
|
||||
|
||||
func kvAgent() *Agent {
|
||||
return &Agent{log: slog.New(slog.DiscardHandler), kv: kvevents.NewMirror(),
|
||||
kvSubs: map[string]*kvevents.Subscriber{}}
|
||||
}
|
||||
|
||||
// TestAnEnginesEventsReachTheControlPlaneStream runs the agent's half end to
|
||||
// end: a listener for the shard, a publisher standing in for vLLM connecting
|
||||
// to the port the engine would be given, and the stream to the control plane
|
||||
// carrying the result.
|
||||
func TestAnEnginesEventsReachTheControlPlaneStream(t *testing.T) {
|
||||
a := kvAgent()
|
||||
spec := engines.ShardSpec{ReplicaID: "r1", ShardID: "r1-0", NNodes: 1,
|
||||
Profile: engines.Profile{Engine: "vllm", KVEvents: true}}
|
||||
a.listenKV(&spec, 0)
|
||||
if spec.KVEventsPort == 0 {
|
||||
t.Fatal("the shard should have been given a port to publish to")
|
||||
}
|
||||
defer a.stopKV(spec.ShardID, spec.ReplicaID)
|
||||
|
||||
pub := zmq4.NewPub(context.Background())
|
||||
defer func() { _ = pub.Close() }()
|
||||
if err := pub.Dial(fmt.Sprintf("tcp://127.0.0.1:%d", spec.KVEventsPort)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokens := make([]int, 32)
|
||||
for i := range tokens {
|
||||
tokens[i] = 500 + i
|
||||
}
|
||||
hs := kvevents.BlockHashes(tokens, 16, 0)
|
||||
payload, _ := msgpack.Marshal([]any{1.0, []any{map[string]any{
|
||||
"type": "BlockStored", "block_hashes": []any{hs[0], hs[1]}, "parent_block_hash": nil,
|
||||
"token_ids": tokens, "block_size": 16, "lora_id": nil, "medium": "GPU",
|
||||
}}})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
out := make(chan *llmgwv1.AgentMessage, 16)
|
||||
go a.forwardKV(ctx, out)
|
||||
|
||||
deadline := time.After(5 * time.Second)
|
||||
var seq uint64
|
||||
for {
|
||||
// Sent until it arrives: a subscription reaches the publisher after
|
||||
// the connection, and what is published before it is dropped.
|
||||
var s [8]byte
|
||||
binary.BigEndian.PutUint64(s[:], seq)
|
||||
seq++
|
||||
_ = pub.Send(zmq4.NewMsgFrom([]byte("kv-events"), s[:], payload))
|
||||
select {
|
||||
case m := <-out:
|
||||
kv := m.GetKvEvents()
|
||||
if kv == nil || kv.GetReplicaId() != "r1" || kv.GetBlockSize() != 16 || len(kv.GetStored()) != 2 {
|
||||
t.Fatalf("message %v", m)
|
||||
}
|
||||
return
|
||||
case <-deadline:
|
||||
t.Fatal("nothing reached the stream")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAShardWithoutKVEventsGetsNoListener(t *testing.T) {
|
||||
a := kvAgent()
|
||||
spec := engines.ShardSpec{ReplicaID: "r1", ShardID: "r1-0", NNodes: 1,
|
||||
Profile: engines.Profile{Engine: "vllm"}}
|
||||
a.listenKV(&spec, 0)
|
||||
if spec.KVEventsPort != 0 || len(a.kvSubs) != 0 {
|
||||
t.Fatal("kv_events is opt-in")
|
||||
}
|
||||
}
|
||||
|
||||
func TestARepeatedStartReusesTheShardsListener(t *testing.T) {
|
||||
a := kvAgent()
|
||||
spec := engines.ShardSpec{ReplicaID: "r1", ShardID: "r1-0", NNodes: 1,
|
||||
Profile: engines.Profile{Engine: "vllm", KVEvents: true}}
|
||||
a.listenKV(&spec, 0)
|
||||
defer a.stopKV(spec.ShardID, spec.ReplicaID)
|
||||
again := spec
|
||||
again.KVEventsPort = 0
|
||||
a.listenKV(&again, 0)
|
||||
if again.KVEventsPort != spec.KVEventsPort || len(a.kvSubs) != 1 {
|
||||
t.Fatal("a start command repeated must not open a second listener")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/discovery"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/engines"
|
||||
)
|
||||
|
||||
func TestAShardPlacedOnAMIGInstanceIsLaunchedWithItsUUID(t *testing.T) {
|
||||
// The control plane sends device 1001: card 0's instance 1, by the number
|
||||
// placement gives it. Only this node knows the instance's UUID, which is
|
||||
// the one thing CUDA will open it by.
|
||||
a := &Agent{}
|
||||
a.inv.GPUs = []discovery.GPU{
|
||||
{Index: 1000, UUID: "MIG-aaa", MIG: &discovery.MIGDevice{ParentIndex: 0, Device: 0, Profile: "3g.40gb"}},
|
||||
{Index: 1001, UUID: "MIG-bbb", MIG: &discovery.MIGDevice{ParentIndex: 0, Device: 1, Profile: "3g.40gb"}},
|
||||
{Index: 1, UUID: "GPU-whole"},
|
||||
}
|
||||
|
||||
spec := engines.ShardSpec{GPUIndices: []int{1001}}
|
||||
a.localizeSpec(&spec)
|
||||
if got := engines.NCCLEnv(spec)["CUDA_VISIBLE_DEVICES"]; got != "MIG-bbb" {
|
||||
t.Errorf("CUDA_VISIBLE_DEVICES=%q, want MIG-bbb", got)
|
||||
}
|
||||
|
||||
// A whole card is given by index, as it always was.
|
||||
whole := engines.ShardSpec{GPUIndices: []int{1}}
|
||||
a.localizeSpec(&whole)
|
||||
if whole.GPUUUIDs != nil || engines.NCCLEnv(whole)["CUDA_VISIBLE_DEVICES"] != "1" {
|
||||
t.Errorf("a whole card was given as %v / %q", whole.GPUUUIDs, engines.NCCLEnv(whole)["CUDA_VISIBLE_DEVICES"])
|
||||
}
|
||||
|
||||
// A device this node does not have is not guessed at.
|
||||
gone := engines.ShardSpec{GPUIndices: []int{1002}}
|
||||
a.localizeSpec(&gone)
|
||||
if gone.GPUUUIDs != nil {
|
||||
t.Errorf("an unknown device was named %v", gone.GPUUUIDs)
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,13 @@ func (a *Agent) setProvision(p *llmgwv1.Provision) {
|
||||
// the installed build is used first — and quietly replace theirs.
|
||||
continue
|
||||
}
|
||||
wants = append(wants, provision.Want{Engine: e.GetEngine(), Version: e.GetVersion(), Variant: e.GetVariant()})
|
||||
w := provision.Want{Engine: e.GetEngine(), Version: e.GetVersion(), Variant: e.GetVariant()}
|
||||
if base := e.GetOfflineBase(); base != "" {
|
||||
// An offline cluster: from its mirror, checked against what the
|
||||
// control plane holds, never the publisher.
|
||||
w.Offline = &provision.Offline{Base: base, SHA256: maps.Clone(e.GetOfflineSha256())}
|
||||
}
|
||||
wants = append(wants, w)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.provWants = wants
|
||||
|
||||
@@ -20,7 +20,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/discovery"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
)
|
||||
|
||||
// Want is one engine at one version.
|
||||
@@ -30,6 +34,24 @@ type Want struct {
|
||||
// Variant is a build chosen for this node ("cu129"); empty leaves it to
|
||||
// the node's hardware.
|
||||
Variant string
|
||||
// Offline, when set, is where the engine comes from instead of its
|
||||
// publisher: a cluster with no way to the internet installs from its
|
||||
// mirror's copy of an offline bundle.
|
||||
Offline *Offline
|
||||
}
|
||||
|
||||
// Offline is an engine version's files on a cluster's own mirror.
|
||||
//
|
||||
// The files come from the mirror and their checksums from the control plane,
|
||||
// which read them from the bundle they were imported from. The mirror serves
|
||||
// plain HTTP to every node; a checksum taken from beside the file there would
|
||||
// prove only that the file and the checksum came from the same place.
|
||||
type Offline struct {
|
||||
// Base is where the version's files are: <mirror>/_llmgw/engines/<engine>/<version>.
|
||||
Base string
|
||||
// SHA256 is each file's checksum, by name, as the publisher gave it
|
||||
// when the bundle was made.
|
||||
SHA256 map[string]string
|
||||
}
|
||||
|
||||
// The states an engine's installation can be in.
|
||||
@@ -152,6 +174,16 @@ func (in *Installer) one(ctx context.Context, w Want) Status {
|
||||
}
|
||||
return st
|
||||
}
|
||||
if w.Offline != nil && recipe.Repo == "" {
|
||||
// Said, not attempted: uv would spend minutes failing to reach PyPI,
|
||||
// and the failure would read like a network fault rather than the
|
||||
// design of an offline site.
|
||||
st.State = Unsupported
|
||||
st.Detail = "this cluster installs offline, and " + w.Engine + " comes from PyPI, which an offline bundle " +
|
||||
"does not carry: install it on the node by hand and name it in agent.yaml, or set engines." +
|
||||
w.Engine + ` to "" in server.yaml`
|
||||
return st
|
||||
}
|
||||
|
||||
// Installed before: whichever candidate is, best first, checked that it
|
||||
// still runs and trusted for nothing else.
|
||||
@@ -251,7 +283,17 @@ func (in *Installer) ready(st Status, b Build, bin, version string) Status {
|
||||
//
|
||||
// Into a scratch directory renamed into place at the end, so a failure halfway
|
||||
// leaves nothing that looks installed.
|
||||
func (in *Installer) install(ctx context.Context, r Recipe, w Want, b Build, dir string, st *Status) error {
|
||||
//
|
||||
// Traced as "install engine", a trace of its own: an install is not part of
|
||||
// any one start, and runs once per version rather than once per replica.
|
||||
func (in *Installer) install(ctx context.Context, r Recipe, w Want, b Build, dir string, st *Status) (err error) {
|
||||
ctx, span := obs.Tracer("gitea.mynodes.xyz/ilker/llmgw/internal/agent/provision").Start(ctx, "install engine",
|
||||
trace.WithAttributes(
|
||||
attribute.String("llmgw.engine", w.Engine),
|
||||
attribute.String("llmgw.engine_version", w.Version),
|
||||
attribute.String("llmgw.engine_build", w.Variant),
|
||||
))
|
||||
defer func() { obs.End(span, err) }()
|
||||
if b.Python != "" {
|
||||
return in.installPython(ctx, r, w, b, dir, st)
|
||||
}
|
||||
@@ -259,10 +301,15 @@ func (in *Installer) install(ctx context.Context, r Recipe, w Want, b Build, dir
|
||||
return err
|
||||
}
|
||||
|
||||
in.progress(st, "asking GitHub for the checksums of %s %s", w.Engine, w.Version)
|
||||
sums, err := in.checksums(ctx, r.Repo, w.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
var sums map[string]string
|
||||
if w.Offline != nil {
|
||||
sums = w.Offline.SHA256
|
||||
} else {
|
||||
in.progress(st, "asking GitHub for the checksums of %s %s", w.Engine, w.Version)
|
||||
var err error
|
||||
if sums, err = in.checksums(ctx, r.Repo, w.Version); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
tmp := dir + ".partial"
|
||||
@@ -275,14 +322,22 @@ func (in *Installer) install(ctx context.Context, r Recipe, w Want, b Build, dir
|
||||
got := map[string]string{}
|
||||
for _, asset := range b.Assets {
|
||||
want, ok := sums[asset]
|
||||
if !ok {
|
||||
switch {
|
||||
case !ok && w.Offline != nil:
|
||||
return fmt.Errorf("the offline bundle has no %s for %s %s: make one that has "+
|
||||
"(llmgw bundle create --engine %s=%s) and import it", asset, w.Engine, w.Version, w.Engine, w.Version)
|
||||
case !ok:
|
||||
// Refused rather than installed unchecked: this is a binary that
|
||||
// will run as root on every node.
|
||||
return fmt.Errorf("%s %s publishes no checksum for %s, so it cannot be verified",
|
||||
w.Engine, w.Version, asset)
|
||||
}
|
||||
url := strings.TrimSuffix(in.downloadBase(), "/") + "/" + r.Repo + "/releases/download/" + w.Version + "/" + asset
|
||||
if w.Offline != nil {
|
||||
url = strings.TrimSuffix(w.Offline.Base, "/") + "/" + asset
|
||||
}
|
||||
archive := filepath.Join(tmp, asset+".download")
|
||||
if err := in.download(ctx, r.Repo, w.Version, asset, archive, want, st); err != nil {
|
||||
if err := in.download(ctx, url, asset, archive, want, st); err != nil {
|
||||
return err
|
||||
}
|
||||
in.progress(st, "unpacking %s", asset)
|
||||
@@ -539,6 +594,26 @@ func (in *Installer) has(tool string) bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Published is the sha256 an engine's publisher gives for each file of a
|
||||
// version, and where each is downloaded from: what an offline bundle is made
|
||||
// of, read the way a node online reads it.
|
||||
func (in *Installer) Published(ctx context.Context, engine, version string) (sums map[string]string, url func(asset string) string, err error) {
|
||||
r, ok := Recipes[engine]
|
||||
if !ok || r.Repo == "" {
|
||||
return nil, nil, fmt.Errorf("%s is not published as release files", engine)
|
||||
}
|
||||
if !validVersion.MatchString(version) {
|
||||
return nil, nil, fmt.Errorf("%q is not a version of %s", version, engine)
|
||||
}
|
||||
sums, err = in.checksums(ctx, r.Repo, version)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sums, func(asset string) string {
|
||||
return strings.TrimSuffix(in.downloadBase(), "/") + "/" + r.Repo + "/releases/download/" + version + "/" + asset
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checksums reads the sha256 GitHub publishes for each asset of a release.
|
||||
func (in *Installer) checksums(ctx context.Context, repo, tag string) (map[string]string, error) {
|
||||
url := strings.TrimSuffix(in.apiBase(), "/") + "/repos/" + repo + "/releases/tags/" + tag
|
||||
@@ -580,8 +655,7 @@ func (in *Installer) checksums(ctx context.Context, repo, tag string) (map[strin
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (in *Installer) download(ctx context.Context, repo, tag, asset, dst, want string, st *Status) error {
|
||||
url := strings.TrimSuffix(in.downloadBase(), "/") + "/" + repo + "/releases/download/" + tag + "/" + asset
|
||||
func (in *Installer) download(ctx context.Context, url, asset, dst, want string, st *Status) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package provision
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/discovery"
|
||||
)
|
||||
|
||||
// offlineMirror is a cluster's mirror holding a bundle's engine files, and
|
||||
// nothing that answers for GitHub.
|
||||
type offlineMirror struct {
|
||||
files map[string][]byte
|
||||
mu sync.Mutex
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (m *offlineMirror) serve(t *testing.T) *httptest.Server {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
m.mu.Lock()
|
||||
m.paths = append(m.paths, r.URL.Path)
|
||||
m.mu.Unlock()
|
||||
b, ok := m.files[r.URL.Path]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(b)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestAnOfflineNodeInstallsFromTheMirrorWithChecksumsFromTheControlPlane(t *testing.T) {
|
||||
rel := llamaRelease(t)
|
||||
asset := "llama-b1-bin-ubuntu-x64.tar.gz"
|
||||
m := &offlineMirror{files: map[string][]byte{"/_llmgw/engines/llamacpp/b1/" + asset: rel.assets[asset]}}
|
||||
srv := m.serve(t)
|
||||
sys := &fakeSystem{installed: map[string]bool{"libgomp1": true}}
|
||||
// GitHub is the mirror too, so a request for it would be seen and
|
||||
// answered 404: an offline install must not ask.
|
||||
in, _ := installer(t, srv, sys, ubuntu)
|
||||
|
||||
want := Want{Engine: "llamacpp", Version: "b1", Offline: &Offline{
|
||||
Base: srv.URL + "/_llmgw/engines/llamacpp/b1",
|
||||
SHA256: map[string]string{asset: strings.TrimPrefix(rel.digests[asset], "sha256:")},
|
||||
}}
|
||||
got := in.Converge(t.Context(), []Want{want})
|
||||
if got[0].State != Ready {
|
||||
t.Fatalf("not installed from the mirror: %+v", got[0])
|
||||
}
|
||||
for _, p := range m.paths {
|
||||
if strings.HasPrefix(p, "/repos/") || strings.Contains(p, "/releases/download/") {
|
||||
t.Errorf("an offline install asked for %s", p)
|
||||
}
|
||||
}
|
||||
|
||||
// A file on the mirror that is not what the bundle recorded is refused,
|
||||
// whatever the mirror says of it.
|
||||
m.files["/_llmgw/engines/llamacpp/b2/llama-b2-bin-ubuntu-x64.tar.gz"] = []byte("replaced on the mirror")
|
||||
got = in.Converge(t.Context(), []Want{{Engine: "llamacpp", Version: "b2", Offline: &Offline{
|
||||
Base: srv.URL + "/_llmgw/engines/llamacpp/b2",
|
||||
SHA256: map[string]string{"llama-b2-bin-ubuntu-x64.tar.gz": strings.Repeat("a", 64)},
|
||||
}}})
|
||||
if got[0].State != Failed || !strings.Contains(got[0].Detail, "checksum") {
|
||||
t.Errorf("a file not matching the bundle's checksum was not refused: %+v", got[0])
|
||||
}
|
||||
|
||||
// One the bundle has no checksum for is not fetched at all, and the
|
||||
// operator is told which bundle would have it.
|
||||
got = in.Converge(t.Context(), []Want{{Engine: "llamacpp", Version: "b3", Offline: &Offline{
|
||||
Base: srv.URL + "/_llmgw/engines/llamacpp/b3",
|
||||
}}})
|
||||
if got[0].State != Failed || !strings.Contains(got[0].Detail, "bundle create --engine llamacpp=b3") {
|
||||
t.Errorf("a version missing from the bundle did not say how to add it: %+v", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnOfflineNodeIsToldPythonEnginesComeFromPyPI(t *testing.T) {
|
||||
gpu := ubuntu
|
||||
gpu.NVIDIADriver, gpu.MinComputeCapability = "580.65", 8.9
|
||||
in := &Installer{Root: t.TempDir(), Host: gpu, Run: (&fakeSystem{}).run}
|
||||
got := in.Converge(t.Context(), []Want{{Engine: "vllm", Version: "0.30.0", Offline: &Offline{Base: "http://mirror"}}})
|
||||
if got[0].State != Unsupported || !strings.Contains(got[0].Detail, "PyPI") {
|
||||
t.Fatalf("vLLM offline: %+v", got[0])
|
||||
}
|
||||
|
||||
// A node it is not meant for still says nothing is wrong.
|
||||
in.Host = ubuntu
|
||||
got = in.Converge(t.Context(), []Want{{Engine: "vllm", Version: "0.30.0", Offline: &Offline{Base: "http://mirror"}}})
|
||||
if got[0].State != Skipped {
|
||||
t.Errorf("vLLM offline on a CPU node: %+v", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestABundleCarriesEveryBuildTheNodesMightChoose(t *testing.T) {
|
||||
variants := func(arch string) []string {
|
||||
bs, err := Builds("llamacpp", "b1", arch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, b := range bs {
|
||||
out = append(out, b.Variant)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := variants("amd64"); !slices.Equal(got, []string{"cpu", "cuda-13.3", "cuda-12.8", "vulkan"}) {
|
||||
t.Errorf("amd64 builds: %v", got)
|
||||
}
|
||||
if got := variants("arm64"); !slices.Equal(got, []string{"cpu", "cuda-13.3", "vulkan"}) {
|
||||
t.Errorf("arm64 builds: %v", got)
|
||||
}
|
||||
|
||||
// Each one a node would choose is among them, file for file.
|
||||
bundled := map[string][]string{}
|
||||
bs, _ := Builds("llamacpp", "b1", "amd64")
|
||||
for _, b := range bs {
|
||||
bundled[b.Variant] = b.Assets
|
||||
}
|
||||
for _, h := range []discovery.Host{
|
||||
ubuntu,
|
||||
{Arch: "amd64", NVIDIADriver: "550.1", MinComputeCapability: 8.6},
|
||||
{Arch: "amd64", NVIDIADriver: "470.1", MinComputeCapability: 6.1},
|
||||
} {
|
||||
chosen, err := llamaCppCandidates("b1", "", h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range chosen {
|
||||
if !slices.Equal(bundled[b.Variant], b.Assets) {
|
||||
t.Errorf("%+v chooses %s %v, which the bundle carries as %v", h, b.Variant, b.Assets, bundled[b.Variant])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := Builds("vllm", "0.30.0", "amd64"); err == nil || !strings.Contains(err.Error(), "PyPI") {
|
||||
t.Errorf("a Python engine was offered for a bundle: %v", err)
|
||||
}
|
||||
if _, err := Builds("llamacpp", "../b1", "amd64"); err == nil {
|
||||
t.Error("a version that is a path was accepted")
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,49 @@ func Installable() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// Builds are every build of an engine version published for an
|
||||
// architecture: what an offline bundle carries, for nodes it has not seen.
|
||||
// Read from the same table the nodes choose from, asked as a machine with
|
||||
// no GPU and as one with any NVIDIA GPU, so a bundle and the nodes that
|
||||
// install from it cannot disagree about which files a build is. Archive
|
||||
// engines only: a Python engine is a PyPI environment, which no bundle
|
||||
// carries.
|
||||
func Builds(engine, version, arch string) ([]Build, error) {
|
||||
r, ok := Recipes[engine]
|
||||
switch {
|
||||
case !ok:
|
||||
return nil, fmt.Errorf("this agent does not know how to install %s", engine)
|
||||
case r.Repo == "":
|
||||
return nil, fmt.Errorf("%s is installed from PyPI, which an offline bundle does not carry", engine)
|
||||
case !validVersion.MatchString(version):
|
||||
return nil, fmt.Errorf("%q is not a version of %s", version, engine)
|
||||
}
|
||||
var out []Build
|
||||
seen := map[string]bool{}
|
||||
var errs []string
|
||||
for _, h := range []discovery.Host{
|
||||
{Arch: arch},
|
||||
// Any card and the newest driver: every GPU build is a candidate.
|
||||
{Arch: arch, NVIDIADriver: "9999"},
|
||||
} {
|
||||
bs, err := r.Candidates(version, "", h)
|
||||
if err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
continue
|
||||
}
|
||||
for _, b := range bs {
|
||||
if !seen[b.Variant] {
|
||||
seen[b.Variant] = true
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, fmt.Errorf("no build of %s %s for %s: %s", engine, version, arch, strings.Join(errs, "; "))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UVVersion is the uv that installs the Python engines.
|
||||
const UVVersion = "0.12.20"
|
||||
|
||||
|
||||
@@ -18,9 +18,19 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/engines"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
)
|
||||
|
||||
// tracerName names the spans the supervisor opens. There is no restart span
|
||||
// here because the supervisor never restarts an engine on its own: a restart
|
||||
// is the control plane's decision, traced there, and reaches a node as a stop
|
||||
// and a start.
|
||||
const tracerName = "gitea.mynodes.xyz/ilker/llmgw/internal/agent/supervisor"
|
||||
|
||||
// Config configures the supervisor.
|
||||
type Config struct {
|
||||
// WorkDir holds pid files and per-shard scratch space.
|
||||
@@ -195,7 +205,25 @@ var ErrAlreadyRunning = errors.New("shard is already running")
|
||||
// It is idempotent by ID: a repeated StartShard for the same shard is a no-op
|
||||
// rather than a second process, because the control plane retries commands
|
||||
// (plan §5.6).
|
||||
func (s *Supervisor) Start(ctx context.Context, id string, spec engines.ShardSpec, cmds []engines.Command) (*Shard, error) {
|
||||
//
|
||||
// Traced as "launch engine": from the first process to the engine's being
|
||||
// started, which for a multi-node worker includes waiting for its leader's
|
||||
// rendezvous point. Loading the model is the readiness wait's, not this.
|
||||
func (s *Supervisor) Start(ctx context.Context, id string, spec engines.ShardSpec, cmds []engines.Command) (_ *Shard, err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "launch engine", trace.WithAttributes(
|
||||
attribute.String("llmgw.shard", id),
|
||||
attribute.String("llmgw.engine", spec.Profile.Engine),
|
||||
attribute.Int("llmgw.processes", len(cmds)),
|
||||
))
|
||||
defer func() {
|
||||
if errors.Is(err, ErrAlreadyRunning) {
|
||||
// A repeated command, which is not this start failing.
|
||||
span.SetAttributes(attribute.Bool("llmgw.already_running", true))
|
||||
span.End()
|
||||
return
|
||||
}
|
||||
obs.End(span, err)
|
||||
}()
|
||||
if len(cmds) == 0 {
|
||||
return nil, fmt.Errorf("shard %s: no commands to run", id)
|
||||
}
|
||||
@@ -301,6 +329,7 @@ func (s *Supervisor) launch(ctx context.Context, sh *Shard, cmds []engines.Comma
|
||||
sh.pid = c.Process.Pid
|
||||
sh.state = Starting
|
||||
sh.mu.Unlock()
|
||||
trace.SpanFromContext(ctx).SetAttributes(attribute.Int("llmgw.pid", c.Process.Pid))
|
||||
|
||||
if err := s.writeState(sh); err != nil {
|
||||
s.log.Warn("could not write pid file; adoption after a restart will not work",
|
||||
@@ -337,7 +366,13 @@ func (s *Supervisor) spawn(ctx context.Context, sh *Shard, c engines.Command) (*
|
||||
}
|
||||
|
||||
// waitForPort blocks until addr accepts a connection.
|
||||
func waitForPort(ctx context.Context, addr string, timeout time.Duration) error {
|
||||
//
|
||||
// Traced: a worker's start that took ten minutes because its leader was
|
||||
// still loading reads as exactly that.
|
||||
func waitForPort(ctx context.Context, addr string, timeout time.Duration) (err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "wait for rendezvous",
|
||||
trace.WithAttributes(attribute.String("llmgw.rendezvous", addr)))
|
||||
defer func() { obs.End(span, err) }()
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -416,7 +451,26 @@ func (s *Supervisor) wait(sh *Shard) {
|
||||
// The timeout comes from the profile because it is model-dependent: loading a
|
||||
// 70B model across two nodes legitimately takes tens of minutes, while a small
|
||||
// model failing to load for ten minutes means something is wrong.
|
||||
func (s *Supervisor) WaitReady(ctx context.Context, sh *Shard, baseURL, model string, timeout time.Duration) error {
|
||||
//
|
||||
// Traced as "wait for engine": the model loading, which is usually most of a
|
||||
// start. The span says how many times the engine was asked and what it last
|
||||
// answered, so one that never came up says why.
|
||||
func (s *Supervisor) WaitReady(ctx context.Context, sh *Shard, baseURL, model string, timeout time.Duration) (err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "wait for engine", trace.WithAttributes(
|
||||
attribute.String("llmgw.shard", sh.ID),
|
||||
attribute.String("llmgw.readiness", "health check"),
|
||||
attribute.String("llmgw.timeout", timeout.String()),
|
||||
))
|
||||
polls := 0
|
||||
var answer error
|
||||
defer func() {
|
||||
span.SetAttributes(attribute.Int("llmgw.polls", polls))
|
||||
if answer != nil && err != nil {
|
||||
span.SetAttributes(attribute.String("llmgw.last_answer", answer.Error()))
|
||||
}
|
||||
obs.End(span, err)
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -432,7 +486,8 @@ func (s *Supervisor) WaitReady(ctx context.Context, sh *Shard, baseURL, model st
|
||||
last := strings.Join(sh.Logs(10), "\n")
|
||||
return fmt.Errorf("shard %s not ready within %v; last output:\n%s", sh.ID, timeout, last)
|
||||
case <-t.C:
|
||||
if err := s.health.Ready(ctx, baseURL, model, sh.Spec.APIKey); err != nil {
|
||||
polls++
|
||||
if answer = s.health.Ready(ctx, baseURL, model, sh.Spec.APIKey); answer != nil {
|
||||
continue
|
||||
}
|
||||
sh.setState(Ready, nil)
|
||||
@@ -449,7 +504,13 @@ func (s *Supervisor) WaitReady(ctx context.Context, sh *Shard, baseURL, model st
|
||||
// leader answering, which only happens once every worker has joined. Polling a
|
||||
// worker's port instead would time out and fail a replica that is coming up
|
||||
// perfectly well.
|
||||
func (s *Supervisor) WaitAlive(ctx context.Context, sh *Shard) error {
|
||||
func (s *Supervisor) WaitAlive(ctx context.Context, sh *Shard) (err error) {
|
||||
_, span := obs.Tracer(tracerName).Start(ctx, "wait for engine", trace.WithAttributes(
|
||||
attribute.String("llmgw.shard", sh.ID),
|
||||
attribute.String("llmgw.readiness", "stays alive"),
|
||||
attribute.String("llmgw.timeout", s.cfg.AliveGrace.String()),
|
||||
))
|
||||
defer func() { obs.End(span, err) }()
|
||||
sh.setState(Loading, nil)
|
||||
|
||||
select {
|
||||
@@ -483,7 +544,14 @@ func (s *Supervisor) Drain(id string) error {
|
||||
|
||||
// Stop terminates a shard: SIGTERM to the whole group, then SIGKILL after
|
||||
// StopTimeout.
|
||||
func (s *Supervisor) Stop(ctx context.Context, id string) error {
|
||||
//
|
||||
// Traced as "stop engine", saying whether it had to be killed: an engine
|
||||
// that ignores SIGTERM for a minute is a minute its replacement waits for
|
||||
// the GPU.
|
||||
func (s *Supervisor) Stop(ctx context.Context, id string) (err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "stop engine",
|
||||
trace.WithAttributes(attribute.String("llmgw.shard", id)))
|
||||
defer func() { obs.End(span, err) }()
|
||||
sh, err := s.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -527,6 +595,7 @@ func (s *Supervisor) Stop(ctx context.Context, id string) error {
|
||||
// force kills the group outright. exec.Cmd's cancel does this for shards we
|
||||
// started; an adopted shard has none, so signal its group directly.
|
||||
force := func() {
|
||||
span.SetAttributes(attribute.Bool("llmgw.killed", true))
|
||||
if sh.cancel != nil {
|
||||
sh.cancel()
|
||||
return
|
||||
@@ -801,6 +870,16 @@ func (s *Supervisor) KillOrphan(o Orphan) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// EngineDir is the working directory engines run in: the engines' user's
|
||||
// home when they run as one, the work directory otherwise. A relative path
|
||||
// an engine is given resolves against it.
|
||||
func (s *Supervisor) EngineDir() string {
|
||||
if s.as != nil {
|
||||
return s.as.home
|
||||
}
|
||||
return s.cfg.WorkDir
|
||||
}
|
||||
|
||||
// dropTo makes a command run as the engines' user, when there is one: its
|
||||
// credential, its home as the working directory, and its caches there.
|
||||
func (s *Supervisor) dropTo(c *exec.Cmd) {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/supervisor"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs/obstest"
|
||||
)
|
||||
|
||||
func TestAStartOnTheNodeIsInTheControlPlanesTrace(t *testing.T) {
|
||||
rec := obstest.Record(t)
|
||||
h := start(t, func(c *Config) {
|
||||
c.Engines.VLLM.Bin = servingEngine(t)
|
||||
})
|
||||
|
||||
// The control plane's side, as the reconciler sends it: the command
|
||||
// dispatched under a span of its own, over the real stream.
|
||||
ctx, sent := obs.Tracer("test").Start(t.Context(), "send start",
|
||||
trace.WithSpanKind(trace.SpanKindProducer))
|
||||
if err := h.svc.StartShard(ctx, shardCommand(t, "shard-a")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent.End()
|
||||
h.rec.await(t, 30*time.Second, func(s status) bool {
|
||||
return s.shardID == "shard-a" && s.state == supervisor.Ready
|
||||
})
|
||||
|
||||
// The node's part ends just after it reports the shard ready.
|
||||
tid := sent.SpanContext().TraceID()
|
||||
node := rec.Await(t, tid, "start shard", 5*time.Second)
|
||||
if node.Parent().SpanID() != sent.SpanContext().SpanID() {
|
||||
t.Fatal("the node's start is not beneath the control plane's command")
|
||||
}
|
||||
if node.SpanKind() != trace.SpanKindConsumer {
|
||||
t.Errorf("the node's start is a %v span", node.SpanKind())
|
||||
}
|
||||
if a := obstest.Attrs(node); a["llmgw.node"] != "n1" || a["llmgw.replica"] != "rep-1" ||
|
||||
a["llmgw.model"] != "test-model" || a["llmgw.engine"] != "vllm" {
|
||||
t.Errorf("the node's start does not say what it started: %v", a)
|
||||
}
|
||||
if node.Status().Code == codes.Error {
|
||||
t.Errorf("a start that served is %v", node.Status())
|
||||
}
|
||||
for _, name := range []string{"fetch weights", "launch engine", "wait for engine"} {
|
||||
if !obstest.ChildOf(rec.One(t, tid, name), node) {
|
||||
t.Errorf("%s is not beneath the node's start", name)
|
||||
}
|
||||
}
|
||||
if a := obstest.Attrs(rec.One(t, tid, "fetch weights")); a["llmgw.weights.outcome"] != "local" {
|
||||
t.Errorf("the weights do not say how they were found: %v", a)
|
||||
}
|
||||
if a := obstest.Attrs(rec.One(t, tid, "wait for engine")); a["llmgw.polls"] == "" || a["llmgw.polls"] == "0" {
|
||||
t.Errorf("the readiness wait does not say how often it asked: %v", a)
|
||||
}
|
||||
|
||||
// A stop joins the trace it was sent in, too.
|
||||
sctx, stop := obs.Tracer("test").Start(t.Context(), "stop replica")
|
||||
if err := h.svc.StopShard(sctx, "n1", "shard-a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stop.End()
|
||||
h.rec.await(t, 15*time.Second, func(s status) bool {
|
||||
return s.shardID == "shard-a" && s.state == supervisor.Stopped
|
||||
})
|
||||
stid := stop.SpanContext().TraceID()
|
||||
nodeStop := rec.Await(t, stid, "stop shard", 5*time.Second)
|
||||
if !obstest.ChildOf(nodeStop, rec.One(t, stid, "stop replica")) {
|
||||
t.Error("the node's stop is not beneath the control plane's")
|
||||
}
|
||||
if !obstest.ChildOf(rec.One(t, stid, "stop engine"), nodeStop) {
|
||||
t.Error("stopping the engine is not beneath the node's stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptionIsTracedAndItsStopsAreInIt(t *testing.T) {
|
||||
rec := obstest.Record(t)
|
||||
h := start(t, func(c *Config) {
|
||||
c.Engines.VLLM.Bin = fakeEngineScript(t, `sleep 60`)
|
||||
})
|
||||
if err := h.svc.StartShard(t.Context(), shardCommand(t, "shard-orphaned")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.rec.await(t, 15*time.Second, func(s status) bool {
|
||||
return s.shardID == "shard-orphaned" && s.state == supervisor.Starting
|
||||
})
|
||||
|
||||
// The control plane, restarted, claims nothing the node is running.
|
||||
h.rec.markUnclaimed("shard-orphaned")
|
||||
h.ln.drop()
|
||||
h.rec.await(t, 20*time.Second, func(s status) bool {
|
||||
return s.shardID == "shard-orphaned" && s.state == supervisor.Stopped
|
||||
})
|
||||
|
||||
adopt := rec.Named("adopt")
|
||||
if len(adopt) != 1 {
|
||||
t.Fatalf("%d adoptions traced", len(adopt))
|
||||
}
|
||||
if a := obstest.Attrs(adopt[0]); a["llmgw.node"] != "n1" || a["llmgw.shards"] != "1" || a["llmgw.unclaimed"] != "1" {
|
||||
t.Errorf("the adoption does not say what it found: %v", a)
|
||||
}
|
||||
stop := rec.Await(t, adopt[0].SpanContext().TraceID(), "stop shard", 5*time.Second)
|
||||
if !obstest.ChildOf(stop, adopt[0]) {
|
||||
t.Error("stopping the unclaimed shard is not beneath the adoption")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStartThatFailsOnTheNodeSaysWhyInTheTrace(t *testing.T) {
|
||||
rec := obstest.Record(t)
|
||||
h := start(t, func(c *Config) {
|
||||
c.Engines.VLLM.Bin = fakeEngineScript(t, `echo "CUDA out of memory" >&2; exit 1`)
|
||||
})
|
||||
|
||||
ctx, sent := obs.Tracer("test").Start(t.Context(), "send start")
|
||||
if err := h.svc.StartShard(ctx, shardCommand(t, "shard-b")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent.End()
|
||||
h.rec.await(t, 30*time.Second, func(s status) bool {
|
||||
return s.shardID == "shard-b" && s.state == supervisor.Failed
|
||||
})
|
||||
|
||||
tid := sent.SpanContext().TraceID()
|
||||
node := rec.Await(t, tid, "start shard", 5*time.Second)
|
||||
if node.Status().Code != codes.Error {
|
||||
t.Errorf("a start that failed is %v", node.Status())
|
||||
}
|
||||
if wait := rec.One(t, tid, "wait for engine"); wait.Status().Code != codes.Error {
|
||||
t.Errorf("the readiness wait of an engine that exited is %v", wait.Status())
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,11 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
)
|
||||
|
||||
// Progress reports how a fetch is going, for anything that wants to say so.
|
||||
@@ -80,13 +85,48 @@ var ErrNotLocal = errors.New("the weights are not on this node and the source sa
|
||||
// local disk, a Lustre mount or an image exported over the fabric, and a
|
||||
// downloader that second-guessed that would copy a hundred gigabytes that were
|
||||
// already present.
|
||||
func (f *Fetcher) Ensure(ctx context.Context, source string) (string, error) {
|
||||
//
|
||||
// Traced as "fetch weights", with what it came to — the file was local,
|
||||
// already cached, downloaded, or downloaded by another shard this one waited
|
||||
// for — since that is most of the difference between a replica that starts
|
||||
// in a minute and one that takes an hour.
|
||||
func (f *Fetcher) Ensure(ctx context.Context, source string) (path string, err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "fetch weights",
|
||||
trace.WithAttributes(attribute.String("llmgw.weights.source", redact(source))))
|
||||
defer func() {
|
||||
span.SetAttributes(attribute.String("llmgw.weights.path", path))
|
||||
obs.End(span, err)
|
||||
}()
|
||||
return f.ensure(ctx, source)
|
||||
}
|
||||
|
||||
// tracerName names the spans this package opens.
|
||||
const tracerName = "gitea.mynodes.xyz/ilker/llmgw/internal/agent/weights"
|
||||
|
||||
// outcome says on the current span how a source was made present.
|
||||
func outcome(ctx context.Context, how string) {
|
||||
trace.SpanFromContext(ctx).SetAttributes(attribute.String("llmgw.weights.outcome", how))
|
||||
}
|
||||
|
||||
// redact is a source fit for a trace: a URL without its credentials or
|
||||
// query, which is where a token would be.
|
||||
func redact(source string) string {
|
||||
u, err := url.Parse(source)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return source
|
||||
}
|
||||
u.User, u.RawQuery, u.Fragment = nil, "", ""
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (f *Fetcher) ensure(ctx context.Context, source string) (string, error) {
|
||||
if source == "" {
|
||||
return "", fmt.Errorf("no source given")
|
||||
}
|
||||
// A version rather than a file. Everything below assumes one URL is one
|
||||
// file, and a set has to be handled before any of it.
|
||||
if IsSet(source) {
|
||||
outcome(ctx, "set")
|
||||
return f.ensureSet(ctx, source)
|
||||
}
|
||||
if !isRemote(source) {
|
||||
@@ -95,9 +135,11 @@ func (f *Fetcher) Ensure(ctx context.Context, source string) (string, error) {
|
||||
// was never meant to be one. vLLM and SGLang resolve those
|
||||
// themselves, and doing it for them would be both a duplicate
|
||||
// downloader and a change in documented behaviour.
|
||||
outcome(ctx, "left to the engine")
|
||||
return source, nil
|
||||
}
|
||||
if _, err := os.Stat(source); err == nil {
|
||||
outcome(ctx, "local")
|
||||
return source, nil
|
||||
}
|
||||
return "", fmt.Errorf("%w: %s", ErrNotLocal, source)
|
||||
@@ -108,6 +150,7 @@ func (f *Fetcher) Ensure(ctx context.Context, source string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
if _, err := os.Stat(target); err == nil {
|
||||
outcome(ctx, "cached")
|
||||
return target, nil
|
||||
}
|
||||
|
||||
@@ -117,6 +160,7 @@ func (f *Fetcher) Ensure(ctx context.Context, source string) (string, error) {
|
||||
}
|
||||
if call, running := f.inflight[source]; running {
|
||||
f.mu.Unlock()
|
||||
outcome(ctx, "fetched by another shard")
|
||||
select {
|
||||
case <-call.done:
|
||||
return call.path, call.err
|
||||
@@ -128,6 +172,7 @@ func (f *Fetcher) Ensure(ctx context.Context, source string) (string, error) {
|
||||
f.inflight[source] = call
|
||||
f.mu.Unlock()
|
||||
|
||||
outcome(ctx, "downloaded")
|
||||
call.path, call.err = f.fetch(ctx, source, target)
|
||||
close(call.done)
|
||||
|
||||
@@ -147,7 +192,15 @@ func (f *Fetcher) fetch(ctx context.Context, source, target string) (string, err
|
||||
// The two differ for a set: the shards waiting on it asked for the version, not
|
||||
// for the fourth file in it, and progress reported under the file's own URL
|
||||
// reaches nobody. What they see is one number climbing across the whole set.
|
||||
func (f *Fetcher) fetchAs(ctx context.Context, source, reportAs, target string) (string, error) {
|
||||
//
|
||||
// Each file is a "download" span, with how many bytes it took and where a
|
||||
// resumed one started from.
|
||||
func (f *Fetcher) fetchAs(ctx context.Context, source, reportAs, target string) (_ string, err error) {
|
||||
ctx, span := obs.Tracer(tracerName).Start(ctx, "download",
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("llmgw.weights.source", redact(source))))
|
||||
defer func() { obs.End(span, err) }()
|
||||
|
||||
url, err := resolveURL(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -208,6 +261,10 @@ func (f *Fetcher) fetchAs(ctx context.Context, source, reportAs, target string)
|
||||
total := existing + resp.ContentLength
|
||||
f.report(Progress{Source: reportAs, BytesDone: existing, BytesTotal: total})
|
||||
written, err := f.copyWithProgress(ctx, out, resp.Body, reportAs, existing, total)
|
||||
span.SetAttributes(
|
||||
attribute.Int64("llmgw.weights.resumed_from", existing),
|
||||
attribute.Int64("llmgw.weights.bytes", written),
|
||||
)
|
||||
closeErr := out.Close()
|
||||
if err != nil {
|
||||
// The part file is kept on purpose, so the next attempt resumes.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package weights
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs/obstest"
|
||||
)
|
||||
|
||||
func TestAFetchSaysInItsTraceWhetherItDownloadedAndHowMuch(t *testing.T) {
|
||||
rec := obstest.Record(t)
|
||||
srv := serveBytes(t, []byte("forty gigabytes, give or take"), nil)
|
||||
f := &Fetcher{CacheDir: t.TempDir()}
|
||||
src := strings.Replace(srv.URL, "http://", "http://user:secret@", 1) + "/m/model.gguf?token=hunter2"
|
||||
|
||||
if _, err := f.Ensure(t.Context(), src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fetch := rec.One(t, [16]byte{}, "fetch weights")
|
||||
a := obstest.Attrs(fetch)
|
||||
if a["llmgw.weights.outcome"] != "downloaded" {
|
||||
t.Errorf("the first fetch says %v", a)
|
||||
}
|
||||
if strings.Contains(a["llmgw.weights.source"], "secret") || strings.Contains(a["llmgw.weights.source"], "hunter2") {
|
||||
t.Errorf("the trace holds the source's credentials: %s", a["llmgw.weights.source"])
|
||||
}
|
||||
dl := rec.One(t, fetch.SpanContext().TraceID(), "download")
|
||||
if !obstest.ChildOf(dl, fetch) || obstest.Attrs(dl)["llmgw.weights.bytes"] != "29" {
|
||||
t.Errorf("the download does not say how much it moved: %v", obstest.Attrs(dl))
|
||||
}
|
||||
|
||||
// The second start on this node finds it here.
|
||||
if _, err := f.Ensure(t.Context(), src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again := rec.Named("fetch weights")
|
||||
if len(again) != 2 || obstest.Attrs(again[1])["llmgw.weights.outcome"] != "cached" {
|
||||
t.Errorf("the second fetch says %v", obstest.Attrs(again[len(again)-1]))
|
||||
}
|
||||
if len(rec.Named("download")) != 1 {
|
||||
t.Error("a cached file was downloaded again")
|
||||
}
|
||||
}
|
||||
@@ -120,8 +120,14 @@ func API(sink Sink, actor func(*http.Request) string, log *slog.Logger, next htt
|
||||
}
|
||||
var body []byte
|
||||
if r.Body != nil {
|
||||
// The first 64 KiB are what is recorded; the handler is given the
|
||||
// whole body, or a larger one — a quality suite sent whole — would
|
||||
// reach it cut off.
|
||||
body, _ = io.ReadAll(io.LimitReader(r.Body, 64<<10))
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
r.Body = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{io.MultiReader(bytes.NewReader(body), r.Body), r.Body}
|
||||
}
|
||||
sw := &statusWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(sw, r)
|
||||
|
||||
@@ -2,6 +2,7 @@ package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -58,3 +59,16 @@ func TestEveryChangeToTheAdminAPIIsRecorded(t *testing.T) {
|
||||
t.Errorf("%+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestABodyLargerThanWhatIsRecordedReachesTheHandlerWhole(t *testing.T) {
|
||||
big := `{"content":"` + strings.Repeat("x", 200<<10) + `"}`
|
||||
var got int
|
||||
h := API(&memSink{}, func(*http.Request) string { return "ilker" }, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = len(b)
|
||||
}))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/api/v1/models/m/eval", strings.NewReader(big)))
|
||||
if got != len(big) {
|
||||
t.Errorf("the handler was given %d of %d bytes", got, len(big))
|
||||
}
|
||||
}
|
||||
@@ -314,5 +314,9 @@ func BearerToken(r *http.Request) string {
|
||||
// A bare value is common enough in hand-written clients to accept.
|
||||
return strings.TrimSpace(h)
|
||||
}
|
||||
return strings.TrimSpace(r.Header.Get("api-key"))
|
||||
if k := r.Header.Get("api-key"); k != "" {
|
||||
return strings.TrimSpace(k)
|
||||
}
|
||||
// Anthropic's clients send their key here.
|
||||
return strings.TrimSpace(r.Header.Get("x-api-key"))
|
||||
}
|
||||
+24
-4
@@ -59,8 +59,13 @@ type Config struct {
|
||||
// is silent: nothing matches, every sample reads zero, and the suggested
|
||||
// thresholds are built on nothing.
|
||||
Engine string
|
||||
Model string
|
||||
APIKey string
|
||||
// MetricsKey is the engine key MetricsURL is read with. Not APIKey: that
|
||||
// is whatever Target takes, which for the gateway is a client's key, and
|
||||
// an engine that guards its metrics (llama.cpp, TensorRT-LLM) takes only
|
||||
// its own.
|
||||
MetricsKey string
|
||||
Model string
|
||||
APIKey string
|
||||
|
||||
// Concurrency is the ramp. Each level runs for Duration.
|
||||
Concurrency []int
|
||||
@@ -140,6 +145,10 @@ type Step struct {
|
||||
// FirstError is kept so a step that failed says why rather than just
|
||||
// reporting zeroes.
|
||||
FirstError string
|
||||
// MetricsUnread says why a step that was to read the engine's metrics
|
||||
// has none, so its zero queue depth and KV usage are not taken for an
|
||||
// idle engine.
|
||||
MetricsUnread string `json:",omitempty"`
|
||||
}
|
||||
|
||||
// Result is the whole ramp plus what it concluded.
|
||||
@@ -169,6 +178,17 @@ func Run(ctx context.Context, cfg Config, progress func(Step)) (Result, error) {
|
||||
return Result{}, err
|
||||
}
|
||||
res := Result{Model: cfg.Model, Target: cfg.Target, SLO: cfg.SLO, RanAt: time.Now()}
|
||||
|
||||
// Read once before any load. Metrics that cannot be read — refused for
|
||||
// want of the engine's key, or written in another engine's names — fail
|
||||
// every sample alike, and finding that out after the ramp has cost its
|
||||
// GPU time would leave a run with no thresholds to suggest.
|
||||
if cfg.MetricsURL != "" {
|
||||
if err := newSampler(cfg.MetricsURL, cfg.Engine, cfg.MetricsKey).read(ctx); err != nil {
|
||||
return Result{}, fmt.Errorf("bench: the engine's metrics cannot be read: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Minute}
|
||||
@@ -224,8 +244,7 @@ func runStep(ctx context.Context, client *http.Client, cfg Config, concurrency i
|
||||
firstErr string
|
||||
)
|
||||
|
||||
sampler := newSampler(cfg.MetricsURL, cfg.Engine)
|
||||
sampler.apiKey = cfg.APIKey
|
||||
sampler := newSampler(cfg.MetricsURL, cfg.Engine, cfg.MetricsKey)
|
||||
sampler.start(ctx)
|
||||
|
||||
start := time.Now()
|
||||
@@ -271,6 +290,7 @@ func runStep(ctx context.Context, client *http.Client, cfg Config, concurrency i
|
||||
step.TokensPerSec = float64(tokens) / elapsed.Seconds()
|
||||
}
|
||||
step.Waiting, step.Running, step.KVUsage = sampler.averages()
|
||||
step.MetricsUnread = sampler.unread()
|
||||
|
||||
// A step that could not complete anything has not met anything.
|
||||
step.MeetsSLO = step.Completed > 0 && step.Failed == 0 &&
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
)
|
||||
|
||||
// Caller sends a chat completion to a model as the gateway does for itself:
|
||||
// the router's Replay, past admission, accounting and the guardrails — a
|
||||
// suite measures the weights, and a tenant's quota or a guardrail's refusal
|
||||
// would measure something else. It answers the status, the body, and how
|
||||
// long it took.
|
||||
type Caller func(ctx context.Context, path, model string, body []byte) (int, []byte, time.Duration, error)
|
||||
|
||||
// Options are how a suite is run.
|
||||
type Options struct {
|
||||
// Model is the catalog model asked.
|
||||
Model string
|
||||
// Concurrency is how many cases are asked at once; 4 unless given.
|
||||
Concurrency int
|
||||
// Judge grades the cases scored by a rubric, instead of the suite's.
|
||||
Judge string
|
||||
// MinScore is the score to pass at, instead of the suite's threshold.
|
||||
MinScore float64
|
||||
// CaseTimeout bounds one case, its judging included; five minutes
|
||||
// unless given, which a model loading on demand needs.
|
||||
CaseTimeout time.Duration
|
||||
// Progress is told as each case finishes.
|
||||
Progress func(done, total int)
|
||||
}
|
||||
|
||||
// PassAt is the score a case passes at: a judge's 0.5 is a coin toss, and
|
||||
// counts as passed so a lenient rubric is not a hidden zero.
|
||||
const PassAt = 0.5
|
||||
|
||||
// keptAnswer is how much of an answer is kept with its result.
|
||||
const keptAnswer = 2000
|
||||
|
||||
// Evaluate asks a model every case of a suite and scores the answers. A
|
||||
// case that got no answer scores 0 with its error; a suite that cannot be
|
||||
// run at all — a rubric and no judge to read it — is an error before
|
||||
// anything is asked.
|
||||
func Evaluate(ctx context.Context, call Caller, s Suite, o Options) (store.EvalRun, error) {
|
||||
if o.Model == "" {
|
||||
return store.EvalRun{}, errors.New("no model to ask")
|
||||
}
|
||||
judge := o.Judge
|
||||
if judge == "" {
|
||||
judge = s.Judge
|
||||
}
|
||||
for _, c := range s.Cases {
|
||||
if c.Judge != "" && c.JudgeModel == "" && judge == "" {
|
||||
return store.EvalRun{}, fmt.Errorf("case %s is graded by a judge and the suite names none: "+
|
||||
"give one with --judge MODEL, or judge: in the suite", c.ID)
|
||||
}
|
||||
}
|
||||
threshold := s.Threshold
|
||||
if o.MinScore > 0 {
|
||||
threshold = o.MinScore
|
||||
}
|
||||
if threshold <= 0 {
|
||||
threshold = DefaultThreshold
|
||||
}
|
||||
workers := o.Concurrency
|
||||
if workers <= 0 {
|
||||
workers = 4
|
||||
}
|
||||
timeout := o.CaseTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 5 * time.Minute
|
||||
}
|
||||
|
||||
run := store.EvalRun{Model: o.Model, Suite: s.Name, SuiteHash: s.Hash, At: time.Now().UTC(),
|
||||
Threshold: threshold, Cases: len(s.Cases), Results: make([]store.EvalCase, len(s.Cases))}
|
||||
if s.NeedsJudge() {
|
||||
run.Judge = judge
|
||||
}
|
||||
todo := make(chan int)
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
done := 0
|
||||
for range min(workers, len(s.Cases)) {
|
||||
wg.Go(func() {
|
||||
for i := range todo {
|
||||
cctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
res := askOne(cctx, call, s, &s.Cases[i], o.Model, judge)
|
||||
cancel()
|
||||
mu.Lock()
|
||||
run.Results[i] = res
|
||||
done++
|
||||
if o.Progress != nil {
|
||||
o.Progress(done, len(s.Cases))
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
})
|
||||
}
|
||||
for i := range s.Cases {
|
||||
select {
|
||||
case todo <- i:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
close(todo)
|
||||
wg.Wait()
|
||||
run.TookMs = time.Since(run.At).Milliseconds()
|
||||
|
||||
var sum, weights float64
|
||||
firstErr := ""
|
||||
for i, r := range run.Results {
|
||||
if r.ID == "" {
|
||||
// Not asked: the run was stopped first.
|
||||
r = store.EvalCase{ID: s.Cases[i].ID, Kind: s.Cases[i].Kind(), Weight: s.Cases[i].Weight,
|
||||
Error: "not asked: the run was stopped"}
|
||||
run.Results[i] = r
|
||||
}
|
||||
sum += r.Weight * r.Score
|
||||
weights += r.Weight
|
||||
if !r.Passed {
|
||||
run.Below++
|
||||
}
|
||||
if r.Error != "" {
|
||||
run.Errors++
|
||||
if firstErr == "" {
|
||||
firstErr = r.Error
|
||||
}
|
||||
}
|
||||
}
|
||||
if weights > 0 {
|
||||
run.Score = sum / weights
|
||||
}
|
||||
run.Passed = run.Score >= threshold
|
||||
if run.Errors == run.Cases {
|
||||
run.Passed = false
|
||||
run.Error = "no case was answered: " + firstErr
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// askedOf is the conversation a case sends.
|
||||
func askedOf(c *Case, suiteSystem string) []Message {
|
||||
var out []Message
|
||||
system := c.System
|
||||
if system == "" {
|
||||
system = suiteSystem
|
||||
}
|
||||
if system != "" && (len(c.Messages) == 0 || c.Messages[0].Role != "system") {
|
||||
out = append(out, Message{Role: "system", Content: system})
|
||||
}
|
||||
if len(c.Messages) > 0 {
|
||||
return append(out, c.Messages...)
|
||||
}
|
||||
return append(out, Message{Role: "user", Content: c.Prompt})
|
||||
}
|
||||
|
||||
// askOne asks one case and scores its answer.
|
||||
func askOne(ctx context.Context, call Caller, s Suite, c *Case, model, judge string) store.EvalCase {
|
||||
res := store.EvalCase{ID: c.ID, Kind: c.Kind(), Weight: c.Weight}
|
||||
start := time.Now()
|
||||
defer func() { res.TookMs = time.Since(start).Milliseconds() }()
|
||||
|
||||
maxTokens := c.MaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = s.MaxTokens
|
||||
}
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = defaultMaxTokens
|
||||
}
|
||||
temp := 0.0
|
||||
if c.Temperature != nil {
|
||||
temp = *c.Temperature
|
||||
}
|
||||
answer, finish, err := chat(ctx, call, model, askedOf(c, s.System), maxTokens, temp)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
answer = cleanAnswer(answer)
|
||||
res.Answer = answer
|
||||
if len(res.Answer) > keptAnswer {
|
||||
res.Answer = res.Answer[:keptAnswer]
|
||||
}
|
||||
|
||||
var v verdict
|
||||
if c.Judge != "" {
|
||||
jm := c.JudgeModel
|
||||
if jm == "" {
|
||||
jm = judge
|
||||
}
|
||||
reply, _, err := chat(ctx, call, jm, judgeRequest(c, answer), 256, 0)
|
||||
if err != nil {
|
||||
res.Error = "the judge " + jm + ": " + err.Error()
|
||||
return res
|
||||
}
|
||||
if v, err = readJudgement(reply); err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
} else {
|
||||
v = scoreRule(c, answer)
|
||||
}
|
||||
res.Score, res.Detail = v.score, v.detail
|
||||
res.Passed = res.Score >= PassAt
|
||||
if finish == "length" && !res.Passed {
|
||||
res.Detail += fmt.Sprintf("; the answer was cut off at %d tokens", maxTokens)
|
||||
}
|
||||
if answer == "" && !res.Passed {
|
||||
res.Detail += "; it answered nothing"
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// chat asks a model one conversation and says what it answered and why it
|
||||
// stopped.
|
||||
func chat(ctx context.Context, call Caller, model string, msgs []Message, maxTokens int, temp float64) (string, string, error) {
|
||||
body, err := json.Marshal(map[string]any{"model": model, "messages": msgs, "max_tokens": maxTokens,
|
||||
"temperature": temp, "stream": false})
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
status, out, _, err := call(ctx, "/v1/chat/completions", model, body)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
var e struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
msg := strings.TrimSpace(string(out))
|
||||
if json.Unmarshal(out, &e) == nil && e.Error.Message != "" {
|
||||
msg = e.Error.Message
|
||||
}
|
||||
return "", "", fmt.Errorf("%s answered %d: %s", model, status, clip(msg, 200))
|
||||
}
|
||||
var resp struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
if err := json.Unmarshal(out, &resp); err != nil || len(resp.Choices) == 0 {
|
||||
return "", "", fmt.Errorf("%s's answer is not a chat completion: %s", model, clip(string(out), 120))
|
||||
}
|
||||
return resp.Choices[0].Message.Content, resp.Choices[0].FinishReason, nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
)
|
||||
|
||||
const arith = `
|
||||
name: arith
|
||||
threshold: 0.75
|
||||
judge: grader
|
||||
cases:
|
||||
- id: add
|
||||
prompt: "What is 17 + 25? Answer with the number only."
|
||||
number: 42
|
||||
- id: mul
|
||||
prompt: "What is 6 * 7?"
|
||||
number: 42
|
||||
weight: 2
|
||||
- id: capital
|
||||
prompt: "What is the capital of France?"
|
||||
contains: Paris
|
||||
- id: polite
|
||||
prompt: "Say hello."
|
||||
judge: "A greeting of any kind passes."
|
||||
`
|
||||
|
||||
// fakeModel answers by the prompt, and as a judge by what it was asked to
|
||||
// grade; it counts what it was asked.
|
||||
type fakeModel struct {
|
||||
mu sync.Mutex
|
||||
answers map[string]string
|
||||
asked []string
|
||||
inFlight, most atomic.Int32
|
||||
}
|
||||
|
||||
func (f *fakeModel) call(_ context.Context, path, model string, body []byte) (int, []byte, time.Duration, error) {
|
||||
n := f.inFlight.Add(1)
|
||||
defer f.inFlight.Add(-1)
|
||||
for {
|
||||
m := f.most.Load()
|
||||
if n <= m || f.most.CompareAndSwap(m, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
var req struct {
|
||||
Model string `json:"model"`
|
||||
Messages []Message `json:"messages"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &req); err != nil || path != "/v1/chat/completions" || req.Model != model {
|
||||
return 400, []byte(`{"error":{"message":"bad request"}}`), 0, nil
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.asked = append(f.asked, model)
|
||||
f.mu.Unlock()
|
||||
last := req.Messages[len(req.Messages)-1].Content
|
||||
answer := "I do not know"
|
||||
switch {
|
||||
case model == "grader":
|
||||
answer = `{"score": 0, "reason": "no greeting"}`
|
||||
if strings.Contains(last, "Answer:\nHello") {
|
||||
answer = `{"score": 1, "reason": "a greeting"}`
|
||||
}
|
||||
case model == "missing":
|
||||
return 404, []byte(`{"error":{"message":"the model \"missing\" does not exist"}}`), 0, nil
|
||||
default:
|
||||
for k, v := range f.answers {
|
||||
if strings.Contains(last, k) {
|
||||
answer = v
|
||||
}
|
||||
}
|
||||
}
|
||||
out, _ := json.Marshal(map[string]any{"choices": []any{map[string]any{
|
||||
"message": map[string]any{"content": answer}, "finish_reason": "stop"}}})
|
||||
return 200, out, 0, nil
|
||||
}
|
||||
|
||||
func TestASuiteIsAskedAndScoredByWeight(t *testing.T) {
|
||||
s, err := Parse("arith.yaml", []byte(arith))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &fakeModel{answers: map[string]string{"17 + 25": "<think>carry</think>42", "6 * 7": "41",
|
||||
"France": "Paris.", "hello": "Hello there!"}}
|
||||
var progress atomic.Int32
|
||||
run, err := Evaluate(context.Background(), f.call, s, Options{Model: "qwen", Concurrency: 2,
|
||||
Progress: func(done, total int) { progress.Store(int32(done)) }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// add 1, mul 0 at weight 2, capital 1, polite 1: 3 of 5.
|
||||
if run.Score != 0.6 || run.Passed || run.Threshold != 0.75 || run.Below != 1 || run.Cases != 4 ||
|
||||
run.Suite != "arith" || run.Judge != "grader" || len(run.SuiteHash) != 64 {
|
||||
t.Fatalf("%+v", run)
|
||||
}
|
||||
byID := map[string]store.EvalCase{}
|
||||
for _, r := range run.Results {
|
||||
byID[r.ID] = r
|
||||
}
|
||||
if r := byID["add"]; !r.Passed || r.Answer != "42" || r.Kind != "number" {
|
||||
t.Errorf("add: %+v", r)
|
||||
}
|
||||
if r := byID["mul"]; r.Passed || !strings.Contains(r.Detail, "read 41, wanted 42") || r.Weight != 2 {
|
||||
t.Errorf("mul: %+v", r)
|
||||
}
|
||||
if r := byID["polite"]; !r.Passed || !strings.Contains(r.Detail, "the judge: a greeting") {
|
||||
t.Errorf("polite: %+v", r)
|
||||
}
|
||||
if progress.Load() != 4 || f.most.Load() > 2 {
|
||||
t.Errorf("progress %d, %d at once with a concurrency of 2", progress.Load(), f.most.Load())
|
||||
}
|
||||
|
||||
// A lower bar passes the same answers.
|
||||
run, _ = Evaluate(context.Background(), f.call, s, Options{Model: "qwen", MinScore: 0.5})
|
||||
if !run.Passed || run.Threshold != 0.5 {
|
||||
t.Errorf("at 0.5: %+v", run)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAModelThatAnswersNothingFailsWithWhy(t *testing.T) {
|
||||
s, _ := Parse("arith.yaml", []byte(arith))
|
||||
run, err := Evaluate(context.Background(), (&fakeModel{}).call, s, Options{Model: "missing"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if run.Passed || run.Errors != 4 || !strings.Contains(run.Error, `"missing" does not exist`) {
|
||||
t.Fatalf("%+v", run)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARubricWithNoJudgeIsRefusedBeforeAnythingIsAsked(t *testing.T) {
|
||||
s, _ := Parse("arith.yaml", []byte(strings.Replace(arith, "judge: grader\n", "", 1)))
|
||||
f := &fakeModel{}
|
||||
if _, err := Evaluate(context.Background(), f.call, s, Options{Model: "qwen"}); err == nil ||
|
||||
!strings.Contains(err.Error(), "--judge") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if len(f.asked) != 0 {
|
||||
t.Errorf("asked %v first", f.asked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASuiteIsReadFromJSONLinesAsFromYAML(t *testing.T) {
|
||||
jsonl := `{"name": "fmt", "threshold": 0.5}
|
||||
{"id": "a", "prompt": "Give JSON", "json_schema": {"type": "object", "required": ["ok"]}}
|
||||
{"prompt": "Say yes", "regex": "^yes", "ignore_case": true, "weight": 3}
|
||||
`
|
||||
s, err := Parse("format.jsonl", []byte(jsonl))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Name != "fmt" || s.Threshold != 0.5 || len(s.Cases) != 2 || s.Cases[1].ID != "case-2" ||
|
||||
s.Cases[1].Weight != 3 || s.Cases[0].schema == nil || s.Cases[1].re == nil {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
// Named by its file when it names nothing, and 0.8 to pass.
|
||||
s, err = Parse("dir/plain.jsonl", []byte(`{"prompt": "q", "exact": "a"}`))
|
||||
if err != nil || s.Name != "plain" || s.Threshold != DefaultThreshold {
|
||||
t.Fatalf("%+v %v", s, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASuiteThatCannotBeScoredIsRefusedSayingWhy(t *testing.T) {
|
||||
for _, tc := range []struct{ suite, why string }{
|
||||
{"cases: []", "no cases"},
|
||||
{"cases:\n - prompt: q", "no way to score it"},
|
||||
{"cases:\n - prompt: q\n exact: a\n regex: b", "exact and regex"},
|
||||
{"cases:\n - exact: a", "nothing to ask"},
|
||||
{"cases:\n - prompt: q\n regex: '('", "the regex"},
|
||||
{"cases:\n - id: x\n prompt: q\n exact: a\n - id: x\n prompt: q\n exact: a", "two cases are called x"},
|
||||
{"threshold: 2\ncases:\n - prompt: q\n exact: a", "not 0 to 1"},
|
||||
{"cases:\n - prompt: q\n exactly: a", "exactly"},
|
||||
{"cases:\n - messages: [{role: robot, content: hi}]\n exact: a", "role"},
|
||||
} {
|
||||
if _, err := Parse("s.yaml", []byte(tc.suite)); err == nil || !strings.Contains(err.Error(), tc.why) {
|
||||
t.Errorf("%q: %v, wanted it to say %q", tc.suite, err, tc.why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
runs []store.EvalRun
|
||||
}
|
||||
|
||||
func (m *memStore) PutEvalRun(_ context.Context, r store.EvalRun) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.runs = append(m.runs, r)
|
||||
return nil
|
||||
}
|
||||
func (m *memStore) EvalRuns(_ context.Context, model string, _ int) ([]store.EvalRun, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
var out []store.EvalRun
|
||||
for i := len(m.runs) - 1; i >= 0; i-- {
|
||||
if r := m.runs[i]; model == "" || r.Model == model || r.Target == model {
|
||||
r.Results = nil
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (m *memStore) EvalRunByID(_ context.Context, id string) (store.EvalRun, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, r := range m.runs {
|
||||
if r.ID == id {
|
||||
return r, nil
|
||||
}
|
||||
}
|
||||
return store.EvalRun{}, store.ErrNotFound
|
||||
}
|
||||
|
||||
func TestTheControlPlaneRunsSuitesByNameAndFilesACanarysRunUnderItsModel(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "arith.yaml"), []byte(arith), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "broken.yaml"), []byte("cases: [}"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
builtin := fstest.MapFS{
|
||||
"arith.yaml": {Data: []byte("cases:\n - prompt: shadowed\n exact: x\n")},
|
||||
"json-format.yaml": {Data: []byte("description: JSON\ncases:\n - prompt: q\n json_schema: {type: object}\n")},
|
||||
}
|
||||
f := &fakeModel{answers: map[string]string{"17 + 25": "42", "6 * 7": "42", "France": "Paris", "hello": "Hello"}}
|
||||
st := &memStore{}
|
||||
svc := NewService(Deps{Call: f.call, Store: st, Dir: dir, Builtin: builtin, Log: slog.New(slog.DiscardHandler),
|
||||
Origin: func(m string) (string, string) { return "o/r", "rev-of-" + m },
|
||||
CanaryOf: func(n string) string {
|
||||
if parent, ok := strings.CutSuffix(n, "-canary"); ok {
|
||||
return parent
|
||||
}
|
||||
return ""
|
||||
},
|
||||
})
|
||||
|
||||
suites := svc.Suites()
|
||||
if len(suites) != 3 || suites[0].Name != "arith" || suites[0].From != filepath.Join(dir, "arith.yaml") ||
|
||||
suites[0].Cases != 4 || !suites[0].Judge || suites[1].Error == "" || suites[2].From != "built in" {
|
||||
t.Fatalf("%+v", suites)
|
||||
}
|
||||
if _, err := svc.Load(Request{Suite: "../etc/passwd"}); err == nil {
|
||||
t.Error("a path outside the eval directory was read")
|
||||
}
|
||||
|
||||
live, err := svc.Start("qwen-canary", Request{Suite: "arith"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if live.State != Running || live.Model != "qwen" || live.Target != "qwen-canary" || live.Cases != 4 {
|
||||
t.Fatalf("%+v", live)
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for live.State == Running && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
live, _ = svc.Get(context.Background(), live.ID)
|
||||
}
|
||||
if live.State != Done || live.Score != 1 || !live.Passed || live.Revision != "rev-of-qwen-canary" || live.By != "tester" {
|
||||
t.Fatalf("%+v", live)
|
||||
}
|
||||
if kept, err := st.EvalRunByID(context.Background(), live.ID); err != nil || len(kept.Results) != 4 {
|
||||
t.Fatalf("kept %+v %v", kept, err)
|
||||
}
|
||||
|
||||
// A gate waits for its run, and files it with the job.
|
||||
run, err := svc.Run(context.Background(), "qwen", Request{Suite: "json-format"}, "tester", "update-1")
|
||||
if err != nil || run.Job != "update-1" || run.Passed || run.Target != "" {
|
||||
t.Fatalf("%+v %v", run, err)
|
||||
}
|
||||
hist, err := svc.History(context.Background(), "qwen", 10)
|
||||
if err != nil || len(hist) != 2 || hist[0].ID != run.ID || hist[1].ID != live.ID {
|
||||
t.Fatalf("%+v %v", hist, err)
|
||||
}
|
||||
if _, err := svc.Get(context.Background(), "eval-nope"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Errorf("%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// A JSON Schema validator for what a suite asks of an answer's shape: types,
|
||||
// properties, required ones, items, enums, bounds and patterns. Not the whole
|
||||
// standard — no $ref, no oneOf — and a schema using what is not here is
|
||||
// refused when the suite is read rather than passed by an answer it never
|
||||
// checked.
|
||||
|
||||
type schema struct {
|
||||
types []string
|
||||
properties map[string]*schema
|
||||
required []string
|
||||
additional *schema // nil: anything; noneAllowed: nothing
|
||||
items *schema
|
||||
enum []any
|
||||
constant any
|
||||
hasConst bool
|
||||
minimum, maximum *float64
|
||||
exclMin, exclMax *float64
|
||||
minLength, maxLength *int
|
||||
minItems, maxItems *int
|
||||
pattern *regexp.Regexp
|
||||
anyOf, allOf []*schema
|
||||
never bool
|
||||
}
|
||||
|
||||
// noneAllowed is additionalProperties: false.
|
||||
var noneAllowed = &schema{never: true}
|
||||
|
||||
// annotations are keywords that describe rather than constrain.
|
||||
var annotations = map[string]bool{"$schema": true, "$id": true, "title": true, "description": true,
|
||||
"default": true, "examples": true, "format": true, "$comment": true}
|
||||
|
||||
func compileSchema(v any) (*schema, error) {
|
||||
// Through JSON, so a schema written in YAML and one in JSON are the same
|
||||
// thing by the time they are read: numbers as float64, maps as map[string]any.
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var raw any
|
||||
if err := json.Unmarshal(b, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return compile(raw, "")
|
||||
}
|
||||
|
||||
func compile(raw any, at string) (*schema, error) {
|
||||
if b, ok := raw.(bool); ok {
|
||||
if b {
|
||||
return &schema{}, nil
|
||||
}
|
||||
return noneAllowed, nil
|
||||
}
|
||||
m, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s is not a schema object", where(at))
|
||||
}
|
||||
s := &schema{}
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
v := m[k]
|
||||
var err error
|
||||
switch k {
|
||||
case "type":
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
s.types = []string{t}
|
||||
case []any:
|
||||
for _, x := range t {
|
||||
if str, ok := x.(string); ok {
|
||||
s.types = append(s.types, str)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, t := range s.types {
|
||||
if !slices.Contains([]string{"object", "array", "string", "number", "integer", "boolean", "null"}, t) {
|
||||
return nil, fmt.Errorf("%s: %q is not a JSON type", where(at), t)
|
||||
}
|
||||
}
|
||||
case "properties":
|
||||
props, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: properties is not an object", where(at))
|
||||
}
|
||||
s.properties = map[string]*schema{}
|
||||
for name, p := range props {
|
||||
if s.properties[name], err = compile(p, at+"."+name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
case "required":
|
||||
list, _ := v.([]any)
|
||||
for _, x := range list {
|
||||
if str, ok := x.(string); ok {
|
||||
s.required = append(s.required, str)
|
||||
}
|
||||
}
|
||||
case "additionalProperties":
|
||||
if s.additional, err = compile(v, at+".*"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "items":
|
||||
if s.items, err = compile(v, at+"[]"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "enum":
|
||||
s.enum, _ = v.([]any)
|
||||
case "const":
|
||||
s.constant, s.hasConst = v, true
|
||||
case "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum":
|
||||
f, ok := v.(float64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: %s is not a number", where(at), k)
|
||||
}
|
||||
*map[string]**float64{"minimum": &s.minimum, "maximum": &s.maximum,
|
||||
"exclusiveMinimum": &s.exclMin, "exclusiveMaximum": &s.exclMax}[k] = &f
|
||||
case "minLength", "maxLength", "minItems", "maxItems":
|
||||
f, ok := v.(float64)
|
||||
if !ok || f < 0 || f != math.Trunc(f) {
|
||||
return nil, fmt.Errorf("%s: %s is not a whole number", where(at), k)
|
||||
}
|
||||
n := int(f)
|
||||
*map[string]**int{"minLength": &s.minLength, "maxLength": &s.maxLength,
|
||||
"minItems": &s.minItems, "maxItems": &s.maxItems}[k] = &n
|
||||
case "pattern":
|
||||
str, _ := v.(string)
|
||||
if s.pattern, err = regexp.Compile(str); err != nil {
|
||||
return nil, fmt.Errorf("%s: pattern: %w", where(at), err)
|
||||
}
|
||||
case "anyOf", "allOf":
|
||||
list, ok := v.([]any)
|
||||
if !ok || len(list) == 0 {
|
||||
return nil, fmt.Errorf("%s: %s is not a list of schemas", where(at), k)
|
||||
}
|
||||
for i, x := range list {
|
||||
sub, err := compile(x, fmt.Sprintf("%s(%s %d)", at, k, i+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if k == "anyOf" {
|
||||
s.anyOf = append(s.anyOf, sub)
|
||||
} else {
|
||||
s.allOf = append(s.allOf, sub)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if !annotations[k] {
|
||||
return nil, fmt.Errorf("%s: %s is not supported here (type, properties, required, "+
|
||||
"additionalProperties, items, enum, const, minimum, maximum, exclusiveMinimum, exclusiveMaximum, "+
|
||||
"minLength, maxLength, minItems, maxItems, pattern, anyOf and allOf are)", where(at), k)
|
||||
}
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func where(at string) string {
|
||||
if at == "" {
|
||||
return "the schema"
|
||||
}
|
||||
return "the schema at " + strings.TrimPrefix(at, ".")
|
||||
}
|
||||
|
||||
// validate says what is wrong with v, or "".
|
||||
func (s *schema) validate(v any, at string) string {
|
||||
if s.never {
|
||||
return fmt.Sprintf("%s is not allowed", place(at))
|
||||
}
|
||||
if len(s.types) > 0 && !slices.ContainsFunc(s.types, func(t string) bool { return isType(v, t) }) {
|
||||
return fmt.Sprintf("%s is %s, not %s", place(at), typeOf(v), strings.Join(s.types, " or "))
|
||||
}
|
||||
if s.hasConst && !equal(v, s.constant) {
|
||||
return fmt.Sprintf("%s is %s, not %s", place(at), short(v), short(s.constant))
|
||||
}
|
||||
if s.enum != nil && !slices.ContainsFunc(s.enum, func(e any) bool { return equal(v, e) }) {
|
||||
return fmt.Sprintf("%s is %s, not one of %s", place(at), short(v), short(s.enum))
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
switch {
|
||||
case s.minimum != nil && x < *s.minimum:
|
||||
return fmt.Sprintf("%s is %v, below %v", place(at), x, *s.minimum)
|
||||
case s.maximum != nil && x > *s.maximum:
|
||||
return fmt.Sprintf("%s is %v, above %v", place(at), x, *s.maximum)
|
||||
case s.exclMin != nil && x <= *s.exclMin:
|
||||
return fmt.Sprintf("%s is %v, not above %v", place(at), x, *s.exclMin)
|
||||
case s.exclMax != nil && x >= *s.exclMax:
|
||||
return fmt.Sprintf("%s is %v, not below %v", place(at), x, *s.exclMax)
|
||||
}
|
||||
case string:
|
||||
n := utf8.RuneCountInString(x)
|
||||
switch {
|
||||
case s.minLength != nil && n < *s.minLength:
|
||||
return fmt.Sprintf("%s is %d characters, fewer than %d", place(at), n, *s.minLength)
|
||||
case s.maxLength != nil && n > *s.maxLength:
|
||||
return fmt.Sprintf("%s is %d characters, more than %d", place(at), n, *s.maxLength)
|
||||
case s.pattern != nil && !s.pattern.MatchString(x):
|
||||
return fmt.Sprintf("%s, %s, does not match %s", place(at), short(x), s.pattern)
|
||||
}
|
||||
case []any:
|
||||
switch {
|
||||
case s.minItems != nil && len(x) < *s.minItems:
|
||||
return fmt.Sprintf("%s has %d items, fewer than %d", place(at), len(x), *s.minItems)
|
||||
case s.maxItems != nil && len(x) > *s.maxItems:
|
||||
return fmt.Sprintf("%s has %d items, more than %d", place(at), len(x), *s.maxItems)
|
||||
}
|
||||
if s.items != nil {
|
||||
for i, e := range x {
|
||||
if why := s.items.validate(e, fmt.Sprintf("%s[%d]", at, i)); why != "" {
|
||||
return why
|
||||
}
|
||||
}
|
||||
}
|
||||
case map[string]any:
|
||||
for _, r := range s.required {
|
||||
if _, ok := x[r]; !ok {
|
||||
return fmt.Sprintf("%s has no %s", place(at), r)
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(x))
|
||||
for k := range x {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if p, ok := s.properties[k]; ok {
|
||||
if why := p.validate(x[k], at+"."+k); why != "" {
|
||||
return why
|
||||
}
|
||||
} else if s.additional != nil {
|
||||
if why := s.additional.validate(x[k], at+"."+k); why != "" {
|
||||
return why
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, sub := range s.allOf {
|
||||
if why := sub.validate(v, at); why != "" {
|
||||
return why
|
||||
}
|
||||
}
|
||||
if len(s.anyOf) > 0 {
|
||||
var first string
|
||||
for _, sub := range s.anyOf {
|
||||
why := sub.validate(v, at)
|
||||
if why == "" {
|
||||
return ""
|
||||
}
|
||||
if first == "" {
|
||||
first = why
|
||||
}
|
||||
}
|
||||
return first + " (nor any other choice)"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func place(at string) string {
|
||||
if at == "" {
|
||||
return "the answer"
|
||||
}
|
||||
return strings.TrimPrefix(at, ".")
|
||||
}
|
||||
|
||||
func isType(v any, t string) bool {
|
||||
switch t {
|
||||
case "object":
|
||||
_, ok := v.(map[string]any)
|
||||
return ok
|
||||
case "array":
|
||||
_, ok := v.([]any)
|
||||
return ok
|
||||
case "string":
|
||||
_, ok := v.(string)
|
||||
return ok
|
||||
case "number":
|
||||
_, ok := v.(float64)
|
||||
return ok
|
||||
case "integer":
|
||||
f, ok := v.(float64)
|
||||
return ok && f == math.Trunc(f)
|
||||
case "boolean":
|
||||
_, ok := v.(bool)
|
||||
return ok
|
||||
case "null":
|
||||
return v == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func typeOf(v any) string {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
return "an object"
|
||||
case []any:
|
||||
return "a list"
|
||||
case string:
|
||||
return "a string"
|
||||
case float64:
|
||||
if x == math.Trunc(x) {
|
||||
return "an integer"
|
||||
}
|
||||
return "a number"
|
||||
case bool:
|
||||
return "a boolean"
|
||||
case nil:
|
||||
return "null"
|
||||
}
|
||||
return fmt.Sprintf("%T", v)
|
||||
}
|
||||
|
||||
func equal(a, b any) bool { return reflect.DeepEqual(a, b) }
|
||||
|
||||
func short(v any) string {
|
||||
b, _ := json.Marshal(v)
|
||||
s := string(b)
|
||||
if len(s) > 60 {
|
||||
s = s[:57] + "..."
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// verdict is how one answer scored, 0 to 1, and why.
|
||||
type verdict struct {
|
||||
score float64
|
||||
detail string
|
||||
}
|
||||
|
||||
func pass(detail string) verdict { return verdict{1, detail} }
|
||||
func fail(detail string) verdict { return verdict{0, detail} }
|
||||
|
||||
var thinkBlock = regexp.MustCompile(`(?s)<think>.*?</think>`)
|
||||
|
||||
// cleanAnswer is what a model said, without a reasoning model's thinking —
|
||||
// what a reader is shown — and without the white space around it.
|
||||
func cleanAnswer(s string) string {
|
||||
s = thinkBlock.ReplaceAllString(s, "")
|
||||
// A reply cut off while still thinking has an opening tag and no close.
|
||||
if i := strings.Index(s, "<think>"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// scoreRule scores an answer by a case's rule; a case graded by a judge is
|
||||
// scored elsewhere, since it takes another request.
|
||||
func scoreRule(c *Case, answer string) verdict {
|
||||
fold := func(s string) string {
|
||||
if c.IgnoreCase {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
return s
|
||||
}
|
||||
switch {
|
||||
case c.Exact != nil:
|
||||
if fold(answer) == fold(strings.TrimSpace(*c.Exact)) {
|
||||
return pass("the answer is exactly that")
|
||||
}
|
||||
return fail(fmt.Sprintf("wanted exactly %q", strings.TrimSpace(*c.Exact)))
|
||||
case len(c.Contains) > 0:
|
||||
var missing []string
|
||||
for _, want := range c.Contains {
|
||||
if !strings.Contains(fold(answer), fold(want)) {
|
||||
missing = append(missing, strconv.Quote(want))
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return pass("has everything asked for")
|
||||
}
|
||||
return fail("has no " + strings.Join(missing, ", "))
|
||||
case c.re != nil:
|
||||
if c.re.MatchString(answer) {
|
||||
return pass("matches")
|
||||
}
|
||||
return fail("does not match " + c.re.String())
|
||||
case c.Number != nil:
|
||||
got, ok := lastNumber(answer)
|
||||
if !ok {
|
||||
return fail(fmt.Sprintf("no number in the answer; wanted %v", *c.Number))
|
||||
}
|
||||
if math.Abs(got-*c.Number) <= c.Tolerance {
|
||||
return pass(fmt.Sprintf("read %v", got))
|
||||
}
|
||||
want := fmt.Sprintf("%v", *c.Number)
|
||||
if c.Tolerance > 0 {
|
||||
want += fmt.Sprintf(" ± %v", c.Tolerance)
|
||||
}
|
||||
return fail(fmt.Sprintf("read %v, wanted %s", got, want))
|
||||
case c.schema != nil:
|
||||
v, err := readJSON(answer)
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
if why := c.schema.validate(v, ""); why != "" {
|
||||
return fail(why)
|
||||
}
|
||||
return pass("JSON of the shape asked for")
|
||||
}
|
||||
return fail("no rule to score it by")
|
||||
}
|
||||
|
||||
// number is a number as a model writes one: a sign, thousands separated by
|
||||
// commas, a decimal part, an exponent.
|
||||
var number = regexp.MustCompile(`[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[eE][-+]?\d+)?`)
|
||||
|
||||
// lastNumber is the last number in a text: a model that shows its working
|
||||
// ends with the result, and one that does not says only the result.
|
||||
func lastNumber(s string) (float64, bool) {
|
||||
all := number.FindAllStringIndex(s, -1)
|
||||
if len(all) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
i, j := all[len(all)-1][0], all[len(all)-1][1]
|
||||
// A hyphen after a digit or letter joins (3-5, 2026-10-04); it is not a
|
||||
// minus sign.
|
||||
if (s[i] == '-' || s[i] == '+') && i > 0 && isWordByte(s[i-1]) {
|
||||
i++
|
||||
}
|
||||
f, err := strconv.ParseFloat(strings.ReplaceAll(s[i:j], ",", ""), 64)
|
||||
return f, err == nil
|
||||
}
|
||||
|
||||
func isWordByte(b byte) bool {
|
||||
return b >= '0' && b <= '9' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z'
|
||||
}
|
||||
|
||||
var fence = regexp.MustCompile("(?s)```(?:json|JSON)?\\s*(.*?)```")
|
||||
|
||||
// readJSON reads an answer as JSON: the whole of it, else what is inside a
|
||||
// code fence, else from the first brace or bracket to the last — models
|
||||
// asked for JSON wrap it in a sentence often enough that refusing that would
|
||||
// measure manners rather than the shape.
|
||||
func readJSON(answer string) (any, error) {
|
||||
try := []string{answer}
|
||||
if m := fence.FindStringSubmatch(answer); m != nil {
|
||||
try = append(try, m[1])
|
||||
}
|
||||
for _, pair := range [][2]string{{"{", "}"}, {"[", "]"}} {
|
||||
i, j := strings.Index(answer, pair[0]), strings.LastIndex(answer, pair[1])
|
||||
if i >= 0 && j > i {
|
||||
try = append(try, answer[i:j+1])
|
||||
}
|
||||
}
|
||||
for _, t := range try {
|
||||
var v any
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(t)), &v) == nil {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
if answer == "" {
|
||||
return nil, fmt.Errorf("the answer is empty, not JSON")
|
||||
}
|
||||
return nil, fmt.Errorf("the answer is not JSON: %s", clip(answer, 80))
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n-3] + "..."
|
||||
}
|
||||
|
||||
// judgePrompt asks a model to grade an answer by a rubric.
|
||||
const judgePrompt = "You grade an answer to a question against a rubric. Read the question, the answer " +
|
||||
"and the rubric, then reply with only a JSON object: {\"score\": a number from 0 to 1, " +
|
||||
"\"reason\": \"one short sentence\"}. 1 means the answer meets the rubric fully, 0 not at all."
|
||||
|
||||
// judgeRequest is what a judge is asked about one answer.
|
||||
func judgeRequest(c *Case, answer string) []Message {
|
||||
var q strings.Builder
|
||||
for _, m := range askedOf(c, "") {
|
||||
if m.Role == "system" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&q, "%s: %s\n", m.Role, m.Content)
|
||||
}
|
||||
return []Message{
|
||||
{Role: "system", Content: judgePrompt},
|
||||
{Role: "user", Content: fmt.Sprintf("Question:\n%s\nAnswer:\n%s\n\nRubric:\n%s", q.String(), answer, c.Judge)},
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
passWord = regexp.MustCompile(`(?i)\b(pass|passed|yes|correct)\b`)
|
||||
failWord = regexp.MustCompile(`(?i)\b(fail|failed|no|incorrect|wrong)\b`)
|
||||
)
|
||||
|
||||
// readJudgement reads a judge's reply: a JSON object with a score (or a
|
||||
// pass true or false), else a lone number, else the words pass or fail.
|
||||
func readJudgement(reply string) (verdict, error) {
|
||||
reply = cleanAnswer(reply)
|
||||
if v, err := readJSON(reply); err == nil {
|
||||
if m, ok := v.(map[string]any); ok {
|
||||
reason, _ := m["reason"].(string)
|
||||
if f, ok := m["score"].(float64); ok {
|
||||
return verdict{clamp(f), "the judge: " + clip(reason, 120)}, nil
|
||||
}
|
||||
if s, ok := m["score"].(string); ok {
|
||||
if f, err := strconv.ParseFloat(strings.TrimSpace(s), 64); err == nil {
|
||||
return verdict{clamp(f), "the judge: " + clip(reason, 120)}, nil
|
||||
}
|
||||
}
|
||||
if b, ok := m["pass"].(bool); ok {
|
||||
if b {
|
||||
return pass("the judge: " + clip(reason, 120)), nil
|
||||
}
|
||||
return fail("the judge: " + clip(reason, 120)), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if f, err := strconv.ParseFloat(strings.TrimSpace(reply), 64); err == nil {
|
||||
return verdict{clamp(f), "the judge gave " + strings.TrimSpace(reply)}, nil
|
||||
}
|
||||
p, f := passWord.MatchString(reply), failWord.MatchString(reply)
|
||||
switch {
|
||||
case p && !f:
|
||||
return pass("the judge: " + clip(reply, 120)), nil
|
||||
case f && !p:
|
||||
return fail("the judge: " + clip(reply, 120)), nil
|
||||
}
|
||||
return verdict{}, fmt.Errorf("the judge's answer could not be read as a score: %s", clip(reply, 120))
|
||||
}
|
||||
|
||||
func clamp(f float64) float64 { return math.Max(0, math.Min(1, f)) }
|
||||
@@ -0,0 +1,133 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func caseOf(t *testing.T, yamlCase string) *Case {
|
||||
t.Helper()
|
||||
s, err := Parse("t.yaml", []byte("cases:\n - prompt: q\n"+indent(yamlCase)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &s.Cases[0]
|
||||
}
|
||||
|
||||
func indent(s string) string {
|
||||
var b strings.Builder
|
||||
for _, l := range strings.Split(strings.TrimSpace(s), "\n") {
|
||||
b.WriteString(" " + l + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func TestEachRuleScoresTheAnswersItShouldAndRefusesTheRest(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
rule string
|
||||
answer string
|
||||
want float64
|
||||
}{
|
||||
{`exact: "42"`, "42", 1},
|
||||
{`exact: "42"`, " 42\n", 1},
|
||||
{`exact: "42"`, "42.", 0},
|
||||
{"exact: Paris\nignore_case: true", "PARIS", 1},
|
||||
{`contains: Paris`, "The capital is Paris.", 1},
|
||||
{`contains: [Paris, France]`, "Paris is in France", 1},
|
||||
{`contains: [Paris, France]`, "Paris", 0},
|
||||
{"contains: paris\nignore_case: true", "PARIS", 1},
|
||||
{`regex: '^\s*\d{4}-\d{2}-\d{2}\s*$'`, "2026-10-04", 1},
|
||||
{`regex: '^\d+$'`, "about 12", 0},
|
||||
{"regex: '^yes'\nignore_case: true", "Yes, it is", 1},
|
||||
{`number: 42`, "17 + 25 = 42", 1},
|
||||
{`number: 42`, "The answer is 42.", 1},
|
||||
{`number: 42`, "It is 41", 0},
|
||||
{`number: 1234567`, "1,234,567", 1},
|
||||
{"number: 3.14\ntolerance: 0.01", "pi is about 3.1416", 1},
|
||||
{"number: 3.14\ntolerance: 0.001", "pi is about 3.1416", 0},
|
||||
{`number: -5`, "3 - 8 = -5", 1},
|
||||
// A date's last part is a number, not a negative one.
|
||||
{`number: 4`, "from 2026-10-04", 1},
|
||||
{`number: 1`, "no number here", 0},
|
||||
} {
|
||||
c := caseOf(t, tc.rule)
|
||||
v := scoreRule(c, cleanAnswer(tc.answer))
|
||||
if v.score != tc.want {
|
||||
t.Errorf("%s against %q scored %v (%s), wanted %v", strings.ReplaceAll(tc.rule, "\n", "; "), tc.answer, v.score, v.detail, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAnswerIsReadAsJSONAndHeldToItsSchema(t *testing.T) {
|
||||
c := caseOf(t, `
|
||||
json_schema:
|
||||
type: object
|
||||
required: [name, age, tags]
|
||||
additionalProperties: false
|
||||
properties:
|
||||
name: {type: string, minLength: 1}
|
||||
age: {type: integer, minimum: 0, maximum: 150}
|
||||
tags: {type: array, items: {type: string}, maxItems: 3}
|
||||
kind: {enum: [cat, dog]}`)
|
||||
for _, tc := range []struct {
|
||||
answer string
|
||||
pass bool
|
||||
why string
|
||||
}{
|
||||
{`{"name": "Ada", "age": 36, "tags": ["math"]}`, true, ""},
|
||||
{"Here it is:\n```json\n{\"name\": \"Ada\", \"age\": 36, \"tags\": []}\n```", true, ""},
|
||||
{`Sure! {"name": "Ada", "age": 36, "tags": []} Hope that helps.`, true, ""},
|
||||
{`{"name": "Ada", "age": 36.5, "tags": []}`, false, "age is a number, not integer"},
|
||||
{`{"name": "Ada", "tags": []}`, false, "has no age"},
|
||||
{`{"name": "Ada", "age": 36, "tags": [], "extra": 1}`, false, "extra is not allowed"},
|
||||
{`{"name": "Ada", "age": 200, "tags": []}`, false, "above 150"},
|
||||
{`{"name": "Ada", "age": 3, "tags": [1]}`, false, "tags[0] is an integer, not string"},
|
||||
{`{"name": "Ada", "age": 3, "tags": [], "kind": "fish"}`, false, "not one of"},
|
||||
{`{"name": "", "age": 3, "tags": []}`, false, "fewer than 1"},
|
||||
{`not json at all`, false, "not JSON"},
|
||||
} {
|
||||
v := scoreRule(c, tc.answer)
|
||||
if (v.score == 1) != tc.pass || (tc.why != "" && !strings.Contains(v.detail, tc.why)) {
|
||||
t.Errorf("%q: %v %q, wanted pass=%v saying %q", tc.answer, v.score, v.detail, tc.pass, tc.why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestASchemaUsingWhatIsNotCheckedIsRefusedWhenTheSuiteIsRead(t *testing.T) {
|
||||
_, err := Parse("t.yaml", []byte("cases:\n - prompt: q\n json_schema: {oneOf: [{type: string}]}\n"))
|
||||
if err == nil || !strings.Contains(err.Error(), "oneOf is not supported") {
|
||||
t.Fatalf("a schema with oneOf was accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAJudgesReplyIsReadAsAScore(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
reply string
|
||||
want float64
|
||||
bad bool
|
||||
}{
|
||||
{`{"score": 0.8, "reason": "mostly right"}`, 0.8, false},
|
||||
{"<think>hmm</think>\n```json\n{\"score\": 1, \"reason\": \"ok\"}\n```", 1, false},
|
||||
{`{"score": "0.25"}`, 0.25, false},
|
||||
{`{"pass": false, "reason": "wrong city"}`, 0, false},
|
||||
{`{"score": 7}`, 1, false},
|
||||
{`0.6`, 0.6, false},
|
||||
{`PASS`, 1, false},
|
||||
{`Fail: it named the wrong city.`, 0, false},
|
||||
{`I cannot say.`, 0, true},
|
||||
} {
|
||||
v, err := readJudgement(tc.reply)
|
||||
if (err != nil) != tc.bad || v.score != tc.want {
|
||||
t.Errorf("%q: %v %v, wanted %v (unreadable: %v)", tc.reply, v.score, err, tc.want, tc.bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAReasoningModelsThinkingIsNotPartOfItsAnswer(t *testing.T) {
|
||||
if got := cleanAnswer("<think>\n17+25... carry the one\n</think>\n\n42"); got != "42" {
|
||||
t.Errorf("%q", got)
|
||||
}
|
||||
if got := cleanAnswer("<think>still thinking when it was cut off"); got != "" {
|
||||
t.Errorf("%q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package eval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
)
|
||||
|
||||
// The control plane's side: suites found on its disk or carried in the
|
||||
// binary, runs started and followed, and kept in the store.
|
||||
|
||||
// Store keeps finished runs.
|
||||
type Store interface {
|
||||
PutEvalRun(ctx context.Context, r store.EvalRun) error
|
||||
EvalRuns(ctx context.Context, model string, limit int) ([]store.EvalRun, error)
|
||||
EvalRunByID(ctx context.Context, id string) (store.EvalRun, error)
|
||||
}
|
||||
|
||||
// Deps are what the service runs suites with.
|
||||
type Deps struct {
|
||||
// Call asks a model: the router's Replay.
|
||||
Call Caller
|
||||
// Store keeps runs; without one they are kept here until a restart.
|
||||
Store Store
|
||||
// Dir is where suites are read from by name: control.eval_dir.
|
||||
Dir string
|
||||
// Builtin are the suites the binary carries, found when Dir has none
|
||||
// of the name.
|
||||
Builtin fs.FS
|
||||
// Origin is where a catalog model's weights came from, when known.
|
||||
Origin func(model string) (repo, revision string)
|
||||
// CanaryOf is the model a name is the canary of, or "": a run on a
|
||||
// canary is filed under the model it is a canary of.
|
||||
CanaryOf func(name string) string
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Request is a suite to run against a model: one on the control plane, by
|
||||
// its name, or one sent whole.
|
||||
type Request struct {
|
||||
// Suite is a suite's name in the eval directory, or carried in the
|
||||
// binary (arithmetic, json-format).
|
||||
Suite string `json:"suite,omitempty"`
|
||||
// Content is a suite's text instead, and File the name of the file it
|
||||
// was read from, which names the suite unless it names itself.
|
||||
Content string `json:"content,omitempty"`
|
||||
File string `json:"file,omitempty"`
|
||||
// Concurrency, Judge and MinScore are as Options has them.
|
||||
Concurrency int `json:"concurrency,omitempty"`
|
||||
Judge string `json:"judge,omitempty"`
|
||||
MinScore float64 `json:"min_score,omitempty"`
|
||||
}
|
||||
|
||||
// Named says which suite a request is, for a step's detail.
|
||||
func (r Request) Named() string {
|
||||
if r.Suite != "" {
|
||||
return r.Suite
|
||||
}
|
||||
return r.File
|
||||
}
|
||||
|
||||
// The states a run can be in.
|
||||
const (
|
||||
Running = "running"
|
||||
Done = "done"
|
||||
Failed = "failed"
|
||||
)
|
||||
|
||||
// Live is a run as it stands: one running, with how many of its cases are
|
||||
// done, or one finished.
|
||||
type Live struct {
|
||||
store.EvalRun
|
||||
State string `json:"state"`
|
||||
Done int `json:"done"`
|
||||
}
|
||||
|
||||
// SuiteInfo is a suite the control plane can run by name.
|
||||
type SuiteInfo struct {
|
||||
Name string `json:"name"`
|
||||
// From is the file it is read from, or "built in".
|
||||
From string `json:"from"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Cases int `json:"cases"`
|
||||
Threshold float64 `json:"threshold"`
|
||||
Judge bool `json:"judge,omitempty"`
|
||||
Hash string `json:"hash,omitempty"`
|
||||
// Error is why the file cannot be run.
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Service runs suites and remembers them.
|
||||
type Service struct {
|
||||
deps Deps
|
||||
mu sync.Mutex
|
||||
live map[string]*Live
|
||||
// order is the live runs oldest first, so the finished ones past
|
||||
// keepLive are forgotten — the store has them.
|
||||
order []string
|
||||
}
|
||||
|
||||
const keepLive = 50
|
||||
|
||||
// NewService builds a service.
|
||||
func NewService(d Deps) *Service {
|
||||
if d.Log == nil {
|
||||
d.Log = slog.Default()
|
||||
}
|
||||
return &Service{deps: d, live: map[string]*Live{}}
|
||||
}
|
||||
|
||||
var suiteExts = []string{".yaml", ".yml", ".jsonl", ".json"}
|
||||
|
||||
// Load reads the suite a request names or carries.
|
||||
func (s *Service) Load(r Request) (Suite, error) {
|
||||
if r.Content != "" {
|
||||
file := r.File
|
||||
if file == "" {
|
||||
file = "suite"
|
||||
}
|
||||
return Parse(file, []byte(r.Content))
|
||||
}
|
||||
name := strings.TrimSpace(r.Suite)
|
||||
if name == "" {
|
||||
return Suite{}, errors.New("no suite: name one on the control plane, or send one's text")
|
||||
}
|
||||
// A name, not a path: this reads the control plane's disk on behalf of
|
||||
// whoever holds the admin API, and only inside the eval directory.
|
||||
if strings.ContainsAny(name, `/\`) || name == "." || name == ".." {
|
||||
return Suite{}, fmt.Errorf("%q is not a suite's name: the control plane reads suites from %s by name; "+
|
||||
"send a file from elsewhere with its text", name, s.dirOrNone())
|
||||
}
|
||||
tries := []string{name}
|
||||
if !slices.Contains(suiteExts, filepath.Ext(name)) {
|
||||
tries = nil
|
||||
for _, e := range suiteExts {
|
||||
tries = append(tries, name+e)
|
||||
}
|
||||
}
|
||||
if s.deps.Dir != "" {
|
||||
for _, t := range tries {
|
||||
b, err := os.ReadFile(filepath.Join(s.deps.Dir, t))
|
||||
if err == nil {
|
||||
return Parse(t, b)
|
||||
}
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
return Suite{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.deps.Builtin != nil {
|
||||
for _, t := range tries {
|
||||
if b, err := fs.ReadFile(s.deps.Builtin, t); err == nil {
|
||||
return Parse(t, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
return Suite{}, fmt.Errorf("no suite called %s in %s or built in: `llmgw ctl eval --suites` lists them", name, s.dirOrNone())
|
||||
}
|
||||
|
||||
func (s *Service) dirOrNone() string {
|
||||
if s.deps.Dir == "" {
|
||||
return "no eval directory"
|
||||
}
|
||||
return s.deps.Dir
|
||||
}
|
||||
|
||||
// Suites are those the control plane can run by name: its directory's, and
|
||||
// the binary's that the directory does not replace.
|
||||
func (s *Service) Suites() []SuiteInfo {
|
||||
var out []SuiteInfo
|
||||
seen := map[string]bool{}
|
||||
add := func(fsys fs.FS, from func(string) string) {
|
||||
entries, err := fs.ReadDir(fsys, ".")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
ext := filepath.Ext(e.Name())
|
||||
if e.IsDir() || !slices.Contains(suiteExts, ext) {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSuffix(e.Name(), ext)
|
||||
if seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
info := SuiteInfo{Name: name, From: from(e.Name())}
|
||||
b, err := fs.ReadFile(fsys, e.Name())
|
||||
var su Suite
|
||||
if err == nil {
|
||||
su, err = Parse(e.Name(), b)
|
||||
}
|
||||
if err != nil {
|
||||
info.Error = err.Error()
|
||||
} else {
|
||||
info.Description, info.Cases, info.Threshold = su.Description, len(su.Cases), su.Threshold
|
||||
info.Judge, info.Hash = su.NeedsJudge(), su.Hash
|
||||
}
|
||||
out = append(out, info)
|
||||
}
|
||||
}
|
||||
if s.deps.Dir != "" {
|
||||
add(os.DirFS(s.deps.Dir), func(n string) string { return filepath.Join(s.deps.Dir, n) })
|
||||
}
|
||||
if s.deps.Builtin != nil {
|
||||
add(s.deps.Builtin, func(string) string { return "built in" })
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
b := make([]byte, 4)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("eval-%s-%s", time.Now().UTC().Format("20060102-150405"), hex.EncodeToString(b))
|
||||
}
|
||||
|
||||
// prepare reads the suite and checks it can be run against model, before
|
||||
// anything is asked.
|
||||
func (s *Service) prepare(model string, r Request) (Suite, error) {
|
||||
if s.deps.Call == nil {
|
||||
return Suite{}, errors.New("this control plane does not route requests, so it cannot ask a model")
|
||||
}
|
||||
if strings.TrimSpace(model) == "" {
|
||||
return Suite{}, errors.New("no model to ask")
|
||||
}
|
||||
su, err := s.Load(r)
|
||||
if err != nil {
|
||||
return Suite{}, err
|
||||
}
|
||||
if r.MinScore < 0 || r.MinScore > 1 {
|
||||
return Suite{}, fmt.Errorf("the minimum score %v is not 0 to 1", r.MinScore)
|
||||
}
|
||||
if su.NeedsJudge() && r.Judge == "" && su.Judge == "" {
|
||||
for _, c := range su.Cases {
|
||||
if c.Judge != "" && c.JudgeModel == "" {
|
||||
return Suite{}, fmt.Errorf("case %s of %s is graded by a judge and the suite names none: give one "+
|
||||
"with --judge MODEL", c.ID, su.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return su, nil
|
||||
}
|
||||
|
||||
// Check says whether a suite can be run against a model, without asking it
|
||||
// anything: for a gate, refused before its job starts rather than after the
|
||||
// new weights are fetched.
|
||||
func (s *Service) Check(model string, r Request) error {
|
||||
_, err := s.prepare(model, r)
|
||||
return err
|
||||
}
|
||||
|
||||
// file fills in what a run is filed under: the model it is about, the one
|
||||
// that answered, and where its weights came from.
|
||||
func (s *Service) file(run *store.EvalRun, asked string) {
|
||||
run.Model = asked
|
||||
if s.deps.CanaryOf != nil {
|
||||
if parent := s.deps.CanaryOf(asked); parent != "" {
|
||||
run.Model, run.Target = parent, asked
|
||||
}
|
||||
}
|
||||
if s.deps.Origin != nil {
|
||||
run.Repo, run.Revision = s.deps.Origin(asked)
|
||||
}
|
||||
}
|
||||
|
||||
// Start runs a suite against a model in the background and returns at once;
|
||||
// Get follows it.
|
||||
func (s *Service) Start(model string, r Request, by string) (Live, error) {
|
||||
su, err := s.prepare(model, r)
|
||||
if err != nil {
|
||||
return Live{}, err
|
||||
}
|
||||
l := &Live{State: Running}
|
||||
l.ID, l.Suite, l.SuiteHash, l.Cases, l.By, l.At = newID(), su.Name, su.Hash, len(su.Cases), by, time.Now().UTC()
|
||||
s.file(&l.EvalRun, model)
|
||||
s.mu.Lock()
|
||||
s.keep(l)
|
||||
s.mu.Unlock()
|
||||
go func() {
|
||||
_, _ = s.run(context.Background(), l, model, su, r)
|
||||
}()
|
||||
return s.snapshot(l), nil
|
||||
}
|
||||
|
||||
// Run runs a suite against a model and waits for it: for a gate, which
|
||||
// cannot go on until it knows. The run is kept like any other; job is the
|
||||
// update or promotion it gates.
|
||||
func (s *Service) Run(ctx context.Context, model string, r Request, by, job string) (store.EvalRun, error) {
|
||||
su, err := s.prepare(model, r)
|
||||
if err != nil {
|
||||
return store.EvalRun{}, err
|
||||
}
|
||||
l := &Live{State: Running}
|
||||
l.ID, l.Suite, l.SuiteHash, l.Cases, l.By, l.Job, l.At = newID(), su.Name, su.Hash, len(su.Cases), by, job, time.Now().UTC()
|
||||
s.file(&l.EvalRun, model)
|
||||
s.mu.Lock()
|
||||
s.keep(l)
|
||||
s.mu.Unlock()
|
||||
return s.run(ctx, l, model, su, r)
|
||||
}
|
||||
|
||||
func (s *Service) run(ctx context.Context, l *Live, model string, su Suite, r Request) (store.EvalRun, error) {
|
||||
run, err := Evaluate(ctx, s.deps.Call, su, Options{Model: model, Concurrency: r.Concurrency, Judge: r.Judge,
|
||||
MinScore: r.MinScore, Progress: func(done, _ int) {
|
||||
s.mu.Lock()
|
||||
l.Done = done
|
||||
s.mu.Unlock()
|
||||
}})
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
l.State, l.Error = Failed, err.Error()
|
||||
out := l.EvalRun
|
||||
s.mu.Unlock()
|
||||
return out, err
|
||||
}
|
||||
run.ID, run.By, run.Job = l.ID, l.By, l.Job
|
||||
run.Model, run.Target, run.Repo, run.Revision = l.Model, l.Target, l.Repo, l.Revision
|
||||
s.mu.Unlock()
|
||||
|
||||
// Kept before it is said to be done, so a history read in between does
|
||||
// not find it in neither place.
|
||||
if s.deps.Store != nil {
|
||||
// Its own context: a gate's caller giving up does not unkeep a run
|
||||
// that finished.
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := s.deps.Store.PutEvalRun(sctx, run); err != nil {
|
||||
s.deps.Log.Warn("could not keep an eval run", "run", run.ID, "model", run.Model, "err", err)
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
l.EvalRun, l.State, l.Done = run, Done, run.Cases
|
||||
s.mu.Unlock()
|
||||
s.deps.Log.Info("eval run finished", "run", run.ID, "model", run.Model, "target", run.Target,
|
||||
"suite", run.Suite, "score", fmt.Sprintf("%.3f", run.Score), "threshold", run.Threshold, "passed", run.Passed)
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// keep remembers a run, and forgets the oldest finished ones past keepLive.
|
||||
// Called with mu held.
|
||||
func (s *Service) keep(l *Live) {
|
||||
s.live[l.ID] = l
|
||||
s.order = append(s.order, l.ID)
|
||||
for len(s.order) > keepLive {
|
||||
oldest := s.live[s.order[0]]
|
||||
if oldest != nil && oldest.State == Running {
|
||||
break
|
||||
}
|
||||
delete(s.live, s.order[0])
|
||||
s.order = s.order[1:]
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) snapshot(l *Live) Live {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := *l
|
||||
out.Results = slices.Clone(l.Results)
|
||||
return out
|
||||
}
|
||||
|
||||
// Get is a run by its id: one running or finished here, else one kept.
|
||||
func (s *Service) Get(ctx context.Context, id string) (Live, error) {
|
||||
s.mu.Lock()
|
||||
l, ok := s.live[id]
|
||||
s.mu.Unlock()
|
||||
if ok {
|
||||
return s.snapshot(l), nil
|
||||
}
|
||||
if s.deps.Store == nil {
|
||||
return Live{}, store.ErrNotFound
|
||||
}
|
||||
r, err := s.deps.Store.EvalRunByID(ctx, id)
|
||||
if err != nil {
|
||||
return Live{}, err
|
||||
}
|
||||
return Live{EvalRun: r, State: Done, Done: r.Cases}, nil
|
||||
}
|
||||
|
||||
// History is a model's runs, newest first, without their cases: those
|
||||
// running here, then those kept.
|
||||
func (s *Service) History(ctx context.Context, model string, limit int) ([]Live, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
var out []Live
|
||||
seen := map[string]bool{}
|
||||
s.mu.Lock()
|
||||
for i := len(s.order) - 1; i >= 0; i-- {
|
||||
l := s.live[s.order[i]]
|
||||
if l == nil || (model != "" && l.Model != model && l.Target != model) {
|
||||
continue
|
||||
}
|
||||
// Finished ones are listed from the store, when there is one, in
|
||||
// its order.
|
||||
if l.State != Running && s.deps.Store != nil {
|
||||
continue
|
||||
}
|
||||
v := *l
|
||||
v.Results = nil
|
||||
out = append(out, v)
|
||||
seen[l.ID] = true
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if s.deps.Store != nil {
|
||||
runs, err := s.deps.Store.EvalRuns(ctx, model, limit)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for _, r := range runs {
|
||||
if !seen[r.ID] {
|
||||
out = append(out, Live{EvalRun: r, State: Done, Done: r.Cases})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
// Package eval asks a model a suite of questions and scores its answers, so
|
||||
// new weights can be held to the quality of the old before they replace them.
|
||||
//
|
||||
// internal/bench measures how fast a replica answers; this measures whether
|
||||
// the answers are any good. A repository that republishes its weights — a
|
||||
// new quantisation, a fixed chat template — can make a model faster and
|
||||
// worse at once, and nothing in the latency numbers says so. A suite is a
|
||||
// handful of cases with known answers, scored by rules where a rule can
|
||||
// decide (an exact string, a number, JSON of a shape) and by another model
|
||||
// with a rubric where only judgement can.
|
||||
package eval
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"go.yaml.in/yaml/v3"
|
||||
)
|
||||
|
||||
// Suite is a set of cases a model is asked, and the score it must reach.
|
||||
type Suite struct {
|
||||
// Name is what runs are filed under; the file's name without its
|
||||
// extension unless the suite gives one.
|
||||
Name string `json:"name,omitempty" yaml:"name"`
|
||||
Description string `json:"description,omitempty" yaml:"description"`
|
||||
// Threshold is the score, 0 to 1, the suite is passed at. Zero is 0.8.
|
||||
Threshold float64 `json:"threshold,omitempty" yaml:"threshold"`
|
||||
// Judge is the model asked to grade the cases scored by a rubric, unless
|
||||
// a case names its own.
|
||||
Judge string `json:"judge,omitempty" yaml:"judge"`
|
||||
// System and MaxTokens are every case's unless it gives its own.
|
||||
System string `json:"system,omitempty" yaml:"system"`
|
||||
MaxTokens int `json:"max_tokens,omitempty" yaml:"max_tokens"`
|
||||
Cases []Case `json:"cases" yaml:"cases"`
|
||||
|
||||
// Hash is the sha256 of the text the suite was read from: two runs
|
||||
// under one name compare only when they asked the same questions.
|
||||
Hash string `json:"-" yaml:"-"`
|
||||
}
|
||||
|
||||
// Message is one turn of a conversation a case sends.
|
||||
type Message struct {
|
||||
Role string `json:"role" yaml:"role"`
|
||||
Content string `json:"content" yaml:"content"`
|
||||
}
|
||||
|
||||
// Case is one question and how its answer is scored: by exactly one of
|
||||
// Exact, Contains, Regex, Number, JSONSchema or Judge.
|
||||
type Case struct {
|
||||
// ID names the case in results; case-N, by its place, unless given.
|
||||
ID string `json:"id,omitempty" yaml:"id"`
|
||||
// Prompt is the user's message; Messages a whole conversation instead.
|
||||
Prompt string `json:"prompt,omitempty" yaml:"prompt"`
|
||||
Messages []Message `json:"messages,omitempty" yaml:"messages"`
|
||||
System string `json:"system,omitempty" yaml:"system"`
|
||||
// MaxTokens bounds the answer; the suite's, else 512.
|
||||
MaxTokens int `json:"max_tokens,omitempty" yaml:"max_tokens"`
|
||||
// Temperature is 0 unless given: a suite is a measurement, and sampling
|
||||
// would make two runs of the same weights disagree.
|
||||
Temperature *float64 `json:"temperature,omitempty" yaml:"temperature"`
|
||||
// Weight is how much the case counts against the others; 1 unless given.
|
||||
Weight float64 `json:"weight,omitempty" yaml:"weight"`
|
||||
|
||||
// Exact is the whole answer, surrounding white space aside.
|
||||
Exact *string `json:"exact,omitempty" yaml:"exact"`
|
||||
// Contains are strings that must all be in the answer.
|
||||
Contains StringList `json:"contains,omitempty" yaml:"contains"`
|
||||
// Regex must match somewhere in the answer.
|
||||
Regex string `json:"regex,omitempty" yaml:"regex"`
|
||||
// IgnoreCase makes Exact, Contains and Regex blind to case.
|
||||
IgnoreCase bool `json:"ignore_case,omitempty" yaml:"ignore_case"`
|
||||
// Number is the value the last number in the answer must be, within
|
||||
// Tolerance either side.
|
||||
Number *float64 `json:"number,omitempty" yaml:"number"`
|
||||
Tolerance float64 `json:"tolerance,omitempty" yaml:"tolerance"`
|
||||
// JSONSchema is a schema the answer, read as JSON, must satisfy.
|
||||
JSONSchema any `json:"json_schema,omitempty" yaml:"json_schema"`
|
||||
// Judge is a rubric another model grades the answer by, 0 to 1;
|
||||
// JudgeModel names that model, else the suite's judge.
|
||||
Judge string `json:"judge,omitempty" yaml:"judge"`
|
||||
JudgeModel string `json:"judge_model,omitempty" yaml:"judge_model"`
|
||||
|
||||
re *regexp.Regexp
|
||||
schema *schema
|
||||
}
|
||||
|
||||
// StringList is one string or a list of them.
|
||||
type StringList []string
|
||||
|
||||
// UnmarshalYAML takes a string or a list.
|
||||
func (l *StringList) UnmarshalYAML(n *yaml.Node) error {
|
||||
if n.Kind == yaml.ScalarNode {
|
||||
*l = StringList{n.Value}
|
||||
return nil
|
||||
}
|
||||
var v []string
|
||||
if err := n.Decode(&v); err != nil {
|
||||
return err
|
||||
}
|
||||
*l = v
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON takes a string or a list.
|
||||
func (l *StringList) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if json.Unmarshal(b, &s) == nil {
|
||||
*l = StringList{s}
|
||||
return nil
|
||||
}
|
||||
var v []string
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return errors.New("contains is a string or a list of strings")
|
||||
}
|
||||
*l = v
|
||||
return nil
|
||||
}
|
||||
|
||||
// Kind is how a case is scored: exact, contains, regex, number,
|
||||
// json_schema or judge.
|
||||
func (c Case) Kind() string {
|
||||
var kinds []string
|
||||
if c.Exact != nil {
|
||||
kinds = append(kinds, "exact")
|
||||
}
|
||||
if len(c.Contains) > 0 {
|
||||
kinds = append(kinds, "contains")
|
||||
}
|
||||
if c.Regex != "" {
|
||||
kinds = append(kinds, "regex")
|
||||
}
|
||||
if c.Number != nil {
|
||||
kinds = append(kinds, "number")
|
||||
}
|
||||
if c.JSONSchema != nil {
|
||||
kinds = append(kinds, "json_schema")
|
||||
}
|
||||
if c.Judge != "" {
|
||||
kinds = append(kinds, "judge")
|
||||
}
|
||||
return strings.Join(kinds, "+")
|
||||
}
|
||||
|
||||
// DefaultThreshold is the score a suite that names none is passed at.
|
||||
const DefaultThreshold = 0.8
|
||||
|
||||
// defaultMaxTokens bounds an answer when neither the case nor the suite do.
|
||||
const defaultMaxTokens = 512
|
||||
|
||||
// Parse reads a suite: YAML (a mapping with its cases under cases:), or
|
||||
// JSON lines (one case on each, and optionally a line without a prompt or
|
||||
// messages that holds the suite's own settings). The name is the file's,
|
||||
// used when the suite gives none.
|
||||
func Parse(file string, data []byte) (Suite, error) {
|
||||
var s Suite
|
||||
var err error
|
||||
if isJSONLines(data) {
|
||||
s, err = parseJSONLines(data)
|
||||
} else {
|
||||
dec := yaml.NewDecoder(bytes.NewReader(data))
|
||||
dec.KnownFields(true)
|
||||
err = dec.Decode(&s)
|
||||
if errors.Is(err, io.EOF) {
|
||||
err = errors.New("the file is empty")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return Suite{}, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
if s.Name == "" {
|
||||
base := path.Base(strings.ReplaceAll(file, "\\", "/"))
|
||||
s.Name = strings.TrimSuffix(base, path.Ext(base))
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
s.Hash = hex.EncodeToString(sum[:])
|
||||
if err := s.check(); err != nil {
|
||||
return Suite{}, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// isJSONLines is whether every line that is not blank is a JSON object, and
|
||||
// there is more than one, or the one there is is a case rather than a whole
|
||||
// suite.
|
||||
func isJSONLines(data []byte) bool {
|
||||
n := 0
|
||||
for _, line := range bytes.Split(data, []byte("\n")) {
|
||||
line = bytes.TrimSpace(line)
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
if line[0] != '{' || !json.Valid(line) {
|
||||
return false
|
||||
}
|
||||
n++
|
||||
}
|
||||
if n == 1 {
|
||||
var probe struct {
|
||||
Cases json.RawMessage `json:"cases"`
|
||||
}
|
||||
_ = json.Unmarshal(bytes.TrimSpace(data), &probe)
|
||||
return probe.Cases == nil
|
||||
}
|
||||
return n > 0
|
||||
}
|
||||
|
||||
func parseJSONLines(data []byte) (Suite, error) {
|
||||
var s Suite
|
||||
for i, line := range bytes.Split(data, []byte("\n")) {
|
||||
line = bytes.TrimSpace(line)
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var probe struct {
|
||||
Prompt *string `json:"prompt"`
|
||||
Messages json.RawMessage `json:"messages"`
|
||||
}
|
||||
_ = json.Unmarshal(line, &probe)
|
||||
dec := json.NewDecoder(bytes.NewReader(line))
|
||||
dec.DisallowUnknownFields()
|
||||
if probe.Prompt == nil && probe.Messages == nil {
|
||||
cases := s.Cases
|
||||
if err := dec.Decode(&s); err != nil {
|
||||
return Suite{}, fmt.Errorf("line %d: %w", i+1, err)
|
||||
}
|
||||
s.Cases = append(cases, s.Cases...)
|
||||
continue
|
||||
}
|
||||
var c Case
|
||||
if err := dec.Decode(&c); err != nil {
|
||||
return Suite{}, fmt.Errorf("line %d: %w", i+1, err)
|
||||
}
|
||||
s.Cases = append(s.Cases, c)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// check fills in what a suite left out and refuses what cannot be run.
|
||||
func (s *Suite) check() error {
|
||||
if len(s.Cases) == 0 {
|
||||
return errors.New("no cases: a suite has them under cases:, or one on each line of JSON")
|
||||
}
|
||||
if s.Threshold < 0 || s.Threshold > 1 {
|
||||
return fmt.Errorf("threshold %v is not 0 to 1", s.Threshold)
|
||||
}
|
||||
if s.Threshold == 0 {
|
||||
s.Threshold = DefaultThreshold
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i := range s.Cases {
|
||||
c := &s.Cases[i]
|
||||
if c.ID == "" {
|
||||
c.ID = fmt.Sprintf("case-%d", i+1)
|
||||
}
|
||||
if seen[c.ID] {
|
||||
return fmt.Errorf("two cases are called %s", c.ID)
|
||||
}
|
||||
seen[c.ID] = true
|
||||
if err := c.check(); err != nil {
|
||||
return fmt.Errorf("case %s: %w", c.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Case) check() error {
|
||||
if strings.TrimSpace(c.Prompt) == "" && len(c.Messages) == 0 {
|
||||
return errors.New("no prompt and no messages: nothing to ask")
|
||||
}
|
||||
if c.Prompt != "" && len(c.Messages) > 0 {
|
||||
return errors.New("a prompt and messages both: give one")
|
||||
}
|
||||
for _, m := range c.Messages {
|
||||
switch m.Role {
|
||||
case "system", "user", "assistant":
|
||||
default:
|
||||
return fmt.Errorf("a message's role is system, user or assistant, not %q", m.Role)
|
||||
}
|
||||
}
|
||||
switch k := c.Kind(); {
|
||||
case k == "":
|
||||
return errors.New("no way to score it: give one of exact, contains, regex, number, json_schema or judge")
|
||||
case strings.Contains(k, "+"):
|
||||
return fmt.Errorf("scored by %s: give one", strings.ReplaceAll(k, "+", " and "))
|
||||
}
|
||||
if c.Weight < 0 {
|
||||
return fmt.Errorf("weight %v is negative", c.Weight)
|
||||
}
|
||||
if c.Weight == 0 {
|
||||
c.Weight = 1
|
||||
}
|
||||
if c.Tolerance < 0 {
|
||||
return fmt.Errorf("tolerance %v is negative", c.Tolerance)
|
||||
}
|
||||
if c.Regex != "" {
|
||||
expr := c.Regex
|
||||
if c.IgnoreCase {
|
||||
expr = "(?i)" + expr
|
||||
}
|
||||
re, err := regexp.Compile(expr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the regex: %w", err)
|
||||
}
|
||||
c.re = re
|
||||
}
|
||||
if c.JSONSchema != nil {
|
||||
sc, err := compileSchema(c.JSONSchema)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the JSON schema: %w", err)
|
||||
}
|
||||
c.schema = sc
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NeedsJudge is whether any case is graded by a model.
|
||||
func (s Suite) NeedsJudge() bool {
|
||||
for _, c := range s.Cases {
|
||||
if c.Judge != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package bench
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -30,12 +32,16 @@ type sampler struct {
|
||||
running float64
|
||||
kv float64
|
||||
n int
|
||||
// lastErr says why a step has no numbers: averages over no samples are
|
||||
// zeros, and zeros read as an idle engine.
|
||||
lastErr error
|
||||
}
|
||||
|
||||
func newSampler(metricsURL, engine string) *sampler {
|
||||
func newSampler(metricsURL, engine, key string) *sampler {
|
||||
return &sampler{
|
||||
url: metricsURL,
|
||||
engine: engine,
|
||||
apiKey: key,
|
||||
client: &http.Client{Timeout: 2 * time.Second},
|
||||
}
|
||||
}
|
||||
@@ -61,21 +67,41 @@ func (s *sampler) start(ctx context.Context) {
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *sampler) sample(ctx context.Context) {
|
||||
// MetricsRefusedError is an engine refusing to show its metrics without its
|
||||
// key: llama.cpp guards /metrics with it, and llmgw's TensorRT-LLM launcher
|
||||
// guards everything but /health.
|
||||
type MetricsRefusedError struct {
|
||||
URL string
|
||||
Status string
|
||||
KeySent bool
|
||||
}
|
||||
|
||||
func (e *MetricsRefusedError) Error() string {
|
||||
if e.KeySent {
|
||||
return fmt.Sprintf("%s refused the key sent for its metrics (%s)", e.URL, e.Status)
|
||||
}
|
||||
return fmt.Sprintf("%s guards its metrics with the engine's key, and none was given (%s)", e.URL, e.Status)
|
||||
}
|
||||
|
||||
// read takes one sample.
|
||||
func (s *sampler) read(ctx context.Context) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.url, nil)
|
||||
if err != nil {
|
||||
return
|
||||
return err
|
||||
}
|
||||
if s.apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+s.apiKey)
|
||||
}
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
|
||||
return &MetricsRefusedError{URL: s.url, Status: resp.Status, KeySent: s.apiKey != ""}
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
return fmt.Errorf("%s: %s", s.url, resp.Status)
|
||||
}
|
||||
|
||||
// The same mapping the router reads with, so a bench result cannot disagree
|
||||
@@ -84,7 +110,11 @@ func (s *sampler) sample(ctx context.Context) {
|
||||
// report a queue depth of zero and suggest thresholds built on it.
|
||||
stats, err := scrape.Parse(resp.Body, scrape.MappingFor(s.engine))
|
||||
if err != nil {
|
||||
return
|
||||
var missing *scrape.MissingError
|
||||
if errors.As(err, &missing) {
|
||||
return fmt.Errorf("%s does not serve %v: is %q the engine there?", s.url, missing.Missing, s.engine)
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.waiting += float64(stats.Waiting)
|
||||
@@ -92,6 +122,17 @@ func (s *sampler) sample(ctx context.Context) {
|
||||
s.kv += stats.KVCacheUsage
|
||||
s.n++
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sampler) sample(ctx context.Context) {
|
||||
err := s.read(ctx)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.lastErr = err
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *sampler) stop() {
|
||||
@@ -110,3 +151,14 @@ func (s *sampler) averages() (waiting, running, kv float64) {
|
||||
n := float64(s.n)
|
||||
return s.waiting / n, s.running / n, s.kv / n
|
||||
}
|
||||
|
||||
// unread says why a step that tried to read the metrics has none of them, or
|
||||
// "" when it has some or never tried.
|
||||
func (s *sampler) unread() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.n > 0 || s.lastErr == nil {
|
||||
return ""
|
||||
}
|
||||
return s.lastErr.Error()
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package bench
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// llamaMetrics is the part of llama-server's /metrics the router reads.
|
||||
const llamaMetrics = `# TYPE llamacpp:requests_processing gauge
|
||||
llamacpp:requests_processing 1
|
||||
# TYPE llamacpp:requests_deferred gauge
|
||||
llamacpp:requests_deferred 2
|
||||
`
|
||||
|
||||
// guardedEngine is a llama.cpp-like engine: it streams completions to
|
||||
// clientKey and serves /metrics only to engineKey, as llama-server does with
|
||||
// --api-key. refuseAfter, when set, makes /metrics refuse every read after
|
||||
// that many.
|
||||
type guardedEngine struct {
|
||||
clientKey, engineKey string
|
||||
refuseAfter int64
|
||||
chats, reads atomic.Int64
|
||||
}
|
||||
|
||||
func (g *guardedEngine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/metrics":
|
||||
n := g.reads.Add(1)
|
||||
if r.Header.Get("Authorization") != "Bearer "+g.engineKey || (g.refuseAfter > 0 && n > g.refuseAfter) {
|
||||
http.Error(w, `{"error":"Invalid API Key"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(llamaMetrics))
|
||||
case "/v1/chat/completions":
|
||||
if r.Header.Get("Authorization") != "Bearer "+g.clientKey {
|
||||
http.Error(w, "no", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
g.chats.Add(1)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for i := range 3 {
|
||||
fmt.Fprintf(w, "data: {\"choices\":[{\"delta\":{\"content\":\"t%d\"}}]}\n\n", i)
|
||||
}
|
||||
fmt.Fprint(w, "data: [DONE]\n\n")
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func guardedRun(t *testing.T, g *guardedEngine, metricsKey string) (Result, error) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(g)
|
||||
t.Cleanup(srv.Close)
|
||||
return Run(context.Background(), Config{
|
||||
Target: srv.URL, APIKey: g.clientKey, Model: "m",
|
||||
MetricsURL: srv.URL + "/metrics", Engine: "llamacpp", MetricsKey: metricsKey,
|
||||
Concurrency: []int{1}, Duration: 1500 * time.Millisecond,
|
||||
SLO: SLO{TTFTp99: time.Minute},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
func TestAnEngineThatGuardsItsMetricsIsReadWithItsOwnKey(t *testing.T) {
|
||||
// The requests go with the client's key and the metrics with the
|
||||
// engine's: llama.cpp's /metrics takes only its own.
|
||||
g := &guardedEngine{clientKey: "client", engineKey: "engine"}
|
||||
res, err := guardedRun(t, g, "engine")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := res.Steps[0]
|
||||
if s.MetricsUnread != "" || s.Waiting != 2 || s.Running != 1 {
|
||||
t.Errorf("metrics not read: waiting=%v running=%v unread=%q", s.Waiting, s.Running, s.MetricsUnread)
|
||||
}
|
||||
if res.SuggestedTargetWaiting != 2 {
|
||||
t.Errorf("target_waiting suggested %d", res.SuggestedTargetWaiting)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsThatRefuseTheRunStopItBeforeAnyLoad(t *testing.T) {
|
||||
// Without the engine's key every sample is refused, and the run used to
|
||||
// report a queue depth of zero as though the engine had been idle.
|
||||
g := &guardedEngine{clientKey: "client", engineKey: "engine"}
|
||||
_, err := guardedRun(t, g, "")
|
||||
var refused *MetricsRefusedError
|
||||
if !errors.As(err, &refused) || refused.KeySent {
|
||||
t.Fatalf("expected the metrics refused for want of a key, got %v", err)
|
||||
}
|
||||
if n := g.chats.Load(); n != 0 {
|
||||
t.Errorf("%d requests were sent before the metrics were found unreadable", n)
|
||||
}
|
||||
|
||||
_, err = guardedRun(t, &guardedEngine{clientKey: "client", engineKey: "engine"}, "client")
|
||||
if !errors.As(err, &refused) || !refused.KeySent {
|
||||
t.Fatalf("expected the key sent reported refused, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStepWhoseMetricsWereNotReadSaysSo(t *testing.T) {
|
||||
// Readable before the ramp and not during it — an engine restarted with
|
||||
// another key, say. The step's zeros are not an idle engine.
|
||||
g := &guardedEngine{clientKey: "client", engineKey: "engine", refuseAfter: 1}
|
||||
res, err := guardedRun(t, g, "engine")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := res.Steps[0]; s.MetricsUnread == "" {
|
||||
t.Errorf("a step with no metrics read reported none missing: %+v", s)
|
||||
}
|
||||
if res.SuggestedTargetWaiting != 0 || res.SuggestedKVCeiling != 0 {
|
||||
t.Errorf("thresholds suggested from metrics never read: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsInAnotherEnginesNamesStopTheRun(t *testing.T) {
|
||||
g := &guardedEngine{clientKey: "client", engineKey: "engine"}
|
||||
srv := httptest.NewServer(g)
|
||||
defer srv.Close()
|
||||
_, err := Run(context.Background(), Config{
|
||||
Target: srv.URL, APIKey: "client", Model: "m",
|
||||
MetricsURL: srv.URL + "/metrics", Engine: "vllm", MetricsKey: "engine",
|
||||
Concurrency: []int{1}, Duration: time.Second,
|
||||
}, nil)
|
||||
if err == nil || g.chats.Load() != 0 {
|
||||
t.Fatalf("a run reading llama.cpp's metrics with vLLM's names started: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// Package bundle carries what a cluster would otherwise fetch from the
|
||||
// internet to a site that has no way to it.
|
||||
//
|
||||
// A bundle is made on a machine with internet access: llmgw's own release
|
||||
// binaries with their signed checksums, the engine builds the nodes install
|
||||
// with the checksums their publisher gave, and model files with the
|
||||
// checksums their registry gave — each checked as it arrives, exactly as a
|
||||
// node online would check it. Its manifest lists every file with its sha256,
|
||||
// and the manifest's own sha256 is what the person carrying the bundle
|
||||
// compares at the other end.
|
||||
//
|
||||
// Imported, the files go into the cluster's mirror: releases and engines
|
||||
// under _llmgw/, which no model can be called, models where the mirror keeps
|
||||
// models. The engines' checksums go to the control plane, which tells each
|
||||
// node what every file it fetches from the mirror must be. The mirror serves
|
||||
// plain HTTP to every node, so nothing a node runs is taken on the mirror's
|
||||
// word: releases carry the project's signature, engines the checksum the
|
||||
// control plane holds.
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/mirror"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/release"
|
||||
)
|
||||
|
||||
// ManifestName is the manifest's file name in a bundle, and the first entry
|
||||
// of a bundle packed as a tar.
|
||||
const ManifestName = "manifest.json"
|
||||
|
||||
// Format is the manifest's layout version. A bundle of a later format is
|
||||
// refused rather than half understood.
|
||||
const Format = 1
|
||||
|
||||
// Prefix is where a mirror keeps what is not a model: _llmgw/releases and
|
||||
// _llmgw/engines. A model name may not start with an underscore here, so
|
||||
// none can be called this.
|
||||
const Prefix = "_llmgw"
|
||||
|
||||
// Manifest says what a bundle holds.
|
||||
type Manifest struct {
|
||||
Format int `json:"format"`
|
||||
Created time.Time `json:"created"`
|
||||
// MadeBy is the llmgw version that made it.
|
||||
MadeBy string `json:"made_by"`
|
||||
Releases []Release `json:"releases,omitempty"`
|
||||
Engines []Engine `json:"engines,omitempty"`
|
||||
Models []Model `json:"models,omitempty"`
|
||||
// Files are every file in the bundle but the manifest, with their
|
||||
// checksums: what an import checks each one against.
|
||||
Files []File `json:"files"`
|
||||
}
|
||||
|
||||
// Release is llmgw's own release, for some architectures.
|
||||
type Release struct {
|
||||
Version string `json:"version"`
|
||||
Arches []string `json:"arches"`
|
||||
}
|
||||
|
||||
// Engine is an engine version's builds, for some architectures.
|
||||
type Engine struct {
|
||||
Engine string `json:"engine"`
|
||||
Version string `json:"version"`
|
||||
Arches []string `json:"arches"`
|
||||
Variants []string `json:"variants"`
|
||||
}
|
||||
|
||||
// Model is a model's files, as the mirror will hold them.
|
||||
type Model struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
// Source is what it was asked for as: hf:owner/repo/file, or a URL.
|
||||
Source string `json:"source"`
|
||||
// Revision is the registry's commit it was taken at, when it has one.
|
||||
Revision string `json:"revision,omitempty"`
|
||||
}
|
||||
|
||||
// File is one file of a bundle.
|
||||
type File struct {
|
||||
// Path is where it is in the bundle: releases/<version>/<file>,
|
||||
// engines/<engine>/<version>/<file> or models/<model>/<version>/<file>.
|
||||
Path string `json:"path"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
// Source is where it was downloaded from.
|
||||
Source string `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// Kinds of file, by the first element of their path.
|
||||
const (
|
||||
kindRelease = "releases"
|
||||
kindEngine = "engines"
|
||||
kindModel = "models"
|
||||
)
|
||||
|
||||
// Digest is a manifest's sha256: what `bundle create` prints and an import
|
||||
// is given to check the bundle by.
|
||||
func Digest(raw []byte) string {
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// parseManifest reads a manifest and checks every path in it, before any
|
||||
// file is read: a path is where the file is written.
|
||||
func parseManifest(raw []byte) (Manifest, error) {
|
||||
var m Manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return Manifest{}, fmt.Errorf("the bundle's manifest cannot be read: %w", err)
|
||||
}
|
||||
if m.Format != Format {
|
||||
return Manifest{}, fmt.Errorf("the bundle is of format %d and this llmgw reads format %d: "+
|
||||
"import it with the llmgw that made it", m.Format, Format)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, f := range m.Files {
|
||||
if _, err := Destination(f.Path); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
if len(f.SHA256) != 64 {
|
||||
return Manifest{}, fmt.Errorf("the manifest gives %s no sha256", f.Path)
|
||||
}
|
||||
if _, err := hex.DecodeString(f.SHA256); err != nil {
|
||||
return Manifest{}, fmt.Errorf("the manifest's sha256 of %s is not one", f.Path)
|
||||
}
|
||||
if seen[f.Path] {
|
||||
return Manifest{}, fmt.Errorf("the manifest lists %s twice", f.Path)
|
||||
}
|
||||
seen[f.Path] = true
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Destination is where a bundle's file goes in a mirror, relative to its
|
||||
// root, or why it goes nowhere.
|
||||
//
|
||||
// Every path in a bundle has a fixed shape — three or four plain elements
|
||||
// under one of three directories — because a path is where the import
|
||||
// writes, as root. Anything else is refused, not cleaned.
|
||||
func Destination(p string) (string, error) {
|
||||
parts := strings.Split(p, "/")
|
||||
bad := func(why string) (string, error) {
|
||||
return "", fmt.Errorf("the bundle names a file %q, which %s", p, why)
|
||||
}
|
||||
if path.Clean(p) != p || strings.HasPrefix(p, "/") {
|
||||
return bad("is not a plain path")
|
||||
}
|
||||
for _, e := range parts {
|
||||
if err := mirror.ValidName(e); err != nil {
|
||||
return bad("has an element that is not a plain name")
|
||||
}
|
||||
}
|
||||
switch parts[0] {
|
||||
case kindRelease:
|
||||
if len(parts) != 3 || !release.Tag.MatchString(parts[1]) {
|
||||
return bad("is not releases/<version>/<file>")
|
||||
}
|
||||
return Prefix + "/" + p, nil
|
||||
case kindEngine:
|
||||
if len(parts) != 4 {
|
||||
return bad("is not engines/<engine>/<version>/<file>")
|
||||
}
|
||||
return Prefix + "/" + p, nil
|
||||
case kindModel:
|
||||
if len(parts) != 4 {
|
||||
return bad("is not models/<model>/<version>/<file>")
|
||||
}
|
||||
if strings.HasPrefix(parts[1], "_") {
|
||||
return bad("names a model starting with an underscore, which the mirror keeps for itself")
|
||||
}
|
||||
return strings.Join(parts[1:], "/"), nil
|
||||
}
|
||||
return bad("is not under releases/, engines/ or models/")
|
||||
}
|
||||
|
||||
// EngineBase is where an engine version's files are on a mirror whose files
|
||||
// are served at mirrorURL.
|
||||
func EngineBase(mirrorURL, engine, version string) string {
|
||||
return strings.TrimSuffix(mirrorURL, "/") + "/" + Prefix + "/" + kindEngine + "/" + engine + "/" + version
|
||||
}
|
||||
|
||||
// ReleasesBase is where llmgw's releases are on a mirror whose files are
|
||||
// served at mirrorURL: what `releases` is on an offline cluster.
|
||||
func ReleasesBase(mirrorURL string) string {
|
||||
return strings.TrimSuffix(mirrorURL, "/") + "/" + Prefix + "/" + kindRelease
|
||||
}
|
||||
|
||||
// ErrNoDigest is an import or trust given no sha256 to check the bundle by.
|
||||
var ErrNoDigest = errors.New("give the bundle's sha256, as 'llmgw bundle create' printed it, " +
|
||||
"so what was carried is known to be what was made; or say it is to be taken unchecked")
|
||||
|
||||
// checkDigest compares a manifest with the digest it was given. Unchecked
|
||||
// takes it as it is, said by the caller.
|
||||
func checkDigest(raw []byte, want string, unchecked bool) error {
|
||||
want = strings.ToLower(strings.TrimSpace(want))
|
||||
switch {
|
||||
case want == "" && unchecked:
|
||||
return nil
|
||||
case want == "":
|
||||
return ErrNoDigest
|
||||
case Digest(raw) != want:
|
||||
return fmt.Errorf("the bundle's manifest is %s, not the %s it was given as: "+
|
||||
"it is not the bundle that was made, or the digest was mistyped", Digest(raw)[:16], want)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/provision"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/mirror"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/release"
|
||||
)
|
||||
|
||||
func hexSum(b []byte) string {
|
||||
s := sha256.Sum256(b)
|
||||
return hex.EncodeToString(s[:])
|
||||
}
|
||||
|
||||
// internet is everything a bundle is made from: a release server, GitHub
|
||||
// and Hugging Face, all fakes.
|
||||
type internet struct {
|
||||
srv *httptest.Server
|
||||
files map[string][]byte
|
||||
digests map[string]string // GitHub's, by asset
|
||||
priv string
|
||||
weights []byte
|
||||
hfDigest string
|
||||
}
|
||||
|
||||
func newInternet(t *testing.T) *internet {
|
||||
t.Helper()
|
||||
pub, priv, err := release.GenerateKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("LLMGW_RELEASE_KEY", pub)
|
||||
in := &internet{files: map[string][]byte{}, digests: map[string]string{}, priv: priv}
|
||||
|
||||
// llmgw v1.2.3 for both architectures, signed.
|
||||
var sums strings.Builder
|
||||
for _, arch := range []string{"amd64", "arm64"} {
|
||||
name := release.AssetName("v1.2.3", "linux", arch)
|
||||
body := []byte("llmgw for " + arch)
|
||||
in.files["/releases/v1.2.3/"+name] = body
|
||||
sums.WriteString(hexSum(body) + " " + name + "\n")
|
||||
}
|
||||
in.files["/releases/v1.2.3/checksums.txt"] = []byte(sums.String())
|
||||
sig, _ := release.Sign(priv, []byte(sums.String()))
|
||||
in.files["/releases/v1.2.3/"+release.SignatureName] = []byte(sig)
|
||||
|
||||
// llama.cpp b1: every build there is for amd64.
|
||||
builds, err := provision.Builds("llamacpp", "b1", "amd64")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range builds {
|
||||
for _, a := range b.Assets {
|
||||
body := []byte("archive " + a)
|
||||
in.files["/gh/ggml-org/llama.cpp/releases/download/b1/"+a] = body
|
||||
in.digests[a] = "sha256:" + hexSum(body)
|
||||
}
|
||||
}
|
||||
|
||||
// A model on Hugging Face, with the checksum the registry publishes.
|
||||
in.weights = []byte("GGUF weights")
|
||||
in.hfDigest = hexSum(in.weights)
|
||||
in.files["/Org/Model-GGUF/resolve/abc123/model-q4.gguf"] = in.weights
|
||||
|
||||
in.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/api/repos/ggml-org/llama.cpp/releases/tags/b1"):
|
||||
var out struct {
|
||||
Assets []map[string]string `json:"assets"`
|
||||
}
|
||||
for name, d := range in.digests {
|
||||
out.Assets = append(out.Assets, map[string]string{"name": name, "digest": d})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
case r.URL.Path == "/api/models/Org/Model-GGUF":
|
||||
_, _ = w.Write([]byte(`{"id":"Org/Model-GGUF","sha":"abc123"}`))
|
||||
case r.URL.Path == "/api/models/Org/Model-GGUF/tree/abc123":
|
||||
_ = json.NewEncoder(w).Encode([]map[string]any{
|
||||
{"type": "file", "path": "model-q4.gguf", "size": 133,
|
||||
"lfs": map[string]any{"oid": in.hfDigest, "size": len(in.weights)}},
|
||||
})
|
||||
default:
|
||||
b, ok := in.files[r.URL.Path]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(b)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(in.srv.Close)
|
||||
return in
|
||||
}
|
||||
|
||||
func (in *internet) options(out string) CreateOptions {
|
||||
return CreateOptions{
|
||||
Out: out, Release: "v1.2.3", Arches: []string{"amd64"},
|
||||
Releases: in.srv.URL + "/releases",
|
||||
Engines: []EngineSpec{{Engine: "llamacpp", Version: "b1", Variants: []string{"cpu", "cuda-12.8"}}},
|
||||
Models: []ModelSpec{{Name: "starter", Version: "2026-10", Source: "hf:Org/Model-GGUF/model-q4.gguf"}},
|
||||
HTTP: in.srv.Client(),
|
||||
GitHubAPI: in.srv.URL + "/api", GitHubDownload: in.srv.URL + "/gh", Registry: in.srv.URL,
|
||||
}
|
||||
}
|
||||
|
||||
func TestABundleCarriesWhatTheClusterWouldFetchAndAMirrorTakesItChecked(t *testing.T) {
|
||||
in := newInternet(t)
|
||||
out := filepath.Join(t.TempDir(), "bundle")
|
||||
m, digest, err := Create(t.Context(), in.options(out))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var paths []string
|
||||
for _, f := range m.Files {
|
||||
paths = append(paths, f.Path)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"releases/v1.2.3/checksums.txt", "releases/v1.2.3/" + release.SignatureName,
|
||||
"releases/v1.2.3/llmgw-v1.2.3-linux-amd64",
|
||||
"engines/llamacpp/b1/llama-b1-bin-ubuntu-x64.tar.gz",
|
||||
"engines/llamacpp/b1/llama-b1-bin-ubuntu-cuda-12.8-x64.tar.gz",
|
||||
"engines/llamacpp/b1/cudart-llama-b1-bin-ubuntu-cuda-12.8-x64.tar.gz",
|
||||
"models/starter/2026-10/model-q4.gguf",
|
||||
} {
|
||||
if !strings.Contains(strings.Join(paths, "\n"), want) {
|
||||
t.Errorf("the bundle lacks %s:\n%s", want, strings.Join(paths, "\n"))
|
||||
}
|
||||
}
|
||||
if strings.Contains(strings.Join(paths, "\n"), "vulkan") {
|
||||
t.Error("a build not asked for was carried")
|
||||
}
|
||||
|
||||
// Carried as one file, and imported from it as from the directory.
|
||||
tarball := out + ".tar"
|
||||
if err := Pack(out, tarball); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, from := range []string{tarball, out} {
|
||||
root := t.TempDir()
|
||||
res, err := Import(from, ImportOptions{Mirror: root, SHA256: digest})
|
||||
if err != nil {
|
||||
t.Fatalf("importing %s: %v", filepath.Base(from), err)
|
||||
}
|
||||
if res.Written != len(m.Files) || res.Digest != digest {
|
||||
t.Errorf("wrote %d of %d files", res.Written, len(m.Files))
|
||||
}
|
||||
bin, _ := os.ReadFile(filepath.Join(root, "_llmgw/releases/v1.2.3/llmgw-v1.2.3-linux-amd64"))
|
||||
if string(bin) != "llmgw for amd64" {
|
||||
t.Errorf("the release is not where releases are fetched from: %q", bin)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "_llmgw/engines/llamacpp/b1/llama-b1-bin-ubuntu-x64.tar.gz")); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// The model is the mirror's like any other, with its checksum.
|
||||
man, err := mirror.ManifestFor(root, "starter", "2026-10")
|
||||
if err != nil || len(man.Files) != 1 || man.Files[0].SHA256 != in.hfDigest {
|
||||
t.Errorf("the model is not offered with its checksum: %+v %v", man, err)
|
||||
}
|
||||
// And the mirror lists nothing of llmgw's own as a model.
|
||||
entries, _ := mirror.List(root)
|
||||
if len(entries) != 1 {
|
||||
t.Errorf("the mirror lists %v", entries)
|
||||
}
|
||||
|
||||
// Again: everything is there and the same, so nothing is written.
|
||||
res, err = Import(from, ImportOptions{Mirror: root, SHA256: digest})
|
||||
if err != nil || res.Written != 0 || res.Kept != len(m.Files) {
|
||||
t.Errorf("a second import: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Made again into the same directory, a file already there and right is
|
||||
// not downloaded: only the checksums are asked for again.
|
||||
for p := range in.files {
|
||||
if !strings.HasSuffix(p, "checksums.txt") && !strings.HasSuffix(p, release.SignatureName) {
|
||||
delete(in.files, p)
|
||||
}
|
||||
}
|
||||
_, again, err := Create(t.Context(), in.options(out))
|
||||
if err != nil {
|
||||
t.Fatalf("made again from what was there: %v", err)
|
||||
}
|
||||
var m2 Manifest
|
||||
raw, _ := os.ReadFile(filepath.Join(out, ManifestName))
|
||||
_ = json.Unmarshal(raw, &m2)
|
||||
if again != Digest(raw) || len(m2.Files) != len(m.Files) {
|
||||
t.Errorf("made again: %d files, digest %s", len(m2.Files), again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheControlPlaneTrustsTheBundlesEngineChecksumsAndNodesAreToldThem(t *testing.T) {
|
||||
in := newInternet(t)
|
||||
out := filepath.Join(t.TempDir(), "bundle")
|
||||
_, digest, err := Create(t.Context(), in.options(out))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "offline.sha256")
|
||||
if _, _, err := Trust(out, file, "", false); err == nil {
|
||||
t.Fatal("a bundle was trusted with no digest to check it by")
|
||||
}
|
||||
if _, _, err := Trust(out, file, strings.Repeat("0", 64), false); err == nil {
|
||||
t.Fatal("a bundle was trusted against the wrong digest")
|
||||
}
|
||||
if _, n, err := Trust(out, file, digest, false); err != nil || n != 3 {
|
||||
t.Fatalf("trusted %d: %v", n, err)
|
||||
}
|
||||
|
||||
tr := NewTrusted(file)
|
||||
got := tr.For("llamacpp", "b1")
|
||||
if got["llama-b1-bin-ubuntu-x64.tar.gz"] != strings.TrimPrefix(in.digests["llama-b1-bin-ubuntu-x64.tar.gz"], "sha256:") {
|
||||
t.Errorf("the control plane holds %v", got)
|
||||
}
|
||||
if len(tr.For("llamacpp", "b2")) != 0 {
|
||||
t.Error("checksums were given for a version no bundle carried")
|
||||
}
|
||||
|
||||
// A second bundle adds to what is trusted, and the control plane sees
|
||||
// it without a restart.
|
||||
m2 := Manifest{Format: Format, Files: []File{{Path: "engines/llamacpp/b2/llama-b2-bin-ubuntu-x64.tar.gz", Bytes: 1, SHA256: strings.Repeat("b", 64)}}}
|
||||
if n, err := TrustManifest(m2, file); err != nil || n != 4 {
|
||||
t.Fatalf("trusted %d: %v", n, err)
|
||||
}
|
||||
if tr.For("llamacpp", "b2")["llama-b2-bin-ubuntu-x64.tar.gz"] != strings.Repeat("b", 64) {
|
||||
t.Error("a bundle trusted while running was not seen")
|
||||
}
|
||||
if len(tr.For("llamacpp", "b1")) != 3 {
|
||||
t.Error("the first bundle's checksums were lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestADamagedBundlePutsNothingInTheMirror(t *testing.T) {
|
||||
in := newInternet(t)
|
||||
out := filepath.Join(t.TempDir(), "bundle")
|
||||
_, digest, err := Create(t.Context(), in.options(out))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The wrong digest, and none at all, are refused before anything is read.
|
||||
root := t.TempDir()
|
||||
if _, err := Import(out, ImportOptions{Mirror: root, SHA256: strings.Repeat("0", 64)}); err == nil {
|
||||
t.Error("a bundle not matching its digest was imported")
|
||||
}
|
||||
if _, err := Import(out, ImportOptions{Mirror: root}); err == nil {
|
||||
t.Error("a bundle was imported with no digest")
|
||||
}
|
||||
if _, err := Import(out, ImportOptions{Mirror: root, Unchecked: true}); err != nil {
|
||||
t.Errorf("a bundle taken unchecked, as asked: %v", err)
|
||||
}
|
||||
|
||||
// An engine changed on the way.
|
||||
engine := filepath.Join(out, "engines/llamacpp/b1/llama-b1-bin-ubuntu-x64.tar.gz")
|
||||
good, _ := os.ReadFile(engine)
|
||||
_ = os.WriteFile(engine, []byte("swapped"), 0o644)
|
||||
root = t.TempDir()
|
||||
if _, err := Import(out, ImportOptions{Mirror: root, SHA256: digest}); err == nil || !strings.Contains(err.Error(), "damaged") {
|
||||
t.Errorf("a changed engine: %v", err)
|
||||
}
|
||||
if entries := walk(t, root); len(entries) > 0 {
|
||||
t.Errorf("a damaged bundle left %v in the mirror", entries)
|
||||
}
|
||||
_ = os.WriteFile(engine, good, 0o644)
|
||||
|
||||
// A release whose checksums the project did not sign, with a manifest
|
||||
// made to agree: what the manifest says is not enough for a binary.
|
||||
_, other, _ := release.GenerateKey()
|
||||
sums, _ := os.ReadFile(filepath.Join(out, "releases/v1.2.3/checksums.txt"))
|
||||
forged, _ := release.Sign(other, sums)
|
||||
_ = os.WriteFile(filepath.Join(out, "releases/v1.2.3/"+release.SignatureName), []byte(forged), 0o644)
|
||||
raw := remanifest(t, out)
|
||||
root = t.TempDir()
|
||||
if _, err := Import(out, ImportOptions{Mirror: root, SHA256: Digest(raw)}); err == nil || !strings.Contains(err.Error(), "not signed") {
|
||||
t.Errorf("a release not signed by the project: %v", err)
|
||||
}
|
||||
if entries := walk(t, root); len(entries) > 0 {
|
||||
t.Errorf("an unsigned release left %v in the mirror", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAVersionAlreadyInTheMirrorIsNeverReplaced(t *testing.T) {
|
||||
in := newInternet(t)
|
||||
out := filepath.Join(t.TempDir(), "bundle")
|
||||
_, digest, err := Create(t.Context(), in.options(out))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
_ = os.MkdirAll(filepath.Join(root, "starter", "2026-10"), 0o755)
|
||||
_ = os.WriteFile(filepath.Join(root, "starter", "2026-10", "model-q4.gguf"), []byte("other weights"), 0o644)
|
||||
if _, err := Import(out, ImportOptions{Mirror: root, SHA256: digest}); err == nil || !strings.Contains(err.Error(), "never replaced") {
|
||||
t.Fatalf("a different file under the same version: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(root, "starter", "2026-10", "model-q4.gguf")); string(b) != "other weights" {
|
||||
t.Error("the mirror's file was replaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestABundleCannotWriteOutsideTheMirror(t *testing.T) {
|
||||
for _, p := range []string{
|
||||
"../etc/cron.d/x", "models/../../x/y/z", "models/a/b/../c", "/abs/olute/path/x",
|
||||
"engines/llamacpp/b1", "releases/latest/llmgw", "models/_llmgw/releases/x",
|
||||
"models/.hidden/v/f", "other/a/b/c",
|
||||
} {
|
||||
if _, err := Destination(p); err == nil {
|
||||
t.Errorf("%q was given a destination", p)
|
||||
}
|
||||
}
|
||||
if d, err := Destination("models/m/v/f.gguf"); err != nil || d != "m/v/f.gguf" {
|
||||
t.Errorf("a model: %q %v", d, err)
|
||||
}
|
||||
|
||||
// A tar carrying a file its manifest does not list is refused.
|
||||
dir := t.TempDir()
|
||||
raw, _ := json.Marshal(Manifest{Format: Format, Files: []File{}})
|
||||
tarball := filepath.Join(dir, "b.tar")
|
||||
f, _ := os.Create(tarball)
|
||||
tw := tar.NewWriter(f)
|
||||
_ = tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o644, Size: int64(len(raw)), Typeflag: tar.TypeReg})
|
||||
_, _ = tw.Write(raw)
|
||||
_ = tw.WriteHeader(&tar.Header{Name: "models/m/v/extra", Mode: 0o644, Size: 1, Typeflag: tar.TypeReg})
|
||||
_, _ = tw.Write([]byte("x"))
|
||||
_ = tw.Close()
|
||||
_ = f.Close()
|
||||
if _, err := Import(tarball, ImportOptions{Mirror: t.TempDir(), SHA256: Digest(raw)}); err == nil {
|
||||
t.Error("a file the manifest does not list was imported")
|
||||
}
|
||||
}
|
||||
|
||||
// remanifest rewrites a bundle's manifest to agree with its files, as
|
||||
// someone changing a bundle on the way would.
|
||||
func remanifest(t *testing.T, dir string) []byte {
|
||||
t.Helper()
|
||||
raw, _ := os.ReadFile(filepath.Join(dir, ManifestName))
|
||||
var m Manifest
|
||||
_ = json.Unmarshal(raw, &m)
|
||||
for i, f := range m.Files {
|
||||
b, _ := os.ReadFile(filepath.Join(dir, f.Path))
|
||||
m.Files[i].SHA256, m.Files[i].Bytes = hexSum(b), int64(len(b))
|
||||
}
|
||||
raw, _ = json.MarshalIndent(m, "", " ")
|
||||
_ = os.WriteFile(filepath.Join(dir, ManifestName), raw, 0o644)
|
||||
return raw
|
||||
}
|
||||
|
||||
func walk(t *testing.T, root string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
_ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
||||
if err == nil && !info.IsDir() {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !unix
|
||||
|
||||
package bundle
|
||||
|
||||
// chownLike does nothing where files have no Unix owner.
|
||||
func chownLike(string, string) {}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build unix
|
||||
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// chownLike gives p the owner of root, when this runs as root: the mirror
|
||||
// runs as its own user, and a version it cannot remove is one `mirror
|
||||
// remove` and the admin page fail on.
|
||||
func chownLike(root, p string) {
|
||||
if os.Geteuid() != 0 {
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(root)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
st, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
_ = os.Lchown(p, int(st.Uid), int(st.Gid))
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/provision"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/hf"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/mirror"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/release"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/version"
|
||||
)
|
||||
|
||||
// EngineSpec is an engine version to carry, and which of its builds.
|
||||
type EngineSpec struct {
|
||||
Engine, Version string
|
||||
// Variants are the builds to carry ("cpu", "cuda-13.3"); empty is every
|
||||
// one, which is what a site whose nodes are not all known wants.
|
||||
Variants []string
|
||||
}
|
||||
|
||||
// ModelSpec is a model file to carry, and where the mirror will hold it.
|
||||
type ModelSpec struct {
|
||||
Name, Version string
|
||||
// Source is hf:owner/repo/path/in/repo, or an http(s) URL.
|
||||
Source string
|
||||
}
|
||||
|
||||
// CreateOptions say what goes into a bundle.
|
||||
type CreateOptions struct {
|
||||
// Out is the directory the bundle is made in. A bundle made there
|
||||
// before is added to: a file already there with the right checksum is
|
||||
// not downloaded again.
|
||||
Out string
|
||||
// Release is llmgw's release to carry, v0.10.4; empty carries none.
|
||||
Release string
|
||||
// Arches are the architectures, of the releases and of the engines:
|
||||
// amd64, arm64.
|
||||
Arches []string
|
||||
// Releases is where release files are published.
|
||||
Releases string
|
||||
Engines []EngineSpec
|
||||
Models []ModelSpec
|
||||
|
||||
// HTTP fetches everything; nil is a client with no overall timeout,
|
||||
// because a model file is tens of gigabytes.
|
||||
HTTP *http.Client
|
||||
// GitHubAPI, GitHubDownload and Registry default to GitHub and Hugging
|
||||
// Face; tests point them at fakes.
|
||||
GitHubAPI, GitHubDownload, Registry string
|
||||
// Log hears what is happening, a line at a time.
|
||||
Log func(format string, args ...any)
|
||||
}
|
||||
|
||||
// Create downloads everything a bundle is asked to carry, checking each
|
||||
// file as a node online would, and writes its manifest. It returns the
|
||||
// manifest and its digest: the value to carry to the site separately and
|
||||
// give to the import.
|
||||
func Create(ctx context.Context, o CreateOptions) (Manifest, string, error) {
|
||||
c := &creator{o: o, client: o.HTTP}
|
||||
if c.client == nil {
|
||||
c.client = &http.Client{}
|
||||
}
|
||||
if len(o.Arches) == 0 {
|
||||
return Manifest{}, "", errors.New("give at least one architecture: amd64, arm64")
|
||||
}
|
||||
for _, a := range o.Arches {
|
||||
if a != "amd64" && a != "arm64" {
|
||||
return Manifest{}, "", fmt.Errorf("%q is not an architecture llmgw is built for: amd64 or arm64", a)
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(o.Out, 0o755); err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
c.m = Manifest{Format: Format, Created: time.Now().UTC().Truncate(time.Second), MadeBy: version.Version}
|
||||
|
||||
if o.Release != "" {
|
||||
if err := c.release(ctx); err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
}
|
||||
for _, e := range o.Engines {
|
||||
if err := c.engine(ctx, e); err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
}
|
||||
for _, m := range o.Models {
|
||||
if err := c.model(ctx, m); err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
}
|
||||
raw, err := json.MarshalIndent(c.m, "", " ")
|
||||
if err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
raw = append(raw, '\n')
|
||||
if err := os.WriteFile(filepath.Join(o.Out, ManifestName), raw, 0o644); err != nil { //nolint:gosec // a list of checksums
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
return c.m, Digest(raw), nil
|
||||
}
|
||||
|
||||
type creator struct {
|
||||
o CreateOptions
|
||||
client *http.Client
|
||||
m Manifest
|
||||
}
|
||||
|
||||
func (c *creator) log(format string, args ...any) {
|
||||
if c.o.Log != nil {
|
||||
c.o.Log(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// release carries llmgw's release: its checksums and their signature,
|
||||
// checked against the key this build trusts, and a binary per
|
||||
// architecture checked against them.
|
||||
func (c *creator) release(ctx context.Context) error {
|
||||
v := c.o.Release
|
||||
base := c.o.Releases
|
||||
if base == "" {
|
||||
base = release.DefaultBase
|
||||
}
|
||||
c.log("llmgw %s: its checksums and their signature", v)
|
||||
sums, err := release.FetchChecksums(ctx, c.client, base, v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("llmgw %s: %w", v, err)
|
||||
}
|
||||
dir := kindRelease + "/" + v + "/"
|
||||
if err := c.writeSmall(dir+"checksums.txt", sums.Text); err != nil {
|
||||
return err
|
||||
}
|
||||
if sums.Signature != "" {
|
||||
if err := c.writeSmall(dir+release.SignatureName, []byte(sums.Signature)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
root := strings.TrimSuffix(base, "/") + "/" + v + "/"
|
||||
for _, arch := range c.o.Arches {
|
||||
asset := release.AssetName(v, "linux", arch)
|
||||
want, err := sums.For(asset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("llmgw %s: %w", v, err)
|
||||
}
|
||||
if err := c.fetch(ctx, root+asset, dir+asset, want); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.m.Releases = append(c.m.Releases, Release{Version: v, Arches: slices.Clone(c.o.Arches)})
|
||||
return nil
|
||||
}
|
||||
|
||||
// engine carries an engine version's builds for each architecture, checked
|
||||
// against the checksums its publisher gives — the same the nodes ask for
|
||||
// online.
|
||||
func (c *creator) engine(ctx context.Context, e EngineSpec) error {
|
||||
in := &provision.Installer{HTTP: c.client, APIBase: c.o.GitHubAPI, DownloadBase: c.o.GitHubDownload}
|
||||
c.log("%s %s: the checksums its publisher gives", e.Engine, e.Version)
|
||||
sums, url, err := in.Published(ctx, e.Engine, e.Version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s: %w", e.Engine, e.Version, err)
|
||||
}
|
||||
var variants []string
|
||||
done := map[string]bool{}
|
||||
for _, arch := range c.o.Arches {
|
||||
builds, err := provision.Builds(e.Engine, e.Version, arch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var names []string
|
||||
for _, b := range builds {
|
||||
names = append(names, b.Variant)
|
||||
if len(e.Variants) > 0 && !slices.Contains(e.Variants, b.Variant) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(variants, b.Variant) {
|
||||
variants = append(variants, b.Variant)
|
||||
}
|
||||
for _, asset := range b.Assets {
|
||||
if done[asset] {
|
||||
continue
|
||||
}
|
||||
want, ok := sums[asset]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s %s publishes no checksum for %s, so it cannot be carried checked", e.Engine, e.Version, asset)
|
||||
}
|
||||
if err := c.fetch(ctx, url(asset), kindEngine+"/"+e.Engine+"/"+e.Version+"/"+asset, want); err != nil {
|
||||
return err
|
||||
}
|
||||
done[asset] = true
|
||||
}
|
||||
}
|
||||
for _, v := range e.Variants {
|
||||
if !slices.Contains(names, v) && !anyArchHas(e, v, c.o.Arches) {
|
||||
return fmt.Errorf("%s has no build %q; it has %s", e.Engine, v, strings.Join(names, ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
c.m.Engines = append(c.m.Engines, Engine{Engine: e.Engine, Version: e.Version,
|
||||
Arches: slices.Clone(c.o.Arches), Variants: variants})
|
||||
return nil
|
||||
}
|
||||
|
||||
// anyArchHas says whether a variant is a build on any of the architectures:
|
||||
// CUDA 12.8 is published for x64 alone, and asking for it with arm64 too is
|
||||
// not a mistake.
|
||||
func anyArchHas(e EngineSpec, variant string, arches []string) bool {
|
||||
for _, a := range arches {
|
||||
bs, _ := provision.Builds(e.Engine, e.Version, a)
|
||||
for _, b := range bs {
|
||||
if b.Variant == variant {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// model carries a model file, checked against the checksum its registry
|
||||
// publishes when it publishes one, at the commit the registry had when it
|
||||
// was asked — so the bundle says exactly which weights it carries.
|
||||
func (c *creator) model(ctx context.Context, s ModelSpec) error {
|
||||
for _, n := range []string{s.Name, s.Version} {
|
||||
if err := mirror.ValidName(n); err != nil {
|
||||
return fmt.Errorf("model %s/%s: %w", s.Name, s.Version, err)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(s.Name, "_") {
|
||||
return fmt.Errorf("model %q: a name starting with an underscore is the mirror's own", s.Name)
|
||||
}
|
||||
var url, want, rev string
|
||||
switch {
|
||||
case strings.HasPrefix(s.Source, "hf:"):
|
||||
parts := strings.SplitN(strings.TrimPrefix(s.Source, "hf:"), "/", 3)
|
||||
if len(parts) != 3 || parts[2] == "" {
|
||||
return fmt.Errorf("%s names a repository, not a file: hf:owner/repo/file", s.Source)
|
||||
}
|
||||
repoID, file := parts[0]+"/"+parts[1], parts[2]
|
||||
reg := hf.New(c.o.Registry, time.Minute)
|
||||
repo, err := reg.Repo(ctx, repoID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", s.Source, err)
|
||||
}
|
||||
found := false
|
||||
for _, f := range repo.Files {
|
||||
if f.Path == file {
|
||||
want, found = f.SHA256, true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("%s has no file %s at its latest commit", repoID, file)
|
||||
}
|
||||
url, rev = repo.DownloadURL(reg.Base(), file), repo.Revision
|
||||
case strings.HasPrefix(s.Source, "https://"), strings.HasPrefix(s.Source, "http://"):
|
||||
url = s.Source
|
||||
default:
|
||||
return fmt.Errorf("model source %q: hf:owner/repo/file or an http(s) URL", s.Source)
|
||||
}
|
||||
name := path.Base(strings.SplitN(url, "?", 2)[0])
|
||||
if err := mirror.ValidName(name); err != nil {
|
||||
return fmt.Errorf("%s: %w", s.Source, err)
|
||||
}
|
||||
if err := c.fetch(ctx, url, kindModel+"/"+s.Name+"/"+s.Version+"/"+name, want); err != nil {
|
||||
return err
|
||||
}
|
||||
c.m.Models = append(c.m.Models, Model{Name: s.Name, Version: s.Version, Source: s.Source, Revision: rev})
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeSmall puts a file the bundle makes itself, rather than downloads.
|
||||
func (c *creator) writeSmall(rel string, b []byte) error {
|
||||
dst := filepath.Join(c.o.Out, filepath.FromSlash(rel))
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(dst, b, 0o644); err != nil { //nolint:gosec // published files
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
c.add(File{Path: rel, Bytes: int64(len(b)), SHA256: hex.EncodeToString(sum[:])})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *creator) add(f File) {
|
||||
for i := range c.m.Files {
|
||||
if c.m.Files[i].Path == f.Path {
|
||||
c.m.Files[i] = f
|
||||
return
|
||||
}
|
||||
}
|
||||
c.m.Files = append(c.m.Files, f)
|
||||
}
|
||||
|
||||
// fetch downloads url into the bundle at rel, checked against want when
|
||||
// there is one; a file already there that matches is kept.
|
||||
func (c *creator) fetch(ctx context.Context, url, rel, want string) error {
|
||||
dst := filepath.Join(c.o.Out, filepath.FromSlash(rel))
|
||||
if want != "" {
|
||||
if got, err := fileSHA256(dst); err == nil && got == want {
|
||||
info, _ := os.Stat(dst)
|
||||
c.log(" have %s", rel)
|
||||
c.add(File{Path: rel, Bytes: info.Size(), SHA256: want, Source: url})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetching %s: %w", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("fetching %s: %s", url, resp.Status)
|
||||
}
|
||||
if resp.ContentLength > 0 {
|
||||
c.log(" fetching %s (%d MB)", rel, resp.ContentLength>>20)
|
||||
} else {
|
||||
c.log(" fetching %s", rel)
|
||||
}
|
||||
part := dst + partSuffix
|
||||
f, err := os.Create(part) //nolint:gosec // inside the bundle
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(f, h), &progressReader{r: resp.Body, total: resp.ContentLength, log: c.log, name: rel})
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil && resp.ContentLength > 0 && n != resp.ContentLength {
|
||||
err = fmt.Errorf("got %d bytes of %d", n, resp.ContentLength)
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(part)
|
||||
return fmt.Errorf("fetching %s: %w", url, err)
|
||||
}
|
||||
got := hex.EncodeToString(h.Sum(nil))
|
||||
if want != "" && got != want {
|
||||
_ = os.Remove(part)
|
||||
return fmt.Errorf("%s does not match the checksum its publisher gave (got %s, expected %s)", url, got[:12], want[:12])
|
||||
}
|
||||
if err := os.Rename(part, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
c.add(File{Path: rel, Bytes: n, SHA256: got, Source: url})
|
||||
return nil
|
||||
}
|
||||
|
||||
// progressReader says how far a long download has got, every few seconds.
|
||||
type progressReader struct {
|
||||
r io.Reader
|
||||
total int64
|
||||
done int64
|
||||
last time.Time
|
||||
log func(string, ...any)
|
||||
name string
|
||||
}
|
||||
|
||||
func (p *progressReader) Read(b []byte) (int, error) {
|
||||
n, err := p.r.Read(b)
|
||||
p.done += int64(n)
|
||||
if p.total > 0 && time.Since(p.last) > 10*time.Second {
|
||||
if !p.last.IsZero() {
|
||||
p.log(" %d%% of %s", p.done*100/p.total, p.name)
|
||||
}
|
||||
p.last = time.Now()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Pack writes a bundle directory as one tar file, manifest first, so it can
|
||||
// be carried as one file and imported as a stream. Weights do not compress,
|
||||
// so it is not compressed.
|
||||
func Pack(dir, out string) error {
|
||||
src, m, err := open(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.close() //nolint:errcheck // read only
|
||||
f, err := os.Create(out + partSuffix) //nolint:gosec // the operator's path
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(out + partSuffix) //nolint:errcheck // gone once renamed
|
||||
tw := tar.NewWriter(f)
|
||||
now := time.Now()
|
||||
raw := src.manifest()
|
||||
if err := tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o644, Size: int64(len(raw)), ModTime: now, Typeflag: tar.TypeReg}); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tw.Write(raw); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
for _, mf := range m.Files {
|
||||
in, err := os.Open(filepath.Join(dir, filepath.FromSlash(mf.Path))) //nolint:gosec // a checked path in the bundle
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
err = tw.WriteHeader(&tar.Header{Name: mf.Path, Mode: 0o644, Size: mf.Bytes, ModTime: now, Typeflag: tar.TypeReg})
|
||||
if err == nil {
|
||||
_, err = io.Copy(tw, in)
|
||||
}
|
||||
in.Close()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return fmt.Errorf("packing %s: %w", mf.Path, err)
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(out+partSuffix, out)
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/mirror"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/release"
|
||||
)
|
||||
|
||||
// ImportOptions say where a bundle goes and how it is known to be the one
|
||||
// that was made.
|
||||
type ImportOptions struct {
|
||||
// Mirror is the mirror's root directory, /srv/models. Empty checks the
|
||||
// bundle and writes nothing.
|
||||
Mirror string
|
||||
// SHA256 is the manifest's digest as `bundle create` printed it.
|
||||
// Unchecked takes the bundle without one, said by whoever runs it.
|
||||
SHA256 string
|
||||
Unchecked bool
|
||||
// Progress hears each file as it is done: kept is one the mirror
|
||||
// already had, the same.
|
||||
Progress func(f File, kept bool)
|
||||
}
|
||||
|
||||
// Result is what an import did.
|
||||
type Result struct {
|
||||
Manifest Manifest
|
||||
// Digest is the manifest's sha256.
|
||||
Digest string
|
||||
// Written and Kept count files: put in the mirror, and already there.
|
||||
Written, Kept int
|
||||
Bytes int64
|
||||
}
|
||||
|
||||
// partSuffix marks a file still being written; the mirror lists none.
|
||||
const partSuffix = ".part"
|
||||
|
||||
// Import checks every file of a bundle and puts it in a mirror.
|
||||
//
|
||||
// Nothing is in place until everything is checked. Each file is written
|
||||
// beside where it goes, under a name the mirror does not serve, and checked
|
||||
// against the manifest as it is written; each release's checksums are
|
||||
// checked against the project's signing key and its binaries against them.
|
||||
// Only then is each renamed into place — so a bundle damaged anywhere
|
||||
// leaves the mirror as it was.
|
||||
//
|
||||
// A file the mirror already has is kept when it is the same, and refused
|
||||
// when it is not: a version in the mirror is never replaced, because that
|
||||
// is what makes going back to it possible.
|
||||
func Import(p string, o ImportOptions) (Result, error) {
|
||||
src, m, err := open(p)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
defer src.close() //nolint:errcheck // read only
|
||||
res := Result{Manifest: m, Digest: Digest(src.manifest())}
|
||||
if err := checkDigest(src.manifest(), o.SHA256, o.Unchecked); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
byPath := map[string]File{}
|
||||
dest := map[string]string{}
|
||||
keep := map[string]bool{}
|
||||
for _, f := range m.Files {
|
||||
byPath[f.Path] = f
|
||||
if o.Mirror == "" {
|
||||
continue
|
||||
}
|
||||
rel, _ := Destination(f.Path) // checked when the manifest was read
|
||||
dest[f.Path] = filepath.Join(o.Mirror, filepath.FromSlash(rel))
|
||||
same, err := alreadyHas(dest[f.Path], f)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
keep[f.Path] = same
|
||||
}
|
||||
|
||||
// Each release's checksums are kept as they pass, to be checked against
|
||||
// the signing key once the whole release has been read.
|
||||
small := map[string][]byte{}
|
||||
var written []string
|
||||
defer func() {
|
||||
// Whatever was staged and not put in place goes.
|
||||
for _, p := range written {
|
||||
_ = os.Remove(dest[p] + partSuffix)
|
||||
}
|
||||
}()
|
||||
seen := map[string]bool{}
|
||||
err = src.each(func(name string, r io.Reader) error {
|
||||
f, ok := byPath[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("the bundle holds %s, which its manifest does not list", name)
|
||||
}
|
||||
if seen[name] {
|
||||
return fmt.Errorf("the bundle holds %s twice", name)
|
||||
}
|
||||
seen[name] = true
|
||||
var w io.Writer = io.Discard
|
||||
var out *os.File
|
||||
if o.Mirror != "" && !keep[name] {
|
||||
if err := mkdirsLike(o.Mirror, filepath.Dir(dest[name])); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err = os.OpenFile(dest[name]+partSuffix, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) //nolint:gosec // a checked path under the mirror
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
written = append(written, name)
|
||||
w = out
|
||||
}
|
||||
if keep[name] {
|
||||
r = eofReader{}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if isReleaseSums(name) {
|
||||
w = io.MultiWriter(w, &limited{w: &buf, n: 1 << 20})
|
||||
}
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(w, h), r)
|
||||
if out != nil {
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
if keep[name] {
|
||||
if isReleaseSums(name) {
|
||||
b, err := os.ReadFile(dest[name])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
small[name] = b
|
||||
}
|
||||
res.Kept++
|
||||
if o.Progress != nil {
|
||||
o.Progress(f, true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if got := hex.EncodeToString(h.Sum(nil)); got != f.SHA256 || n != f.Bytes {
|
||||
return fmt.Errorf("%s is not what the bundle was made with (sha256 %s, expected %s): "+
|
||||
"the bundle was damaged on the way; nothing was put in the mirror", name, got[:12], f.SHA256[:12])
|
||||
}
|
||||
if isReleaseSums(name) {
|
||||
small[name] = buf.Bytes()
|
||||
}
|
||||
res.Written++
|
||||
res.Bytes += n
|
||||
if o.Progress != nil {
|
||||
o.Progress(f, false)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
for _, f := range m.Files {
|
||||
if !seen[f.Path] {
|
||||
return res, fmt.Errorf("the bundle lacks %s, which its manifest lists", f.Path)
|
||||
}
|
||||
}
|
||||
if err := checkReleases(m, small); err != nil {
|
||||
return res, err
|
||||
}
|
||||
if o.Mirror == "" {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
for _, name := range written {
|
||||
d := dest[name]
|
||||
f := byPath[name]
|
||||
if strings.HasPrefix(name, kindModel+"/") {
|
||||
// Beside the file before it is in place, as a download into the
|
||||
// mirror does, so a node is never offered it without its checksum.
|
||||
if err := mirror.Record(d, f.SHA256, f.Source); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
if err := os.Rename(d+partSuffix, d); err != nil {
|
||||
return res, err
|
||||
}
|
||||
chownLike(o.Mirror, d)
|
||||
if strings.HasPrefix(name, kindModel+"/") {
|
||||
dir, base := filepath.Split(d)
|
||||
chownLike(o.Mirror, filepath.Join(dir, "."+base+".sha256"))
|
||||
chownLike(o.Mirror, filepath.Join(dir, "."+base+".source"))
|
||||
}
|
||||
}
|
||||
written = nil
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// alreadyHas says whether the mirror has this file already, the same; an
|
||||
// error when it has a different one there.
|
||||
func alreadyHas(dst string, f File) (bool, error) {
|
||||
info, err := os.Stat(dst)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
sum := mirror.Recorded(dst)
|
||||
if sum == "" || info.Size() != f.Bytes {
|
||||
if sum, err = fileSHA256(dst); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if sum != f.SHA256 || info.Size() != f.Bytes {
|
||||
return false, fmt.Errorf("the mirror already has %s, and it is not the bundle's: "+
|
||||
"a version in the mirror is never replaced; give the model another version in a new bundle", dst)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func isReleaseSums(name string) bool {
|
||||
if !strings.HasPrefix(name, kindRelease+"/") {
|
||||
return false
|
||||
}
|
||||
b := path.Base(name)
|
||||
return b == "checksums.txt" || b == release.SignatureName
|
||||
}
|
||||
|
||||
// checkReleases holds each release's binaries to its checksums, and the
|
||||
// checksums to the project's signing key — as `node add` and an upgrade
|
||||
// would online. The manifest's own checksums say the bundle arrived as it
|
||||
// was made; these say what was made is the project's release.
|
||||
func checkReleases(m Manifest, small map[string][]byte) error {
|
||||
byVersion := map[string][]File{}
|
||||
for _, f := range m.Files {
|
||||
if strings.HasPrefix(f.Path, kindRelease+"/") {
|
||||
v := strings.Split(f.Path, "/")[1]
|
||||
byVersion[v] = append(byVersion[v], f)
|
||||
}
|
||||
}
|
||||
for _, v := range slices.Sorted(maps.Keys(byVersion)) {
|
||||
root := kindRelease + "/" + v + "/"
|
||||
text, ok := small[root+"checksums.txt"]
|
||||
if !ok {
|
||||
return fmt.Errorf("the bundle's llmgw %s has no checksums.txt", v)
|
||||
}
|
||||
c := release.Checksums{Text: text, Signature: string(small[root+release.SignatureName])}
|
||||
if err := c.Verify(); err != nil {
|
||||
return fmt.Errorf("llmgw %s in the bundle: %w", v, err)
|
||||
}
|
||||
for _, f := range byVersion[v] {
|
||||
name := path.Base(f.Path)
|
||||
if name == "checksums.txt" || name == release.SignatureName {
|
||||
continue
|
||||
}
|
||||
want, err := c.For(name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("llmgw %s in the bundle: %w", v, err)
|
||||
}
|
||||
if want != f.SHA256 {
|
||||
return fmt.Errorf("%s in the bundle is not the release's (the release gives sha256 %s)", f.Path, want[:12])
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mkdirsLike makes dir and every directory above it up to root, each owned
|
||||
// as root is: the mirror runs as its own user, and removes what it holds.
|
||||
func mkdirsLike(root, dir string) error {
|
||||
rel, err := filepath.Rel(root, dir)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return fmt.Errorf("%s is outside the mirror at %s", dir, root)
|
||||
}
|
||||
cur := root
|
||||
for _, e := range strings.Split(rel, string(filepath.Separator)) {
|
||||
if e == "." {
|
||||
continue
|
||||
}
|
||||
cur = filepath.Join(cur, e)
|
||||
if _, err := os.Stat(cur); err == nil {
|
||||
continue
|
||||
}
|
||||
if err := os.Mkdir(cur, 0o755); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
chownLike(root, cur)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileSHA256(p string) (string, error) {
|
||||
f, err := os.Open(p) //nolint:gosec // a file in the mirror
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// eofReader is a file passed over: a tar moves past it on its own.
|
||||
type eofReader struct{}
|
||||
|
||||
func (eofReader) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
|
||||
// limited keeps at most n bytes and quietly drops the rest: a checksums
|
||||
// file larger than that is refused by its signature, not by a write error.
|
||||
type limited struct {
|
||||
w io.Writer
|
||||
n int64
|
||||
}
|
||||
|
||||
func (l *limited) Write(p []byte) (int, error) {
|
||||
if l.n <= 0 {
|
||||
return len(p), nil
|
||||
}
|
||||
k := min(int64(len(p)), l.n)
|
||||
l.n -= k
|
||||
if _, err := l.w.Write(p[:k]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxManifest bounds the manifest read into memory.
|
||||
const maxManifest = 16 << 20
|
||||
|
||||
// source is a bundle being read: a directory, or the same packed as a tar
|
||||
// with the manifest first, read as a stream so tens of gigabytes of weights
|
||||
// are never unpacked twice.
|
||||
type source interface {
|
||||
// manifest is the manifest's bytes, as they are in the bundle.
|
||||
manifest() []byte
|
||||
// each hands over every file, in the order the bundle has them. A file
|
||||
// fn does not read is passed over.
|
||||
each(fn func(path string, r io.Reader) error) error
|
||||
close() error
|
||||
}
|
||||
|
||||
// open reads a bundle's manifest, from a directory or a tar.
|
||||
func open(p string) (source, Manifest, error) {
|
||||
info, err := os.Stat(p)
|
||||
if err != nil {
|
||||
return nil, Manifest{}, fmt.Errorf("the bundle: %w", err)
|
||||
}
|
||||
var src source
|
||||
if info.IsDir() {
|
||||
src, err = openDir(p)
|
||||
} else {
|
||||
src, err = openTar(p)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, Manifest{}, err
|
||||
}
|
||||
m, err := parseManifest(src.manifest())
|
||||
if err != nil {
|
||||
_ = src.close()
|
||||
return nil, Manifest{}, err
|
||||
}
|
||||
if d, ok := src.(*dirSource); ok {
|
||||
d.files = m.Files
|
||||
}
|
||||
return src, m, nil
|
||||
}
|
||||
|
||||
// ReadManifest reads a bundle's manifest and its digest, without reading
|
||||
// its files.
|
||||
func ReadManifest(p string) (Manifest, string, error) {
|
||||
src, m, err := open(p)
|
||||
if err != nil {
|
||||
return Manifest{}, "", err
|
||||
}
|
||||
defer src.close() //nolint:errcheck // read only
|
||||
return m, Digest(src.manifest()), nil
|
||||
}
|
||||
|
||||
type dirSource struct {
|
||||
dir string
|
||||
raw []byte
|
||||
files []File
|
||||
}
|
||||
|
||||
func openDir(dir string) (*dirSource, error) {
|
||||
raw, err := readLimited(filepath.Join(dir, ManifestName))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s is not a bundle: %w", dir, err)
|
||||
}
|
||||
return &dirSource{dir: dir, raw: raw}, nil
|
||||
}
|
||||
|
||||
func (d *dirSource) manifest() []byte { return d.raw }
|
||||
func (d *dirSource) close() error { return nil }
|
||||
|
||||
func (d *dirSource) each(fn func(string, io.Reader) error) error {
|
||||
for _, f := range d.files {
|
||||
// The path was checked when the manifest was read: plain names
|
||||
// under the bundle's three directories.
|
||||
in, err := os.Open(filepath.Join(d.dir, filepath.FromSlash(f.Path)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("the bundle lists %s and does not have it: %w", f.Path, err)
|
||||
}
|
||||
err = fn(f.Path, in)
|
||||
in.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type tarSource struct {
|
||||
f *os.File
|
||||
tr *tar.Reader
|
||||
raw []byte
|
||||
}
|
||||
|
||||
func openTar(p string) (*tarSource, error) {
|
||||
f, err := os.Open(p) //nolint:gosec // the operator's bundle
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tr := tar.NewReader(f)
|
||||
h, err := tr.Next()
|
||||
if err != nil || h.Name != ManifestName || h.Typeflag != tar.TypeReg {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("%s is not a bundle: its first entry is not %s", p, ManifestName)
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(tr, maxManifest))
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &tarSource{f: f, tr: tr, raw: raw}, nil
|
||||
}
|
||||
|
||||
func (t *tarSource) manifest() []byte { return t.raw }
|
||||
func (t *tarSource) close() error { return t.f.Close() }
|
||||
|
||||
func (t *tarSource) each(fn func(string, io.Reader) error) error {
|
||||
for {
|
||||
h, err := t.tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading the bundle: %w", err)
|
||||
}
|
||||
if h.Typeflag == tar.TypeDir {
|
||||
continue
|
||||
}
|
||||
if h.Typeflag != tar.TypeReg {
|
||||
// Links and devices have no place in a bundle; the files it
|
||||
// lists are all it holds.
|
||||
return fmt.Errorf("the bundle holds %s, which is not a plain file", h.Name)
|
||||
}
|
||||
if err := fn(strings.TrimPrefix(h.Name, "./"), t.tr); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readLimited(p string) ([]byte, error) {
|
||||
f, err := os.Open(p) //nolint:gosec // the operator's bundle
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return io.ReadAll(io.LimitReader(f, maxManifest))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package bundle
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Trust records a bundle's engine checksums in the file the control plane
|
||||
// reads them from, beside any recorded before, and says how many it holds
|
||||
// now. Only the manifest is read: the checksums are what each node holds
|
||||
// the files it fetches to, so the manifest must be the one that was made —
|
||||
// which is what the digest says.
|
||||
func Trust(p, file, digest string, unchecked bool) (Manifest, int, error) {
|
||||
src, m, err := open(p)
|
||||
if err != nil {
|
||||
return Manifest{}, 0, err
|
||||
}
|
||||
defer src.close() //nolint:errcheck // read only
|
||||
if err := checkDigest(src.manifest(), digest, unchecked); err != nil {
|
||||
return m, 0, err
|
||||
}
|
||||
n, err := TrustManifest(m, file)
|
||||
return m, n, err
|
||||
}
|
||||
|
||||
// TrustManifest records a manifest's engine checksums, for one already
|
||||
// checked by an import.
|
||||
func TrustManifest(m Manifest, file string) (int, error) {
|
||||
sums, err := readTrusted(file)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return 0, err
|
||||
}
|
||||
if sums == nil {
|
||||
sums = map[string]string{}
|
||||
}
|
||||
for _, f := range m.Files {
|
||||
if strings.HasPrefix(f.Path, kindEngine+"/") {
|
||||
sums[Prefix+"/"+f.Path] = f.SHA256
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("# Engine files the nodes may install, as the offline bundles they came in\n" +
|
||||
"# gave them. Kept by 'llmgw bundle import' and 'llmgw bundle trust'.\n")
|
||||
for _, k := range slices.Sorted(maps.Keys(sums)) {
|
||||
fmt.Fprintf(&b, "%s %s\n", sums[k], k)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
tmp := file + partSuffix
|
||||
if err := os.WriteFile(tmp, []byte(b.String()), 0o644); err != nil { //nolint:gosec // checksums, for anyone to read
|
||||
return 0, err
|
||||
}
|
||||
return len(sums), os.Rename(tmp, file)
|
||||
}
|
||||
|
||||
// readTrusted reads a checksums file: "<sha256> <path>" a line, as
|
||||
// sha256sum writes them, with paths as the mirror has the files.
|
||||
func readTrusted(file string) (map[string]string, error) {
|
||||
b, err := os.ReadFile(file) //nolint:gosec // the control plane's own file
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]string{}
|
||||
sc := bufio.NewScanner(bytes.NewReader(b))
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
f := strings.Fields(line)
|
||||
if len(f) != 2 || len(f[0]) != 64 {
|
||||
return nil, fmt.Errorf("%s: %q is not a checksum and a file", file, line)
|
||||
}
|
||||
out[strings.TrimPrefix(f[1], "*")] = f[0]
|
||||
}
|
||||
return out, sc.Err()
|
||||
}
|
||||
|
||||
// Trusted is the engine checksums a control plane holds, read from their
|
||||
// file again whenever it changes — so a bundle imported while the control
|
||||
// plane runs is offered to the next node that asks.
|
||||
type Trusted struct {
|
||||
file string
|
||||
|
||||
mu sync.Mutex
|
||||
mod time.Time
|
||||
size int64
|
||||
sums map[string]string
|
||||
err error
|
||||
}
|
||||
|
||||
// NewTrusted reads checksums from file as they are asked for.
|
||||
func NewTrusted(file string) *Trusted { return &Trusted{file: file} }
|
||||
|
||||
// For is an engine version's files and their checksums, by file name; none
|
||||
// when no bundle imported here carried it.
|
||||
func (t *Trusted) For(engine, version string) map[string]string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if info, err := os.Stat(t.file); err != nil {
|
||||
t.sums, t.err, t.mod, t.size = nil, err, time.Time{}, 0
|
||||
} else if !info.ModTime().Equal(t.mod) || info.Size() != t.size {
|
||||
t.sums, t.err = readTrusted(t.file)
|
||||
t.mod, t.size = info.ModTime(), info.Size()
|
||||
}
|
||||
prefix := Prefix + "/" + kindEngine + "/" + engine + "/" + version + "/"
|
||||
out := map[string]string{}
|
||||
for p, sum := range t.sums {
|
||||
if rest, ok := strings.CutPrefix(p, prefix); ok && path.Base(rest) == rest {
|
||||
out[rest] = sum
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Err is why the file could not be read, the last time it was.
|
||||
func (t *Trusted) Err() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package canary compares a model's candidate with the model it may
|
||||
// replace, from what each side served, and says when to give up on it.
|
||||
package canary
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/catalog"
|
||||
)
|
||||
|
||||
// Side is what one side of a canary served since it began.
|
||||
type Side struct {
|
||||
Requests int64 `json:"requests"`
|
||||
// Errors are answers of 500 and up: the engine's failures, not the
|
||||
// client's mistakes.
|
||||
Errors int64 `json:"errors"`
|
||||
// TTFT is over streamed requests, Latency over the rest, both means in
|
||||
// milliseconds with how many they are over.
|
||||
TTFTMs float64 `json:"ttft_ms"`
|
||||
TTFTCount int64 `json:"ttft_count"`
|
||||
LatencyMs float64 `json:"latency_ms"`
|
||||
LatencyCount int64 `json:"latency_count"`
|
||||
}
|
||||
|
||||
// ErrorRate is errors over requests, 0 with none.
|
||||
func (v Side) ErrorRate() float64 {
|
||||
if v.Requests == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(v.Errors) / float64(v.Requests)
|
||||
}
|
||||
|
||||
// Add counts one finished request.
|
||||
func (v *Side) Add(status int, streamed bool, ttft, took time.Duration) {
|
||||
v.Requests++
|
||||
if status >= 500 {
|
||||
v.Errors++
|
||||
}
|
||||
switch {
|
||||
case streamed && ttft > 0:
|
||||
v.TTFTMs += (float64(ttft.Milliseconds()) - v.TTFTMs) / float64(v.TTFTCount+1)
|
||||
v.TTFTCount++
|
||||
case !streamed && status < 400:
|
||||
v.LatencyMs += (float64(took.Milliseconds()) - v.LatencyMs) / float64(v.LatencyCount+1)
|
||||
v.LatencyCount++
|
||||
}
|
||||
}
|
||||
|
||||
// Stat compares the two sides of one model's canary.
|
||||
type Stat struct {
|
||||
Canary string `json:"canary"`
|
||||
Since time.Time `json:"since"`
|
||||
Stable Side `json:"stable"`
|
||||
Candidate Side `json:"candidate"`
|
||||
}
|
||||
|
||||
// minTimed is how many timed requests a side needs before its mean counts.
|
||||
const minTimed = 10
|
||||
|
||||
// Verdict says whether the candidate has done worse than the canary allows,
|
||||
// and how. Nothing is decided before it has served MinRequests.
|
||||
func Verdict(s Stat, cn catalog.Canary) (rollback bool, why string) {
|
||||
minReq, maxErr, maxRatio := cn.Limits()
|
||||
c, st := s.Candidate, s.Stable
|
||||
if c.Requests < int64(minReq) {
|
||||
return false, ""
|
||||
}
|
||||
if d := c.ErrorRate() - st.ErrorRate(); d > maxErr {
|
||||
return true, fmt.Sprintf("errors in %.1f%% of its requests against %.1f%%", 100*c.ErrorRate(), 100*st.ErrorRate())
|
||||
}
|
||||
if c.TTFTCount >= minTimed && st.TTFTCount >= minTimed && st.TTFTMs > 0 && c.TTFTMs > maxRatio*st.TTFTMs {
|
||||
return true, fmt.Sprintf("first token after %.0f ms on average against %.0f ms", c.TTFTMs, st.TTFTMs)
|
||||
}
|
||||
if c.LatencyCount >= minTimed && st.LatencyCount >= minTimed && st.LatencyMs > 0 && c.LatencyMs > maxRatio*st.LatencyMs {
|
||||
return true, fmt.Sprintf("answers in %.0f ms on average against %.0f ms", c.LatencyMs, st.LatencyMs)
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package canary
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/catalog"
|
||||
)
|
||||
|
||||
func side(n, errs int, ms time.Duration, streamed bool) Side {
|
||||
var s Side
|
||||
for i := range n {
|
||||
status := 200
|
||||
if i < errs {
|
||||
status = 500
|
||||
}
|
||||
s.Add(status, streamed, ms, ms)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestTheVerdict(t *testing.T) {
|
||||
cn := catalog.Canary{Model: "c", Percent: 10}
|
||||
for name, c := range map[string]struct {
|
||||
stable, cand Side
|
||||
rollback bool
|
||||
}{
|
||||
"too few to say": {side(500, 0, 100*time.Millisecond, true), side(49, 49, 100*time.Millisecond, true), false},
|
||||
"as good": {side(500, 5, 100*time.Millisecond, true), side(60, 1, 110*time.Millisecond, true), false},
|
||||
"more errors": {side(500, 5, 100*time.Millisecond, true), side(60, 6, 100*time.Millisecond, true), true},
|
||||
"slower first token": {side(500, 0, 100*time.Millisecond, true), side(60, 0, 200*time.Millisecond, true), true},
|
||||
"slower answers": {side(500, 0, time.Second, false), side(60, 0, 2*time.Second, false), true},
|
||||
} {
|
||||
got, why := Verdict(Stat{Stable: c.stable, Candidate: c.cand}, cn)
|
||||
if got != c.rollback {
|
||||
t.Errorf("%s: rollback=%v (%s)", name, got, why)
|
||||
}
|
||||
if got && why == "" {
|
||||
t.Errorf("%s: no reason given", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-3
@@ -16,6 +16,7 @@ import (
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/agent/discovery"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/config"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/obs"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/version"
|
||||
)
|
||||
|
||||
@@ -64,6 +65,21 @@ func newAgentCmd() *cobra.Command {
|
||||
}
|
||||
cfg.Version = version.Version
|
||||
|
||||
// Before the agent, so its tracer is the configured one.
|
||||
shutdownTracing, err := obs.SetupTracing(cmd.Context(), obs.TracingOptions{
|
||||
Endpoint: cfg.Tracing.Endpoint, SampleRatio: cfg.Tracing.SampleRatio,
|
||||
Service: "llmgw-agent", Version: version.Version, Instance: cfg.NodeID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
// Bounded: a collector that is gone must not hold up a shutdown.
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = shutdownTracing(sctx)
|
||||
}()
|
||||
|
||||
httpClient, err := agent.Client(cfg.TLS, 30*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -159,13 +175,13 @@ func printInventory(inv discovery.Inventory) {
|
||||
if !g.Health.OK() {
|
||||
health = g.Health.Problems[0]
|
||||
}
|
||||
fmt.Fprintf(w, " %d\t%s\t%s\t%d MiB\t%s\t%s\n",
|
||||
g.Index, g.Class(), g.Name, g.MemoryTotalMB, g.ComputeCapability, health)
|
||||
fmt.Fprintf(w, " %s\t%s\t%s\t%d MiB\t%s\t%s\n",
|
||||
discovery.DeviceLabel(g.Index), g.Class(), g.Name, g.MemoryTotalMB, g.ComputeCapability, health)
|
||||
}
|
||||
fmt.Fprintf(w, " classes: %v\n", inv.Classes())
|
||||
for _, g := range inv.GPUs {
|
||||
if len(g.NVLinkPeers) > 0 {
|
||||
fmt.Fprintf(w, " GPU %d NVLink peers: %v\n", g.Index, g.NVLinkPeers)
|
||||
fmt.Fprintf(w, " GPU %s NVLink peers: %v\n", discovery.DeviceLabel(g.Index), g.NVLinkPeers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newAnswerCacheCmd(open opener) *cobra.Command {
|
||||
var (
|
||||
project string
|
||||
ttl time.Duration
|
||||
anyAnswer bool
|
||||
off bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "cache",
|
||||
Short: "Reuse a project's answers: the same request is answered again without the model",
|
||||
Long: "With this on, a request of the project that is the same as one answered within\n" +
|
||||
"--ttl, to the same model, gets that answer again, from the gateway's memory,\n" +
|
||||
"rather than asking the model. It is answered with x-llmgw-cache: hit, recorded\n" +
|
||||
"as a request with no tokens, and costs nothing against a budget.\n\n" +
|
||||
"Only answers that would come out the same are reused: a chat or completion\n" +
|
||||
"asked at temperature 0 or with a seed, and embeddings, rerank and score.\n" +
|
||||
"--any reuses every answer, sampled or not. A client sending\n" +
|
||||
"Cache-Control: no-cache or x-llmgw-cache: no is always asked afresh, and so is\n" +
|
||||
"a request continuing a stored conversation or under a guardrails no_store\n" +
|
||||
"policy. The guardrails judge a reused answer as they judge any other.\n\n" +
|
||||
"Off for every project until this is run. Without --ttl or --off, says how\n" +
|
||||
"it stands. The answers are held in memory, router.cache bounds how much.",
|
||||
Example: " llmgw keys cache --project Acme/ml/train --ttl 1h\n" +
|
||||
" llmgw keys cache --project Acme/ml/eval --ttl 24h --any\n" +
|
||||
" llmgw keys cache --project Acme/ml/train --off",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
switch {
|
||||
case off && (ttl != 0 || anyAnswer):
|
||||
return fmt.Errorf("--off, or --ttl with --any: not both")
|
||||
case ttl < 0:
|
||||
return fmt.Errorf("--ttl is how long an answer is reused, like 1h")
|
||||
case ttl > 0 && ttl < time.Second:
|
||||
return fmt.Errorf("--ttl is at least a second")
|
||||
case anyAnswer && ttl == 0:
|
||||
return fmt.Errorf("--any goes with --ttl: say how long answers are reused")
|
||||
}
|
||||
s, err := open(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.Close()
|
||||
p, err := resolveProject(cmd.Context(), s, project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if off || ttl > 0 {
|
||||
if err := s.SetAnswerCache(cmd.Context(), p.ID, ttl, anyAnswer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c, err := s.AnswerCacheOf(cmd.Context(), p.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case c.TTL == 0:
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s reuses no answers.\n", p.Path)
|
||||
case c.Any:
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s reuses every answer for %s, sampled or not.\n", p.Path, c.TTL)
|
||||
default:
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s reuses answers for %s: those asked at temperature 0 or with a seed, "+
|
||||
"and embeddings, rerank and score.\n", p.Path, c.TTL)
|
||||
}
|
||||
if off || ttl > 0 {
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "Gateways see the change within 30 seconds.")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&project, "project", "", "project: id, path or unique name")
|
||||
cmd.Flags().DurationVar(&ttl, "ttl", 0, "how long an answer is reused, like 1h")
|
||||
cmd.Flags().BoolVar(&anyAnswer, "any", false, "reuse sampled answers too, not only reproducible ones")
|
||||
cmd.Flags().BoolVar(&off, "off", false, "stop reusing answers for this project")
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAProjectIsToldToReuseItsAnswersAndToStop(t *testing.T) {
|
||||
db := filepath.Join(t.TempDir(), "s.db")
|
||||
mustRun(t, db, "org", "add", "org", "Acme")
|
||||
mustRun(t, db, "org", "add", "team", "ml", "--in", "Acme")
|
||||
mustRun(t, db, "org", "add", "project", "train", "--in", "Acme/ml")
|
||||
|
||||
if out := mustRun(t, db, "keys", "cache", "--project", "Acme/ml/train"); !strings.Contains(out, "reuses no answers") {
|
||||
t.Errorf("before: %s", out)
|
||||
}
|
||||
if out := mustRun(t, db, "keys", "cache", "--project", "Acme/ml/train", "--ttl", "1h"); !strings.Contains(out, "for 1h0m0s: those asked at temperature 0") {
|
||||
t.Errorf("on: %s", out)
|
||||
}
|
||||
if out := mustRun(t, db, "keys", "cache", "--project", "train", "--ttl", "24h", "--any"); !strings.Contains(out, "every answer for 24h0m0s") {
|
||||
t.Errorf("any: %s", out)
|
||||
}
|
||||
for _, bad := range [][]string{{"--off", "--ttl", "1h"}, {"--any"}, {"--ttl", "10ms"}} {
|
||||
if _, err := run(t, db, append([]string{"keys", "cache", "--project", "train"}, bad...)...); err == nil {
|
||||
t.Errorf("%v was accepted", bad)
|
||||
}
|
||||
}
|
||||
if out := mustRun(t, db, "keys", "cache", "--project", "train", "--off"); !strings.Contains(out, "reuses no answers") {
|
||||
t.Errorf("off: %s", out)
|
||||
}
|
||||
}
|
||||
+27
-4
@@ -74,6 +74,16 @@ func newBackupCmd() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(cfg.BackupCopyTo) > 0 {
|
||||
if err := copyBackup(cmd.Context(), path, cfg.BackupCopyTo, cfg.BackupCopyKey,
|
||||
filepath.Join(etcDir, "backup_known_hosts"), keep,
|
||||
func(s string) { fmt.Fprintln(cmd.OutOrStdout(), s) }); err != nil {
|
||||
// The archive is here; that it did not travel is said, and
|
||||
// the exit says it failed, so the timer's unit shows it.
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "wrote %s\n", path)
|
||||
return fmt.Errorf("the archive was not copied off this machine: %w", err)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "wrote %s", path)
|
||||
if removed > 0 {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "; removed %d older", removed)
|
||||
@@ -263,8 +273,9 @@ func addTree(tw *tar.Writer, root, as string) error {
|
||||
}
|
||||
switch {
|
||||
case d.IsDir():
|
||||
return tw.WriteHeader(&tar.Header{Name: name + "/", Mode: int64(info.Mode().Perm()),
|
||||
Typeflag: tar.TypeDir, ModTime: info.ModTime()})
|
||||
h := ownedHeader(info)
|
||||
h.Name, h.Mode, h.Typeflag, h.ModTime = name+"/", int64(info.Mode().Perm()), tar.TypeDir, info.ModTime()
|
||||
return tw.WriteHeader(h)
|
||||
case info.Mode().IsRegular():
|
||||
return addFile(tw, p, name)
|
||||
}
|
||||
@@ -282,14 +293,26 @@ func addFile(tw *tar.Writer, path, name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: int64(info.Mode().Perm()),
|
||||
Size: info.Size(), ModTime: info.ModTime(), Typeflag: tar.TypeReg}); err != nil {
|
||||
h := ownedHeader(info)
|
||||
h.Name, h.Mode, h.Size, h.ModTime, h.Typeflag = name, int64(info.Mode().Perm()), info.Size(), info.ModTime(), tar.TypeReg
|
||||
if err := tw.WriteHeader(h); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(tw, f)
|
||||
return err
|
||||
}
|
||||
|
||||
// ownedHeader is a header with the file's owner and group by name, which is
|
||||
// what a restore on another machine can give back: the llmgw user there has
|
||||
// another number.
|
||||
func ownedHeader(info fs.FileInfo) *tar.Header {
|
||||
h, err := tar.FileInfoHeader(info, "")
|
||||
if err != nil {
|
||||
return &tar.Header{}
|
||||
}
|
||||
return &tar.Header{Uid: h.Uid, Gid: h.Gid, Uname: h.Uname, Gname: h.Gname}
|
||||
}
|
||||
|
||||
func addBytes(tw *tar.Writer, name string, b []byte) error {
|
||||
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(b)),
|
||||
ModTime: time.Now(), Typeflag: tar.TypeReg}); err != nil {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/onboard"
|
||||
)
|
||||
|
||||
// copyBackup puts an archive where server.yaml's backup_copy_to says, and
|
||||
// keeps as many there as here. It says each copy, and fails on the first
|
||||
// that cannot be made.
|
||||
func copyBackup(ctx context.Context, archive string, targets []string, key, knownHosts string, keep int, say func(string)) error {
|
||||
for _, t := range targets {
|
||||
if strings.HasPrefix(t, "ssh://") {
|
||||
if err := copyOverSSH(ctx, archive, t, key, knownHosts, keep); err != nil {
|
||||
return fmt.Errorf("%s: %w", t, err)
|
||||
}
|
||||
} else {
|
||||
if err := copyToDir(archive, t, keep); err != nil {
|
||||
return fmt.Errorf("%s: %w", t, err)
|
||||
}
|
||||
}
|
||||
say("copied to " + t)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyToDir(archive, dir string, keep int) error {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := os.ReadFile(archive) //nolint:gosec // the archive just written
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
final := filepath.Join(dir, filepath.Base(archive))
|
||||
if err := os.WriteFile(final+".part", b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(final+".part", final); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = pruneBackups(dir, keep)
|
||||
return err
|
||||
}
|
||||
|
||||
func copyOverSSH(ctx context.Context, archive, target, key, knownHosts string, keep int) error {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil || u.User == nil || u.Host == "" || u.Path == "" {
|
||||
return fmt.Errorf("not ssh://user@host/path")
|
||||
}
|
||||
port := 22
|
||||
if p := u.Port(); p != "" {
|
||||
port, _ = strconv.Atoi(p)
|
||||
}
|
||||
b, err := os.ReadFile(archive) //nolint:gosec // the archive just written
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := &onboard.GoSSH{Addr: u.Hostname(), Port: port, User: u.User.Username(), KeyFile: key, KnownHosts: knownHosts}
|
||||
defer c.Close()
|
||||
dir, name := shellQuote(u.Path), shellQuote(filepath.Base(archive))
|
||||
// Written beside its name and renamed, then the oldest beyond keep
|
||||
// removed: only archives this command wrote, by their names.
|
||||
script := fmt.Sprintf(`set -e
|
||||
umask 077
|
||||
mkdir -p %[1]s
|
||||
cat > %[1]s/%[2]s.part
|
||||
mv %[1]s/%[2]s.part %[1]s/%[2]s
|
||||
ls -1t %[1]s | grep -E '^llmgw-backup-.*\.tar\.gz(\.age)?$' | tail -n +%[3]d | while read -r f; do rm -f %[1]s/"$f"; done
|
||||
`, dir, name, keep+1)
|
||||
if out, err := c.Run(ctx, script, b); err != nil {
|
||||
return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
|
||||
+65
-15
@@ -2,7 +2,9 @@ package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -20,6 +22,7 @@ func newBenchCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
|
||||
metrics string
|
||||
engine string
|
||||
key string
|
||||
mkey string
|
||||
save bool
|
||||
)
|
||||
|
||||
@@ -41,10 +44,25 @@ func newBenchCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
|
||||
cfg.MetricsURL = metrics
|
||||
cfg.Engine = engine
|
||||
cfg.APIKey = key
|
||||
// A replica's engine demands its own key. Asked for rather than
|
||||
// typed: the admin API knows which replica answers at the target.
|
||||
if cfg.APIKey == "" {
|
||||
cfg.APIKey = replicaKey(cmd, client, target)
|
||||
cfg.MetricsKey = mkey
|
||||
// A replica's engine demands its own key, for its API and — on
|
||||
// llama.cpp and TensorRT-LLM — for its metrics. Asked for rather
|
||||
// than typed: the admin API knows which replica answers where, and
|
||||
// this runs wherever ctl does, which can reach it.
|
||||
needKeys := cfg.APIKey == "" || (metrics != "" && cfg.MetricsKey == "")
|
||||
if needKeys {
|
||||
reps, err := listReplicas(cmd, client)
|
||||
if cfg.APIKey == "" {
|
||||
cfg.APIKey = replicaKey(reps, target)
|
||||
}
|
||||
if metrics != "" && cfg.MetricsKey == "" {
|
||||
cfg.MetricsKey = replicaKey(reps, metrics)
|
||||
if err != nil {
|
||||
cmd.PrintErrf("The admin API could not be asked for the engine key of the replica at "+
|
||||
"--metrics (%v); an engine that guards its metrics will refuse them. "+
|
||||
"Pass --metrics-key to give it.\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(steps) > 0 {
|
||||
cfg.Concurrency = steps
|
||||
@@ -72,17 +90,29 @@ func newBenchCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
|
||||
if s.Failed > 0 {
|
||||
verdict = fmt.Sprintf("%d failed", s.Failed)
|
||||
}
|
||||
// Unread is not zero: a dash, and the reason under the row.
|
||||
wait, kv := fmt.Sprintf("%.1f", s.Waiting), fmt.Sprintf("%.0f%%", s.KVUsage*100)
|
||||
if s.MetricsUnread != "" {
|
||||
wait, kv = "-", "-"
|
||||
}
|
||||
fmt.Fprintf(cmd.ErrOrStderr(), row,
|
||||
fmt.Sprint(s.Concurrency),
|
||||
fmt.Sprintf("%.1f", s.RequestsPerSec),
|
||||
fmt.Sprintf("%.0f", s.TokensPerSec),
|
||||
ms(s.TTFT.P50), ms(s.TTFT.P99), ms(s.TPOT.P99),
|
||||
fmt.Sprintf("%.1f", s.Waiting),
|
||||
fmt.Sprintf("%.0f%%", s.KVUsage*100),
|
||||
verdict)
|
||||
wait, kv, verdict)
|
||||
if s.MetricsUnread != "" {
|
||||
fmt.Fprintf(cmd.ErrOrStderr(), " metrics not read: %s\n", s.MetricsUnread)
|
||||
}
|
||||
}
|
||||
|
||||
res, err := bench.Run(cmd.Context(), cfg, progress)
|
||||
var refused *bench.MetricsRefusedError
|
||||
if errors.As(err, &refused) {
|
||||
return fmt.Errorf("%w. The engine's key is the admin API's, given for the replica "+
|
||||
"whose endpoint `llmgw ctl replicas` lists at --metrics' address; "+
|
||||
"or pass it with --metrics-key", err)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -106,8 +136,10 @@ func newBenchCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
|
||||
f := cmd.Flags()
|
||||
f.StringVar(&target, "target", "http://127.0.0.1:8080", "base URL: a replica, or the gateway")
|
||||
f.StringVar(&metrics, "metrics", "", "the replica's /metrics, to observe queue depth and KV usage")
|
||||
f.StringVar(&engine, "engine", "", "which metric names --metrics uses: vllm | sglang | llamacpp")
|
||||
f.StringVar(&engine, "engine", "", "which metric names --metrics uses: vllm | sglang | llamacpp | trtllm (whose are at /prometheus/metrics)")
|
||||
f.StringVar(&key, "key", "", "API key, when the gateway requires one")
|
||||
f.StringVar(&mkey, "metrics-key", "",
|
||||
"the engine key --metrics is read with (default: the replica's, from the admin API)")
|
||||
f.IntSliceVar(&steps, "concurrency", nil, "levels to try (default 1,2,4,…,128)")
|
||||
f.DurationVar(&cfg.Duration, "duration", cfg.Duration, "how long to hold each level")
|
||||
f.IntVar(&cfg.PromptTokens, "prompt-tokens", cfg.PromptTokens, "approximate prompt size")
|
||||
@@ -233,17 +265,35 @@ func ms(d time.Duration) string {
|
||||
}
|
||||
}
|
||||
|
||||
// replicaKey is the engine key of the replica at target, or "" when target is
|
||||
// not a replica (the gateway, say) or the admin API cannot be asked.
|
||||
func replicaKey(cmd *cobra.Command, client func() *ctlClient, target string) string {
|
||||
func listReplicas(cmd *cobra.Command, client func() *ctlClient) ([]adminapi.ReplicaView, error) {
|
||||
var reps []adminapi.ReplicaView
|
||||
if err := client().get(cmd.Context(), "/api/v1/replicas", &reps); err != nil {
|
||||
return ""
|
||||
}
|
||||
err := client().get(cmd.Context(), "/api/v1/replicas", &reps)
|
||||
return reps, err
|
||||
}
|
||||
|
||||
// replicaKey is the engine key of the replica serving at addr, or "" when
|
||||
// addr is not a replica's (the gateway's, say).
|
||||
//
|
||||
// Matched by scheme, host and port rather than by the whole URL, so the same
|
||||
// lookup serves the target, which is a replica's base URL, and --metrics,
|
||||
// which is a path under it: /metrics, or /prometheus/metrics on TensorRT-LLM.
|
||||
func replicaKey(reps []adminapi.ReplicaView, addr string) string {
|
||||
for _, rep := range reps {
|
||||
if sameEndpoint(rep.Endpoint, target) {
|
||||
if sameOrigin(rep.Endpoint, addr) {
|
||||
return rep.EngineKey
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sameOrigin(a, b string) bool {
|
||||
ua, err := url.Parse(a)
|
||||
if err != nil || ua.Host == "" {
|
||||
return false
|
||||
}
|
||||
ub, err := url.Parse(b)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return ua.Scheme == ub.Scheme && ua.Host == ub.Host
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
|
||||
)
|
||||
|
||||
// benchCluster is a gateway taking the client's key, a llama.cpp replica
|
||||
// whose /metrics takes only its engine key, and an admin API that lists the
|
||||
// replica with that key, as the control plane does.
|
||||
type benchCluster struct {
|
||||
gateway, engine, admin *httptest.Server
|
||||
metricsAuth atomic.Value
|
||||
}
|
||||
|
||||
func newBenchCluster(t *testing.T) *benchCluster {
|
||||
t.Helper()
|
||||
c := &benchCluster{}
|
||||
c.metricsAuth.Store("")
|
||||
c.gateway = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer client" {
|
||||
http.Error(w, "no", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n")
|
||||
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"b\"}}]}\n\n")
|
||||
fmt.Fprint(w, "data: [DONE]\n\n")
|
||||
}))
|
||||
c.engine = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c.metricsAuth.Store(r.Header.Get("Authorization"))
|
||||
if r.URL.Path != "/metrics" || r.Header.Get("Authorization") != "Bearer engine-key" {
|
||||
http.Error(w, `{"error":"Invalid API Key"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, "llamacpp:requests_processing 1\nllamacpp:requests_deferred 3\n")
|
||||
}))
|
||||
c.admin = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode([]adminapi.ReplicaView{
|
||||
{ID: "r1", Model: "m", Profile: "cpu", Endpoint: c.engine.URL, EngineKey: "engine-key"},
|
||||
})
|
||||
}))
|
||||
t.Cleanup(func() { c.gateway.Close(); c.engine.Close(); c.admin.Close() })
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *benchCluster) bench(t *testing.T, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
t.Setenv("LLMGW_ADMIN_TOKEN", "t")
|
||||
asJSON := false
|
||||
cmd := newBenchCmd(func() *ctlClient { return newCtlClient(c.admin.URL) }, &asJSON)
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&out)
|
||||
cmd.SetArgs(append([]string{"m", "--concurrency", "1", "--duration", "1500ms", "--ttft-p99", "1m", "--tpot-p99", "1m"}, args...))
|
||||
err := cmd.ExecuteContext(context.Background())
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func TestBenchReadsAGuardedEnginesMetricsWithTheKeyTheAdminAPIGives(t *testing.T) {
|
||||
// Through the gateway with a client's key, and the replica's metrics on
|
||||
// the side: the client's key is not the engine's, and the engine's is
|
||||
// found by the replica at --metrics' address, not at the target's.
|
||||
c := newBenchCluster(t)
|
||||
out, err := c.bench(t, "--target", c.gateway.URL, "--key", "client",
|
||||
"--metrics", c.engine.URL+"/metrics", "--engine", "llamacpp")
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, out)
|
||||
}
|
||||
if got := c.metricsAuth.Load(); got != "Bearer engine-key" {
|
||||
t.Errorf("metrics read with %q", got)
|
||||
}
|
||||
if !strings.Contains(out, "target_waiting: 3") {
|
||||
t.Errorf("the queue depth read was not suggested:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBenchSaysWhyAnEnginesMetricsCannotBeRead(t *testing.T) {
|
||||
// A key the engine refuses fails the run before any load, saying where
|
||||
// the right one comes from, rather than reporting an idle engine.
|
||||
c := newBenchCluster(t)
|
||||
out, err := c.bench(t, "--target", c.gateway.URL, "--key", "client",
|
||||
"--metrics", c.engine.URL+"/metrics", "--engine", "llamacpp", "--metrics-key", "wrong")
|
||||
if err == nil || !strings.Contains(err.Error(), "refused the key") || !strings.Contains(err.Error(), "--metrics-key") {
|
||||
t.Fatalf("expected the refusal explained, got %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 469 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user