diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index 30ec1ac43339..e54713bad748 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -1024,6 +1024,90 @@ jobs: llama-turboquant-macos-arm64.tar.gz retention-days: 14 + # Decision mode (DECISION.md): C++ unit tests and the offline server contract + # tests. Warnings are errors on the Linux leg only. Builds only what the + # tests need and no archive, so publish-dev-latest does not wait for it. + decision-tests: + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, windows-2025] + runs-on: ${{ matrix.os }} + + steps: + - name: Clone + uses: actions/checkout@v6 + + - name: ccache + uses: ggml-org/ccache-action@v1.2.21 + with: + key: turboquant-decision-tests-${{ matrix.os }} + evict-old-files: 1d + + - name: Build (Linux) + if: ${{ runner.os == 'Linux' }} + run: | + cmake -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DGGML_NATIVE=OFF \ + -DLLAMA_CURL=OFF \ + -DLLAMA_OPENSSL=OFF \ + -DLLAMA_BUILD_SERVER=ON \ + -DLLAMA_BUILD_TOOLS=ON \ + -DLLAMA_BUILD_TESTS=ON \ + -DLLAMA_BUILD_EXAMPLES=OFF \ + -DLLAMA_FATAL_WARNINGS=ON + cmake --build build --config Release -j $(nproc) \ + --target test-decision-json test-decision-request test-decision-calib test-decision-router test-decision-reference test-laya-convert llama-server llama-laya-cli llama-laya-convert + + # same toolchain as the server.yml Windows job + - name: Build (Windows) + if: ${{ runner.os == 'Windows' }} + shell: cmd + run: | + cmake -B build -G "Ninja Multi-Config" ^ + -DCMAKE_TOOLCHAIN_FILE=cmake/x64-windows-llvm.cmake ^ + -DGGML_NATIVE=OFF ^ + -DLLAMA_CURL=OFF ^ + -DLLAMA_OPENSSL=OFF ^ + -DLLAMA_BUILD_SERVER=ON ^ + -DLLAMA_BUILD_TOOLS=ON ^ + -DLLAMA_BUILD_TESTS=ON ^ + -DLLAMA_BUILD_EXAMPLES=OFF + cmake --build build --config Release -j %NUMBER_OF_PROCESSORS% ^ + --target test-decision-json test-decision-request test-decision-calib test-decision-router test-decision-reference test-laya-convert llama-server llama-laya-cli llama-laya-convert + + # decision + the checkpoint converter (test-laya-convert, test-decision-checkpoint-cli); the Python + # cross-check (label python) needs torch + transformers 5.17 and runs locally (make_tiny_hf_laya.py --check) + - name: Unit tests + run: ctest --test-dir build -C Release -R "decision|laya-convert" -LE python --output-on-failure + + - name: Python setup + uses: actions/setup-python@v6 + with: + python-version: '3.11' + pip-install: -r tools/server/tests/requirements.txt + + # the Python reference of the router rendering and the calibration tools; the golden file + # that test-decision-reference reads must match a fresh run of its generator + - name: Reference tests + shell: bash + env: + PYTHONIOENCODING: 'utf-8' + run: | + python -m pip install jsonschema + python tests/decision/gen_router_golden.py --check + python -m pytest -v tests/decision/test_reference.py + + # offline: the tests generate a tiny random laya GGUF + - name: Server tests + shell: bash + env: + PYTHONIOENCODING: ':replace' + run: | + cd tools/server/tests + python -m pytest -v unit/test_decision.py + # Republishes the rolling `dev-latest` prerelease with whatever archives the # build jobs produced. Runs even when some jobs fail (if: always()) so a # broken backend never blocks the others from shipping to testers — the diff --git a/CHANGELOG.md b/CHANGELOG.md index b53ef5aa7992..ad0d2c1393dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,136 @@ commit list underneath. Releases before `b10269-1.5.0` predate this file; see the git history. +## Unreleased + +### Added + +- **Decision models in `llama-server`** (`--decision`, see `DECISION.md`). A + separate server mode for Jev-class decision models: no chat routes, one CPU + worker, calibrated probabilities instead of generated text. + - `POST /v1/systemone`: TypeSafe-compatible typed questions (noul, choice, + score) over a state. + - `POST /v1/router/score`: executor cards in, an independent calibrated + `p_success` per candidate out (Platt calibration from the model's spec; 501 + unless calibrated or `--decision-allow-uncalibrated`). + - `/health`, `/props` (`decision` block with limits, plan and calibration), + `/v1/models` capabilities, an error envelope with stable reason codes, and a + bounded queue (429 + `Retry-After`). + - New flags: `--decision`, `--decision-spec`, `--decision-plan`, + `--decision-queue`, `--decision-max-items`, `--decision-allow-uncalibrated`, + `--decision-debug`. +- **Laya decision model support** (`tools/laya`, `llama-laya-cli`), based on + upstream PR #29363: converter for `laya-multilingual`, GGUF arch `laya`, a + self-contained CPU graph, and a tokenizer that matches the HF tokenizer exactly. + Inputs follow the laya 0.3.21 PyTorch reference. On a 2605-question parity set + the F32 GGUF matches the reference to 6.6e-4 in scorer logits with identical + answers; F16 changes 2 answers, both near-ties. +- **English Laya checkpoints** `convaiinnovations/laya` (512 ctx) and + `laya-typed-decisions` (1024 ctx), ModernBERT-large encoder: the converter + handles them, `tools/laya` gets a second tokenizer (ModernBERT / OLMo + byte-level BPE with NFC, 0 mismatches against the HF tokenizer on 13.6k strings, + 10.7k of them English-heavy), the special ids come from the tokenizer (`[CLS]` + 50281, `[MASK]` 50284 with lstrip; a GGUF whose mask id is not + `laya.marker_token_id` no longer loads), and the checkpoint's + `temperature_by_options` buckets are stored in the GGUF and applied like the + reference. On 1491 English questions the F32 GGUFs match the PyTorch reference + with identical answers (max |dlogit| 4.2e-4 and 6.8e-5). F16 through the server + keeps every answer with the `blas` kernels, the macOS default (1.3e-2 and + 4.6e-3); with the `default` ggml kernels, the Linux and Windows default, it + reaches 0.24 and 3.8e-2 with one near-tie answer change on `laya` + (`llama-laya-cli`, which packs the questions of an item: 0.44, two changes). About 2.2x the compute of `laya-multilingual` per token on an + M4 Max (router N=1 221 vs 111 ms at `-t 12`) and 944 vs 519 MiB footprint in + F16 (see `DECISION.md`, "English checkpoints"). + `laya-multilingual` results are unchanged bit for bit with the `default` + kernels (`llama-laya-cli`, and the server with `--decision-kernels default`). +- **Model metadata `decision.spec`**, stamped into a GGUF without reconversion + with `gguf-py/gguf/scripts/gguf_decision_spec.py`. A calibration marked + required must cover every question type and option count, or the model does not + load. +- **`llama-decision-bench`** and `scripts/bench-decision.sh`: in-process latency + (p50/p95/p99 per phase), CPU seconds, memory and logits-hash determinism of + decision requests, plus server time-to-ready and first request after idle, with + the machine's power source and load recorded next to the numbers. +- **Router training and calibration tools** (`DECISION.md`, "Training and + calibration tools"): `tools/decision/reference.py`, a stdlib Python reference of + the router input (strict JSON, executor cards, `card-v1`, router state, + `escape-control` from the GGUF vocabulary), checked against the engine byte for + byte on 540 golden requests (`test-decision-reference`) and through the server's + render route; the card as JSON Schema; `scripts/fit-router-calibration.py` + (collects the server's raw router logits, fits the Platt `router.calibration` + block with bootstrap-interval ECE / Brier before and after, and prints the + `gguf_decision_spec.py` command instead of touching the GGUF); and + `scripts/router-baselines.py` (pass-rate heuristic and logistic regression on + card metrics, same data format and metrics). +- **Decision CPU levers** (laya engine): `token_embd` stays in a read-only file + mapping and the GGUF metadata is freed after the load (Q8_0 with the `default` + kernels: RSS 637 -> 262 MiB and footprint 764 -> 389 MiB after load; the macOS + default `auto` adds the BLAS backend, 408 MiB; results bitwise unchanged); one persistent ggml + threadpool; a warm-up pass at load (`--no-warmup` skips it); `--load-mode mlock` + / `mmap+mlock` lock the model; the default thread count is the performance cores + (Windows: highest `EfficiencyClass`); `KMP_BLOCKTIME=0` / `OMP_WAIT_POLICY=passive` + unless set. New `--decision-kernels auto|default|repack|blas|repack+blas` (also + spec `plan.kernels`, shown in `/props.decision.plan.kernels`): `auto`, the new + default, uses the Accelerate BLAS backend on macOS, which is 2-2.3x faster, uses + 3-4x fewer CPU seconds and is closer to the PyTorch reference than the ggml kernels + for F16 and Q8_0 (F16: 2604/2604 argmax agreement); `repack` enables + the CPU repack buffers for quantized weights. The BLAS backend runs with + min(`-t`, 8) threads (it starts new threads for every weight conversion; at + `-t 12`, 12 threads were up to 10% slower than 4 or 8 on `laya-multilingual`, and + 4 was 3-5% slower than 8 on the larger English encoder). `llama-laya-cli` gets `--kernels`, + `--no-mmap` and `--mlock` and keeps the `default` kernels. `/props.decision` + also shows the BLAS threads and the weight bytes loaded / mapped / repacked. + +- **Laya checkpoints without Python.** `llama-server --decision -m ` and + `llama-laya-cli -m ` take a laya Hugging Face checkpoint directory (an HF + snapshot works as it is). The first start converts it into a GGUF cache, + later starts reuse it ("converted" / "cache hit" in the log), and the cached + GGUF is loaded exactly like `-m FILE`. The cache lives in + `$LLAMA_CACHE/laya/gguf-cache` or the user cache (macOS + `~/Library/Caches/llama.cpp/laya/gguf-cache`, Linux `~/.cache/...`, Windows + `%LOCALAPPDATA%\...`), never in the checkpoint; new flags + `--decision-convert-cache DIR` and `--decision-convert-type f16|f32` + (default f16; the converter's q8_0 is not the precision-protected Q8_0 recipe, + use `tests/laya/quantize.sh` on the f16 GGUF). The cache key covers the + converter version, the outtype and the files the converter can read (root, + `encoder/`, `tokenizer/`; files up to 8 MiB by content, larger ones such as the + weights by size + mtime + symlink target). Writes are atomic and synced to disk. + `/props.decision` shows `source` (`gguf` / `checkpoint-dir`) and `cache_path`. + The conversion is the new `llama-laya-convert` (C++, no Python; also + usable on its own), byte-identical to `convert_hf_to_gguf.py` for all three + published checkpoints in f32, f16 and q8_0, with and without `--model-name` + (18 of 18 files), and 6-19x faster (0.2-1.8 s per f16 file). A first start of + `laya-multilingual` takes about 1.2-1.3 s instead of 0.3 s and peaks at about + 515 MiB instead of 372 MiB RSS. + +### Notes + +- Decision mode runs on the CPU backend only; start it with `--device none` next + to a GPU chat server. +- A laya GGUF started without `--decision` fails fast with a hint. +- **Decision server numerics on macOS change**: the default kernels there are now + `cpu+blas` (Accelerate), so macOS server logits differ slightly from Phase 1 and + from Linux and Windows, where `auto` stays on the ggml kernels and nothing + changes. `--decision-kernels default` restores the Phase 1 numerics bit for bit on + every platform. An explicit `--decision-kernels blas` fails at load on a + build without a BLAS backend. +- Recommended laya precision is F16: Q8_0 is about 1.5x faster but changes about + 2% of answers on the parity set. +- Windows: decision model, spec and input paths may contain non-ASCII characters + (for example a Cyrillic user folder), and `llama-laya-cli` prints LF line ends on + every platform, so its output compares byte for byte with the golden files. +- A router calibration fitted with `scripts/fit-router-calibration.py` pins the + kernels its logits came from (`plan.kernels`): one fitted on a Mac pins `blas` + and needs a BLAS build elsewhere. Collect on the target platform, or start the + collecting server with `--decision-kernels default`. + +### Changed + +- **Qwen3.5 / Qwen3-Next / Kimi-Linear / Kimi-K3 / BailingMoeV3 numerics:** the + Gated DeltaNet q/k normalization now uses upstream's `rsqrt(sum(x^2) + eps)` + form (upstream 5fdfa6282). Logits of these models shift slightly; results + measured on earlier builds are not bit-identical. + ## b10269-1.6.0 ### Added diff --git a/DECISION.md b/DECISION.md new file mode 100644 index 000000000000..124d8ce64c7f --- /dev/null +++ b/DECISION.md @@ -0,0 +1,1197 @@ +# Decision mode (`llama-server --decision`) + +`llama-server --decision -m model.gguf` (or `-m `, see "Loading a Hugging +Face checkpoint directly") serves a *decision model*: a small model that +returns calibrated probabilities over a fixed set of options in one forward pass, with +no generation. It is a separate process role of this fork. It has no chat routes, no +slots, no KV cache and no web UI. + +Engines (layouts): + +| layout | models | runtime | status | +|---|---|---|---| +| `laya` | Laya family: `laya-multilingual` (mmBERT-base encoder), `laya` and `laya-typed-decisions` (English, ModernBERT-large encoder), each with the marker head | `tools/laya`, own ggml graph, CPU only | done | +| `semif-letters` | Arbiter-4B, JevK5 (Qwen3.5 + letter readout) | libllama | not supported yet: load fails with a clear error | + +Code map: + +| path | role | +|---|---| +| `tools/server/server-decision.{h,cpp}` | HTTP routes, FIFO worker, error envelope, info routes | +| `tools/decision/` | static library: py-json, `decision.spec`, request checks, calibration, executor cards, engines, laya input building (`laya-decide`), the GGUF cache for `-m ` (`decision-checkpoint.h`) | +| `tools/laya/` | laya runtime (port of upstream PR #29363; links only ggml), `llama-laya-cli`, and `llama-laya-convert` (HF checkpoint -> GGUF without Python, `laya-convert.h`) | +| `gguf-py/gguf/scripts/gguf_decision_spec.py` | get / set / verify `decision.spec` in a GGUF | +| `tests/test-decision-*.cpp`, `tests/decision/` | C++ unit tests, golden files, tiny model generator | +| `tools/server/tests/unit/test_decision.py` | server contract tests (offline) | +| `tools/decision/decision-bench.cpp`, `tests/decision/bench/`, `scripts/bench-decision*` | `llama-decision-bench`, its request suite, the KPI script and report (see Benchmark) | + +## Quick start + +```bash +cmake -B build -DLLAMA_BUILD_TESTS=ON +cmake --build build -j --target llama-server llama-laya-cli +./build/bin/llama-server --decision -m laya-multilingual-Q8_0.gguf --device none -t 4 --port 8090 + +curl -s localhost:8090/props | jq .decision +curl -s localhost:8090/v1/systemone -H 'content-type: application/json' \ + -d '{"state":"Billed twice, please refund","questions":{"refund":{"type":"noul","instructions":"Asks for money back?"}}}' +``` + +Start-up order: the HTTP server starts first (so `/health` answers 503 while the model +loads), then a checkpoint directory is converted (or found in the cache), then the spec and +the engine load, then the server is ready. A load error stops +the process with exit code 1. + +## Flags + +Environment variables use the `LLAMA_ARG_DECISION_*` names. + +| flag | default | meaning | +|---|---|---| +| `--decision` | off | decision mode. Requires `-m FILE` or `-m DIR` (a laya Hugging Face checkpoint directory, converted once into a GGUF cache); `-hf`, `-dr` and `-mu` are rejected (without `-m` the server would start in router mode). Explicit only: a stamped GGUF never switches mode on its own. | +| `--decision-convert-cache DIR` | `$LLAMA_CACHE/laya/gguf-cache`, else the user cache + `llama.cpp/laya/gguf-cache` | `-m DIR` only: where the converted GGUF is kept (never in the checkpoint directory). See "Loading a Hugging Face checkpoint directly" | +| `--decision-convert-type T` | `f16` | `-m DIR` only: `f16` or `f32`. The converter's `q8_0` is not the precision-protected recipe (see "Converting without Python"); for Q8_0 quantize the f16 GGUF with `tests/laya/quantize.sh` | +| `--decision-spec FILE` | from the GGUF | JSON that replaces the embedded `decision.spec` as a whole. A bare Arbiter `calibration.json` (`{"temperature": x}` or `{"temperature": {...}}`) is accepted too: it is a required calibration, keeps the layout clamp (laya [0.5, 5]) and replaces the `laya.temperature` calibration; its `calibration.version` is its own `version` field (else `cal-`), never `gguf:laya.temperature`. | +| `--decision-plan NAME` | from the spec | compute plan, laya: `sequential`, `packed` (systemone only; the router always runs `sequential`) | +| `--decision-kernels NAME` | from the spec, then `auto` | matmul kernels, laya: `auto` (`blas` when the BLAS backend is Accelerate, i.e. on macOS; else `default`), `default` (ggml CPU kernels, the Phase 1 numerics), `repack` (CPU repack buffers for quantized weights), `blas` (BLAS backend in the scheduler), `repack+blas`. Kernels change the logits slightly, so the default logits on macOS differ from those on Linux and Windows; `default` gives the same numerics everywhere. An explicit `blas` / `repack+blas` fails at load on a build without a BLAS backend. See "CPU kernels and memory" | +| `--decision-queue N` | 4 | requests that may wait while one runs; more get 429 | +| `--decision-max-items N` | 16 | questions per `/v1/systemone` request, candidates per `/v1/router/score` request (router is also capped at 16) | +| `--decision-allow-uncalibrated` | off | serve `/v1/router/score` without a router calibration | +| `--decision-debug` | off | raw logits and token ids in answers, `POST /v1/decision/render`, request logging, test delays (below) | + +Reused: `-m`, `-a/--alias` (default: the model file name without its directories and a trailing `.gguf`, for `-m DIR` the directory name; the same name as the default spec `model_id`), `--host`, `--port`, `--api-key` / `LLAMA_API_KEY`, `-t` +(engine threads, fixed at load; default: the performance cores, see below), `--load-mode` +(`mmap`, the default, keeps `token_embd` in a read-only file mapping; `none` / `dio` load it; +`mlock` / `mmap+mlock` also lock the model in RAM, and a failed lock only warns), +`--mlock` / `--no-mmap` (deprecated spellings of `--load-mode`), `--no-warmup` (skip the +warm-up forward pass at load), `--metrics`, `--timeout`, SSL flags. `--device` is +ignored by the laya engine (CPU only). + +Ignored with a warning: `--parallel`, `-ctk/-ctv`, `--ctx-checkpoints`, `--spec-*` / `-md`, +`--embedding` / `--pooling`, `--mmproj`, `--lora`, `--sleep-idle-seconds`, +`--mcp-servers-*`, `--tools`, `--ui-mcp-proxy`, `--path`. The UI is always off. + +A laya GGUF or checkpoint directory started without `--decision` fails fast with a hint. `--decision` inside a +router-mode child instance is rejected: run a separate process. + +## API + +Auth is the usual middleware: `Authorization: Bearer ` when `--api-key` is set. +`/health`, `/v1/health`, `/models` and `/v1/models` stay public. Probabilities are +doubles and are never rounded. Answers and scores keep the request order. + +### `POST /v1/systemone` + +A superset of TypeSafe `systemone`: + +```json +{"model": "optional, ignored", + "state": "", + "questions": { + "refund": {"type": "noul", "instructions": "Asks for money back?"}, + "topic": {"type": "choice", "instructions": "Topic?", "criteria": {"billing": "payments", "other": null}}, + "tone": {"type": "choice", "instructions": "Tone?", "criteria": ["calm", "angry"]}, + "sev": {"type": "score", "instructions": "Severity?", "criteria": ["low", "mid", "high"]}, + "urgent": {"type": "noul", "instructions": "Urgent?", "criteria": {"True": "today"}, "labels": {"false": "later", "true": "now"}}}, + "truncation": "allow"} +``` + +Questions of the `laya` layout are read exactly as the Laya reference reads them (laya +0.3.21 `Agent._check_question`, `Agent._to_internal`, `common.render_options`; +`laya_question_parse` in `tools/decision/laya-decide.cpp`, shared with `llama-laya-cli`): + +- `state` is required: absent or `null` is 400 `INVALID_REQUEST` (`param` `state`), as in + the reference server (the text `null` would otherwise be scored). A string is used as is, + anything else as `json.dumps(state, ensure_ascii=False)`. A list state is cut from the + left (the newest turns stay), anything else from the right. +- `questions` is an object; an empty one gets `"answers": {}` and zero usage. +- `instructions` must be present (`EMPTY_INSTRUCTIONS` when it is not) and may be any JSON + value: blank text is kept, a non-string is `json.dumps(value, ensure_ascii=False)`. +- `choice` criteria: an object `{label: description}` or a list of labels, with at least + one option. The option text is `str(label)`, plus `": " + description` unless the + description is `null` or `""`. A list label must be a string, number or bool; `null`, a + nested value or a label equal to an earlier one by Python `==` (`1`, `1.0` and `true` are + one label) is 400 `UNSUPPORTED_CRITERIA_VALUE`. Answer keys are the labels as `json.dumps` + writes dict keys (`3` -> `"3"`, `true` -> `"true"`, `2.5` -> `"2.5"`), and `choice` is the + label as given (a number stays a number). +- `score` criteria: a non-empty list of levels, none `null`; option text `level i: `. +- `noul` criteria: absent, `null` or an object keyed `true` / `false` in any case (`True`, + `FALSE`; a later duplicate wins); any other key is 400 `INVALID_NOUL_CRITERIA`. `labels` + (noul only) is `null` or exactly `{"false": str, "true": str}`, stripped like Python + `str.strip` (so U+2028 and U+0085 count as space), non-empty and distinct; it replaces the + words `false` / `true` in the option texts. Bad labels are 400 `INVALID_NOUL_CRITERIA` + (`param` `questions..labels`), labels on a choice or score question 400 + `UNSUPPORTED_CRITERIA_VALUE`. +- A structured description or level is compact JSON (`json.dumps`, `", "` / `": "`). +- `truncation`: `"allow"` (default) or `"error"`. + +Where this differs from the TypeSafe / arbiter rules (`arbiter/prompt.py` +`normalized_question`), the laya layout follows the reference: blank or non-string +instructions are accepted, one choice option or score level is a valid question, list +labels do not collapse (`["a", "a"]` is an error instead of one option; `null` is an error +instead of `"None"`; `["1", 1]` are two labels), unknown noul criteria keys are an error +instead of being ignored, `labels` is accepted, a missing state is an error instead of the +text `null`, and empty `questions` is not an error. Two limits the reference does not have +stay: at most 20 options per question (`TOO_MANY_OPTIONS`, the marker slots of the laya +graph) and two labels with the same answer key (`["1", 1]`, `["true", true]`) are 400 +`UNSUPPORTED_CRITERIA_VALUE`, since a JSON object cannot hold both keys (the reference +writes the key twice). Other layouts keep the TypeSafe rules: list entries become keys +through Python `str()` and collapse (`dict.fromkeys`), at least two options, non-blank +string instructions. + +Response: + +```json +{"model": "tiny-laya", + "answers": { + "refund": {"type": "noul", "noul": 0.93, "confidence": 0.93}, + "topic": {"type": "choice", "choice": "billing", "probabilities": {"billing": 0.97, "other": 0.03}, "confidence": 0.81}, + "sev": {"type": "score", "score": 1.4, "probabilities": {"0": 0.2, "1": 0.2, "2": 0.6}, "legend": {"0": "low", "1": "mid", "2": "high"}, "confidence": 0.1}}, + "usage": {"input_tokens": 138, "output_tokens": 0, "evaluated_tokens": 138}, + "latency_ms": 42.1, + "timings": {"queue_ms": 0.1, "render_ms": 0.4, "compute_ms": 41.5}, + "warnings": [], + "runtime": {"layout": "laya", "format": "laya-v1", "plan": "sequential", "spec_sha256": "...", "calibration": "..."}} +``` + +- `noul` = P(true). `choice` = the first argmax in criteria order (laya: the label as + given). `score` = sum(i * p_i); `legend` holds the request levels as given. +- `confidence` follows `spec.confidence`: `laya` (noul: max(p, 1 - p); choice/score: + 1 - H / ln K), `typesafe` (1 - H / ln K for all), `max_p`. +- Probabilities are `softmax(logits / T)` in double. T comes from the spec calibration + (see below); an uncalibrated model uses T = 1, and so does a calibration that is not + `required` for a question type or option count it has no temperature for. +- `input_tokens` sums the full prompt lengths; `evaluated_tokens` counts what was computed. +- `warnings`: `state_truncated` (laya cuts the state as the reference does: a list from the + left, `state_ids[len - room:]`, anything else from the right), `options_truncated`, `instructions_truncated`. + With `"truncation": "error"` any of these cuts is a 422 instead (`STATE_TRUNCATED`, + `OPTIONS_TRUNCATED`, `PROMPT_TOO_LONG` with `param` `questions..instructions`). +- With `--decision-debug` every answer has `debug: {logits, temperature, tokens, n_state, n_state_cut, options_cut, head_cut}`. + +### `POST /v1/router/score` + +Scores each candidate executor independently: `p_success` values do not sum to 1, and +there is no threshold or argmax. Routing policy lives in the caller. + +```json +{"task": "Extract invoice number, date and total", + "criterion": "All three fields exact; nothing invented.", + "candidates": [ + {"id": "local/qwen3.5-4b-q4_k_m", + "card": {"schema": "atomic.executor-card/1", "name": "Qwen3.5-4B local", "kind": "local", + "description": "4B general model on this laptop (Q4_K_M)", + "checks": [ + {"skill": "field extraction", "status": "measured", "passed": 188, "total": 200, + "criterion": "exact match", "source": "atomic-evals/extract", "version": "2026-09"}, + {"skill": "long-document QA", "status": "missing", "source": "atomic-evals/longqa", "version": "2026-09"}]}}], + "truncation": "allow"} +``` + +```json +{"object": "router.scores", "model": "...", + "scores": [{"id": "local/qwen3.5-4b-q4_k_m", "p_success": 0.9412, "logit": 2.78, "calibrated": true, + "input_tokens": 431, "truncated_tokens": 0}], + "usage": {"input_tokens": 431, "output_tokens": 0, "passes": 1}, + "latency_ms": 212.4, "timings": {"queue_ms": 0.1, "render_ms": 0.6, "compute_ms": 211.5}, + "runtime": {"layout": "laya", "format": "laya-v1", "plan": "sequential", "spec_sha256": "...", "calibration": "platt"}, + "warnings": []} +``` + +Card rules (`atomic.executor-card/1`): `name` and `kind` are required strings, +`description` is optional; at most 32 `checks`; every card string is at most 4096 bytes. A `measured` check needs integer `passed` +and `total` with 0 <= passed <= total and total >= 1. A `missing` check has no numbers. +Floats are rejected, so Python and C++ render the same text. Unknown fields are ignored +and reported in `warnings`. Candidate ids match `[A-Za-z0-9._:/@+-]{1,128}` and are unique. +`tools/decision/schema/executor-card-v1.schema.json` has the card as JSON Schema, and +`tools/decision/reference.py` has the Python rules and rendering (see "Training and calibration tools"). + +laya mapping: one `noul` sequence per candidate (cost: N encoder passes). The question comes +from `spec.router.question`. Without one (no `router` block, or no `question` in it) it is +the built-in question `{"type": "noul", "instructions": "Will the executor meet the success +criterion on this task?", "criteria": {"true": "meets the criterion", "false": "does not meet +the criterion"}}`. A spec question without `criteria` gets these built-in criteria. The +criteria are part of the prompt, so a router calibration is only valid for the question it +was fitted with. The state is the `card-v1` text, then the criterion, then the task, so a cut +only hits the end of the task (`truncated_tokens`, warning `task_truncated`): + +``` +executor: +kind: +description: +checks: +- : passed of ; criterion: ; source: +- : not measured; source: + +success criterion: + +task: +``` + +Card strings are made single-line (control characters become spaces, space runs collapse) +and absent optional parts are left out; a card without checks renders `checks: none`. + +A card longer than `router.max_card_tokens` tokens is a 422 `CARD_TOO_LONG`. Without that +key the limit is 3/8 of the model sequence length (384 tokens for `laya-multilingual`, 1024); +`0` turns the limit off. `/props.decision.limits.max_card_tokens` shows the value in use. + +Special-token text (`spec.special_tokens`) in the state: the mask literal (``) always +becomes a space, as in the Laya reference (`mask-to-space`, the default). With +`escape-control` the card, criterion and task also have every CONTROL-token string of the +vocabulary (`tokenizer.ggml.token_type` 3) and every `` added token replaced by one +space, so user text cannot inject structure. For `laya-multilingual` that set is ``, +``, ``, ``, ``, `<2mass>`, `[@BOS@]`, ``, +`` and `` ... ``; other added tokens (newline and tab runs, +HTML tags) stay tokens. For the English checkpoints it is `[UNK]`, `[CLS]`, `[SEP]`, `[PAD]`, +`[MASK]`, `<|padding|>`, `<|endoftext|>` and `[unused0]` ... `[unused82]`; the space runs and +`|||IP_ADDRESS|||`, `|||EMAIL_ADDRESS|||`, `|||PHONE_NUMBER|||` stay tokens. The strings cannot overlap and a space cannot form a new one, so +replacing them one after another in any order gives the same text (`reference.py` can use +`str.replace`). Token counts for `CARD_TOO_LONG` and `CRITERION_TOO_LONG` use the same +replacement. Systemone questions and states always use `mask-to-space`. + +`logit` is the raw z = s_true - s_false. With a router calibration, +p = sigmoid(a * z + b) (`spec.router.calibration`, Platt). Without one the route answers +501 `ROUTER_NOT_CALIBRATED` to every request, before the body is read. With `--decision-allow-uncalibrated` it answers +`calibrated: false` and p = sigmoid(z), the zero-shot baseline. The router always runs +plan `sequential` (`runtime.plan`, `/props.decision.plan.router`), even with +`--decision-plan packed`: adding or removing candidates never changes the other +candidates' scores (bitwise). + +### Info routes + +- `GET /health`, `/v1/health`: `{"status": "ok", "ok": true, "model": ..., "layout": ...}`. +- `GET /v1/models`, `/models`: one entry with `capabilities` (`decision`, `systemone`, plus + `router_score` only when a router calibration exists) and + `decision: {api_version, layout, model_id, model_version}`. +- `GET /props`: `model_alias`, `model_path`, `build_info`, and a `decision` block with + `api_version` (1), `endpoints`, `layout`, `format`, `model_id`, `model_version`, + `spec_version`, `spec_sha256`, `spec_source` (`gguf`, `file` or `default`), + `question_types`, `limits` (`max_questions`, `max_candidates`, `max_options`, + `max_checks`, `max_tokens`, `max_card_tokens`, `max_card_field_bytes`, `max_body_bytes`), `confidence`, + `calibration {method, calibrated, version}`, `router {available, calibrated, method, card_schema, card_renderer}`, + `plan {name, router, plans, n_threads, kernels, n_threads_blas, state_split, recipe, fa, n_batch, n_ubatch}` + (`router`: the plan of `/v1/router/score`; `kernels`: `cpu`, `cpu+repack`, `cpu+blas` or + `cpu+repack+blas`; `n_threads_blas`: threads of the BLAS backend, 0 without it; `state_split`: + router state pieces are tokenized separately, see Scheduling), + `memory {weights_loaded_bytes, weights_mapped_bytes, weights_repacked_bytes}` (where the + weights went, see "CPU kernels and memory"), `device`, `kv_type`, + `queue_capacity`, `input_contract`, `special_tokens`, `debug`, + `source` (`gguf` for `-m FILE`, `checkpoint-dir` for `-m DIR`), `cache_path` (the cached GGUF + that was loaded; `null` for `gguf`) and `checkpoint` (`null` for `gguf`, else + `{dir, cache_dir, key, outtype, cache_hit, convert_ms, converter}`). `model_path` is `-m` as given. +- `GET /metrics` (only with `--metrics`): Prometheus counters `llamacpp:decision_requests_total`, + `_errors_total`, `_rejected_total`, `_items_total`, `_tokens_total`, + `_compute_seconds_total` and the gauge `llamacpp:decision_queue_waiting`. +- `POST /v1/decision/render` (only with `--decision-debug`): takes a systemone or router + body (router if it has `candidates`) and returns per item the question, keys, state, token + ids and cut info, without compute. + +A client that checks for decision support: `/health` 200 -> `/v1/models` has `decision` -> +`/props.decision.api_version == 1`. + +### Errors + +Decision handlers answer `{"error": {"code", "type", "reason", "message", "param"?}}`; +`param` is the JSON path of the bad field. + +| HTTP | reason | +|---|---| +| 400 | `MALFORMED_JSON`, `BODY_NOT_OBJECT`, `INVALID_REQUEST` (missing `questions` / `task` / `criterion` / `candidates`, laya: missing or `null` `state`, bad `truncation`), `UNKNOWN_QUESTION_TYPE`, `EMPTY_INSTRUCTIONS` (laya: no `instructions` key), `TOO_FEW_OPTIONS`, `TOO_MANY_OPTIONS`, `INVALID_NOUL_CRITERIA`, `UNSUPPORTED_NUMBER` (NaN/Infinity, integers outside int64/uint64, float overflow), `UNSUPPORTED_CRITERIA_VALUE`, `TOO_MANY_QUESTIONS`, `INVALID_CARD` (also a card string over 4096 bytes), `DUPLICATE_CANDIDATE_ID`, `INVALID_CANDIDATE_ID`, `TOO_MANY_CANDIDATES` | +| 413 | `BODY_TOO_LARGE` (body over 1 MiB, checked in the handler) | +| 422 | `PROMPT_TOO_LONG` (instructions cut with `"truncation": "error"`; letters engine: prompt too long), `CARD_TOO_LONG` (card over `router.max_card_tokens`), `CRITERION_TOO_LONG` (card + criterion do not fit), `OPTIONS_TRUNCATED` (option markers cut, or any option cut with `"truncation": "error"`), `STATE_TRUNCATED` (with `"truncation": "error"`) | +| 429 | `OVERLOADED`, with `Retry-After: 1` | +| 500 | `INTERNAL` | +| 501 | `ROUTER_NOT_CALIBRATED` | +| 503 | `UNAVAILABLE`: an accepted request was not run or not finished because the server is stopping or the client left | + +Not from decision handlers, so without `reason`: 401 (API key middleware), 503 while +loading (state middleware), 404 for unknown routes (httplib rewrites any 404 body, so +decision handlers never use 404), and 413 for bodies over httplib's 100 MB limit. httplib +adds `Connection: close` to responses with status >= 400. + +## Scheduling and determinism + +One engine, one request at a time, in arrival order. Parsing and validation run on the +HTTP thread; rendering and compute run on a single worker thread. With `--decision-queue N`, +up to N requests wait while one runs (an idle worker always takes a request); the next one +gets 429. When the client disconnects, the request is cancelled: it is skipped if it has +not started, or stops between items (while rendering or between forward passes), and a +cancelled request no longer takes a place in the queue; a running request that is cancelled +does not count as busy either, so with `--decision-queue 0` the next request is taken +instead of getting 429. On shutdown (SIGINT/SIGTERM) the worker stops accepting requests +(new ones get 503 `UNAVAILABLE`), and every waiting and running request is cancelled the +same way, all under the worker lock, so no request slips in after the cancel and the process +does not wait for the queue. The worker never touches the HTTP request object. + +Tokenization matches the HF tokenizer of the checkpoint (`tests/laya/verify_tokenizer.py`) +and costs O(n log n) in the text length. `tools/laya` ports both tokenizers of the family; the +GGUF key `decision.laya.tokenizer` picks one (a GGUF without it is `metaspace-bpe`): + +| `decision.laya.tokenizer` | checkpoints | steps (HF `tokenizer(text, add_special_tokens=False)`) | +|---|---|---| +| `metaspace-bpe` | `laya-multilingual` | added tokens on the raw text, `" "` -> U+2581, Metaspace words, BPE with byte fallback | +| `bytelevel-bpe` | `laya`, `laya-typed-decisions` | special added tokens on the raw text; NFC (`decision.laya.normalizer`); normalized added tokens (space runs, `[unusedN]`); GPT-2 regex; byte-to-unicode; BPE | + +The converter also stores the HF flags of the added tokens (`decision.laya.added_tokens`: id, +flags pairs; lstrip, normalized) and refuses a tokenizer that needs anything else (rstrip, +single_word, another normalizer or pre-tokenizer). NFC and the regex classes use the Unicode +tables of HF tokenizers itself (`tools/laya/laya-unicode-data.inc`, probed from `tokenizers` +by `tools/laya/gen-unicode-data.py`, which checks them against HF NFC on every codepoint): +Python's `unicodedata` is newer and would differ on marks added after Unicode 10. +libllama's vocab (vocab-only load) was not reused: on the English GGUF `llama-tokenize` skips NFC +(`cafe` + U+0301 ` is here` gives 6 tokens where HF gives 5) and ignores the lstrip of `[MASK]` +(`a [MASK] b` gives 66 209 50284 270 where HF gives 66 50284 270), and `tools/laya` would have to +link libllama instead of ggml alone. +For both, long words without spaces (CJK, base64, URLs) stay cheap (a 1 MB input takes well +under a second). Each request tokenizes its state once: +all questions of a systemone request share the state tokens, and router candidates share +the tokens of the criterion and the task. For that the router state splits after the card +and after `task:`, and each piece is tokenized on its own. That gives the tokens of the +whole text only where both points are token boundaries of the vocabulary (for +`laya-multilingual`: `\n\n` is an added token and a space starts a Metaspace word; for the +English checkpoints the GPT-2 regex already cuts there), so at +load the engine checks tokenize(A + B) == tokenize(A) + tokenize(B) on card endings and +task starts of every kind (letters, digits, CJK, punctuation, spaces, newlines, special-token +text, with and without `escape-control`). If any probe differs, router states are tokenized +whole: the same tokens, without the sharing. `/props.decision.plan.state_split` shows the +result. + +Plans (laya): + +- `sequential` (default): one graph per question or candidate, no state between calls. + Results are bitwise stable for a fixed `-t`, and items are independent. +- `packed`: the items of a systemone request in one graph with a block-diagonal mask (from + PR #29363). Opt-in; per the PR README it is not faster on CPU. Measured against + `sequential`: max |dlogit| 2e-6 on F32, 1e-2 on F16, 7e-2 on Q8_0. The graph holds an + n_tok x n_tok attention matrix per head, so items are packed in order into groups of at + most 2048 tokens (about 230 MB for mmBERT-base); a larger request runs several graphs. + Never used for `/v1/router/score`, where a candidate's score must not depend on the others. + +There is no batching across requests and no inexact prefix reuse. Settings that change +numerics (plan, threads, kernels, recipe) are shown in `/props.decision.plan`. + +### CPU kernels and memory + +- Threads: without `-t` the engine runs on the performance cores (macOS + `hw.perflevel0.physicalcpu`, which is also the common default there; Windows the cores of + the highest `EfficiencyClass`, while the common default counts the efficiency cores too; + other systems keep the common default), for every kernels choice (measured below). The CPU + backend gets one persistent ggml + threadpool, created at load (polling level 0 between graphs: idle workers sleep; within a + graph they spin on the barrier), so the CPU backend creates no threads per graph. The BLAS + backend is different: without OpenMP, ggml-blas converts the weights of every matmul it + takes to F32 on `n - 1` new `std::async` threads (about 90 conversions per forward pass of + mmBERT-base). The engine therefore gives the BLAS backend min(`-t`, 8) threads + (`/props.decision.plan.n_threads_blas`; measured below); Accelerate runs the sgemm itself + on its own threads. On macOS the worker thread that runs the graphs is raised to QoS + `USER_INITIATED`. OpenMP builds get `KMP_BLOCKTIME=0` and `OMP_WAIT_POLICY=passive` unless + set, at process start before the HTTP threads exist (LLVM libomp reads them at its first + parallel region; GNU libgomp only at program start, so set them in the environment there). +- Memory: `token_embd` (393 MB F16 / 209 MB Q8_0 for mmBERT-base, read only by `get_rows`) + stays in a read-only mapping of the GGUF, so only the rows of the tokens seen become + resident; every other weight is loaded. The GGUF header, vocabulary strings and merges are + freed after the load. `--load-mode none` loads everything; results are bitwise the same. + `/props.decision.memory` shows the weight bytes loaded, mapped and repacked. +- Warm-up: one 64-token forward pass at load (starts the threads, faults in the weights + that every pass reads, and sizes the compute buffer for 64 tokens); `--no-warmup` skips it. + It changes no result. It does not bound the compute memory: the scheduler grows the buffer + again on the first longer request (measured below). +- Kernels (`--decision-kernels`, spec `plan.kernels`, `/props.decision.plan.kernels` shows + what runs: `cpu`, `cpu+repack`, `cpu+blas`, `cpu+repack+blas`): + - `default`: the ggml CPU kernels. F16 matmuls round the activations to F16, Q8_0 matmuls + quantize them to Q8_0. `llama-laya-cli`, the golden files and + `tests/laya/verify_precision.py` use it. + - `blas`: the BLAS backend takes the matmuls it supports (weights converted to F32, F32 + sgemm); on macOS that is Accelerate (AMX). Closer to the PyTorch reference and faster + than `default` on both F16 and Q8_0 (table below). `auto` picks it when the BLAS backend + is Accelerate; other BLAS libraries are not measured and stay opt-in. ggml-blas takes a + matmul only when all its dimensions are at least 32, so sequences shorter than 32 tokens + and the head matmuls over the marker rows still run on the ggml CPU kernels, while + `/props` says `cpu+blas`. An explicit `blas` on a build without a BLAS backend fails at + load (it does not quietly compute with other kernels). + - `repack`: CPU repack buffers (`ggml_backend_dev_get_extra_bufts`) for quantized matmul + weights that have a repacked kernel (Q8_0 / Q4_0 / Q4_K on NEON dotprod / i8mm, Q4_0 / + Q4_K on AVX2, ...). F16 weights are never repacked. Same accuracy class as `default`, + different rounding. + - `repack+blas`: repacked weights are not host memory, so BLAS never takes them. With Q8_0 + (where every encoder matmul is repacked) it computes exactly like `repack`; BLAS only + takes the weights that have no repacked kernel (F16, or types without one). + - Platforms: the default `auto` means `cpu+blas` on macOS and `cpu` on Linux and Windows, so + the same GGUF gives slightly different logits there. Through the server, `laya-multilingual` + F16 is within max |dlogit| 0.014 of the reference with `auto` on macOS and 1.09 with + `default` (the kernels Linux and Windows run; measured on this Mac, the x86 kernels round + differently and are not measured); parity tables below. `--decision-kernels default` (or spec + `plan.kernels: "default"`) restores the Phase 1 numerics bit for bit on every platform. + - Results are bitwise stable for a fixed model, `-t` and kernels on one machine. + +## Model metadata: `decision.spec` + +`decision.spec` is a GGUF string holding UTF-8 JSON. It is the source of truth. The mirror +keys `decision.spec_version` (u32), `decision.layout`, `decision.model_id` and +`decision.model_version` are for readers that skip the JSON; the server checks that they +agree with the spec. `laya.*` keys hold architecture hyperparameters only. + +Where the spec comes from, in order: + +1. `--decision-spec FILE` replaces it as a whole (`spec_source: file`). +2. The GGUF `decision.spec` (`spec_source: gguf`). +3. Defaults for an unstamped laya GGUF (`spec_source: default`): calibration from + `laya.temperature` and `laya.temperature_by_options.{buckets,values}` unless all + temperatures are 1.0 and there are no buckets (then `calibrated: false`, which is the case + for `laya-multilingual`), no router calibration. A non-laya GGUF without a spec does not + load. The checkpoint's `temperature_by_options` (`"choice:3-5": 1.76`, ...) becomes the + bucket of that type and the per-type temperature the `"*"` bucket, which is the lookup of + the Laya reference (`laya.agent._decode_answers`); its bucket `2` means K <= 2 and is + stored as `"1-2"`. The English `laya` ships `choice:11+` = 0.1006, which the [0.5, 5] + clamp turns into 0.5, as the reference does. + +A laya spec (file or GGUF) without a `calibration` key keeps the calibration from +`laya.temperature` of case 3 (`calibration.version` `gguf:laya.temperature`). To turn it +off, give `"calibration": {"method": "none"}` or `"calibration": null`. + +`spec_sha256` is the SHA-256 of the exact spec bytes (for defaults: of their py-json +text). It is in `/props` and in every response. + +Example (router on laya): + +```json +{"spec_version": 1, "model_id": "atomic/router-laya", "model_version": "1.0.0", "layout": "laya", + "input_contract": "laya-router-v1", "special_tokens": "escape-control", + "limits": {"max_options": 20, "max_candidates": 16}, + "calibration": {"method": "temperature", "required": true, "clamp": [0.5, 5.0], + "temperature": {"noul": {"2": 1.37}, "choice": {"2": 1.2, "3-5": 1.45, "6-10": 1.6, "11+": 1.8}, "score": {"*": 1.3}}}, + "confidence": "laya", "plan": {"name": "sequential", "recipe": "Q8_0-mixed", "n_threads": 4}, + "router": {"card_schema": "atomic.executor-card/1", "card_renderer": "card-v1", "max_card_tokens": 384, + "question": {"type": "noul", "instructions": "Will the executor meet the success criterion on this task?", + "criteria": {"true": "meets the criterion", "false": "does not meet the criterion"}}, + "calibration": {"method": "platt", "a": 1.0, "b": 0.0}}} +``` + +Calibration rules: + +- Temperature lookup: the question type entry, else `all`. Inside an entry, by option + count K: exact `"N"`, then range `"A-B"`, then `"N+"`, then `"*"`. A temperature found + this way is clamped to `clamp`. +- With no entry or no matching bucket the temperature is exactly 1 (not clamped). Only a + `required: true` calibration rules this out: it needs a temperature for every question + type and option count the model accepts (noul: 2; choice and score: 2 to + `limits.max_options`, capped by the layout: laya 20, semif-letters 16), through the type + entry or `all` and a matching bucket, and a gap is a load error that names it (for example + "choice with 6 options"). A calibration without `required` can fall back to T = 1 for the + cases it does not cover. A bare `calibration.json` sidecar is always `required`. +- Temperatures and Platt parameters are fitted on the raw logits of this engine, for this + GGUF, recipe, plan and kernels. `plan.kernels` (`auto`, `default`, `repack`, `blas`, + `repack+blas`) pins the kernels the calibration was fitted with; `--decision-kernels` + overrides it. Any other value (also a non-string) is a load error, and `gguf_decision_spec.py` + refuses it too. + +A router question (`router.question`) follows the laya question rules above: criteria keyed +only `true` / `false` in any case, and `labels`, when given, valid noul labels; the loader and +`gguf_decision_spec.py` both reject anything else. + +Contracts: the loader rejects values the engine does not implement. laya: `input_contract` +`laya-v1` (default) or `laya-router-v1` (the router state above, needs `special_tokens` +`escape-control`), `special_tokens` `mask-to-space` (default) or `escape-control`. +`semif-letters`: `semif-v1` and `escape`. + +Stamping without re-converting: + +```bash +python gguf-py/gguf/scripts/gguf_decision_spec.py set model.gguf spec.json # in place, or -o out.gguf +python gguf-py/gguf/scripts/gguf_decision_spec.py get model.gguf +python gguf-py/gguf/scripts/gguf_decision_spec.py verify model.gguf [spec.json] +``` + +`set` and `verify` check the spec with the rules of the server loader, so a spec they accept +also loads. Both implementations run the cases in `tests/decision/spec_cases.json` +(`test-decision-calib` and `test_decision.py`): a new rule goes into both and gets a case. +`set` takes a full spec only, not a bare `calibration.json`. + +## Training and calibration tools + +Python tools for the model team, so that training data, calibration and baselines use the text +and the logits of this engine. They are offline and write no GGUF. + +**`tools/decision/reference.py`** (stdlib only) is the Python reference of the router input. +The training pipeline imports it instead of re-implementing the prompt: + +- `py_dumps` / `loads_strict` / `parse_body`: `json.dumps(v, ensure_ascii=False)` and the + engine's strict JSON parse (NaN and Infinity, integers outside int64/uint64 and float + overflow are `UNSUPPORTED_NUMBER`; lone surrogates and more than 128 levels are + `MALFORMED_JSON`; a duplicate key keeps its first position and its last value; one leading + UTF-8 BOM is skipped). +- `card_validate` / `card_render`: the `atomic.executor-card/1` rules and the `card-v1` text, + with the engine's reason, param and warnings. +- `parse_router` / `router_state` / `state_splits`: the `/v1/router/score` checks and the + candidate state (card, then criterion, then task). +- `router_question` / `noul_options`: the spec router question (built-in default, default + criteria) and its laya option texts. +- `Escape` / `control_strings_from_gguf`: `mask-to-space` and `escape-control`. The escape set + comes from the GGUF (a stdlib GGUF metadata reader) exactly as `laya_escape_init` builds it. +- `render_router(body, spec, esc)`: all of the above for one request. `model_text` is the + state the tokenizer reads. `laya_router_examples` gives one Laya noul example per candidate. + +```bash +python3 tools/decision/reference.py control-tokens laya-multilingual-q8_0.gguf > control.json +python3 tools/decision/reference.py router request.json --spec spec.json --control control.json +python3 tools/decision/reference.py router request.json --spec spec.json --gguf model.gguf --candidate ID --text model +python3 tools/decision/reference.py card card.json # validate + card-v1 text +``` + +Token counts (`CARD_TOO_LONG`, `CRITERION_TOO_LONG`, truncation) need the tokenizer and are +not in the reference; the render route shows them (`POST /v1/decision/render` with +`--decision-debug`). + +How the reference is tied to the engine: + +- `tests/decision/gen_router_golden.py` writes `tests/decision/golden/router_cases.jsonl`: + 540 exact request bodies (fixed parser cases such as a leading BOM, `-NaN`, duplicate keys, + 128 nesting levels, and two failures in one body, where the first in document order decides + the reason as in the engine's SAX parser; 3 cases per card and request rule; random requests + with unicode, C0/C1 controls, control-token text, 4096-byte fields, missing checks and unknown + fields; 421 accepted, 1132 candidate states), each with the 400 reason and param from + `reference.py`, or a SHA-256 over its warnings, the question's type and instructions, options, + states, split offsets and escaped model texts. The escape sets in the file are those of + `laya-multilingual` and of the English checkpoints, written into it: ctest does not read + GGUFs, and the check against the real vocabularies (last point) runs only on a machine with + the models. +- `test-decision-reference` (`ctest -R decision`) runs every body through + `decision_parse_body`, `decision_parse_router`, `decision_router_items` and + `laya_escape_text` and requires the same result for every case (`--dump NAME` prints the + engine's side of one case). `test_reference.py` requires the file to be what the generator + writes now, so a change on either side fails a test. +- `test_decision.py` sends every golden body to the server's render route on the tiny model and + compares the states byte for byte and the 400 reason and param. For the escaping it renders the + reference's `model_text` as a plain systemone state with the same question: the tokens must be + those of the router item. The English tiny model repeats this on every 5th case. +- The escape sets of `laya-f16`, `laya-ml-f16`, `laya-en-f16` and `laya-td-f16` from + `control_strings_from_gguf` equal the engine's (`test-decision-reference --control MODEL`; + `test_reference.py` checks this when `TEST_DECISION_REFERENCE_BIN` is set and the models are + there). + +**`tools/decision/schema/executor-card-v1.schema.json`** is the card as JSON Schema (draft +2020-12), for tools that want a standard validator. Three rules cannot be written in JSON Schema: +`passed <= total`, the 4096-byte limit (`maxLength` counts code points) and integral floats +(`188.0` is an integer for JSON Schema; the engine refuses it). So the schema accepts a little +more than the engine. `test_reference.py` runs the schema and `reference.card_validate` on 1427 +cards (hand-written cases and every card of the golden requests). They agree on every card +outside those three gaps (13 cards inside: 9 over 4096 bytes, 2 integral floats, 2 with passed > +total), and the reference refuses every card inside them. The same cards also go through the +`jsonschema` package (`Draft202012Validator`) when it is installed, as in CI. Counts carry +`exclusiveMaximum` 2^63, not `maximum` 2^63 - 1: that number is not a double, and a validator +that reads numbers as doubles would round it up and accept 2^63. + +**Data format** (`tools/decision/router_eval.py`, shared by the two scripts): JSONL, one record +per task, `{"id", "task", "criterion", "candidates": [{"id", "card", "outcome": 0|1, +"logit"?}], "split"?: "fit"|"eval"}`. Every record must be a valid router request. Without +`split` a record goes to eval when `sha256("router:")` falls below `--heldout-frac` +(default 0.3), so both scripts use the same split. Metrics: + +- ECE: 10 equal-width bins of `p_success`, positive class. JevBench's top-label ECE bins + `max(p, 1-p)` instead. +- Brier: mean `(p - y)^2`, the one-class form (half the 2-class convention). +- NLL, AUC, and accuracy at 0.5. + +Intervals are 95 % percentile intervals of a cluster bootstrap over records: candidates of one +task share the task. Deltas are paired. An interval that contains zero means no convincing +difference. The bootstrap ECE is biased upward, so its interval can sit at or above the point +value. + +**`scripts/fit-router-calibration.py`** fits `spec.router.calibration` (Platt, p = sigmoid(a z + b)) +on this engine's raw logits: + +```bash +# the server as it will run (GGUF, plan, kernels), uncalibrated for now +llama-server --decision -m router.gguf --decision-spec spec.json --decision-allow-uncalibrated --port 8090 +python3 scripts/fit-router-calibration.py collect data.jsonl logits.jsonl --url http://127.0.0.1:8090 --spec spec.json +python3 scripts/fit-router-calibration.py fit logits.jsonl --spec spec.json --spec-out spec-router.json -o fit.json +python3 gguf-py/gguf/scripts/gguf_decision_spec.py set router.gguf spec-router.json -o router-cal.gguf +``` + +- `collect` posts each record to `/v1/router/score`. It stores the raw `logit` of every + candidate and an `engine` block from `/props`: model, `spec_sha256`, plan, kernels, recipe. + With `--spec` it checks that the server runs that exact spec: the `--decision-spec` file, or + the output of `gguf_decision_spec.py get router.gguf > spec.json` (the GGUF text plus the + newline `get` prints). It reports and skips requests the server refuses (for example + `CARD_TOO_LONG`). +- `fit` refuses logits from more than one engine identity; a record without an `engine` block + (logits from elsewhere) counts as its own. It refuses fewer than `--min-examples` (1000) fit + examples or `--min-per-class` (50) of either outcome, and fewer than `--min-eval` (200) eval + examples. It fits with Platt's prior-corrected targets (Newton, backtracking) and reports + ECE, Brier, NLL and accuracy before and after, on the eval split, with the paired delta. + "Before" is what ships now: `--before A,B`, else the `router.calibration` of `--spec`, else + sigmoid(z). The in-sample fit-split numbers are marked as such. +- `fit` prints the `router.calibration` block. With `--spec` / `--spec-out` it writes the spec + with that block and with `plan.kernels` set to the kernels the logits came from + (`/props` `cpu`, `cpu+blas`, `cpu+repack`, `cpu+repack+blas` -> `default`, `blas`, + `repack`, `repack+blas`), checks it with the `gguf_decision_spec.py` loader rules and prints + the `set` command. `auto` is `blas` on macOS and `default` elsewhere, and the two give + different z, so a calibration fitted on a Mac pins `blas`: such a GGUF fails to load on a + build without a BLAS backend unless `--decision-kernels` overrides it (and then the + calibration does not fit its logits). Collect on the platform the model will run on, or with + the server started with `--decision-kernels default`. Without an `engine` block in the logits + `fit` warns and leaves `plan.kernels` as it is. The router question's criteria are part of + the prompt, so the block is valid only for the question in the spec the logits were + collected with. + +**`scripts/router-baselines.py`** scores simple baselines on the same data and split, with the +same metrics: + +- `base-rate`: the fit-split positive rate. +- `pass-rate`: the pooled card pass rate (passed + 1) / (total + 2), with no fit. +- `pass-rate-platt`: `pass-rate` with a Platt fit. +- `logreg`: L2 logistic regression on card metrics (pooled and per-check pass rates, totals, + measured and missing counts, kind). +- `engine-raw` and `engine-platt`: when the file has logits, all from one engine identity. + +Deltas are taken against `--reference` (default `engine-platt`, else `pass-rate-platt`). + +```bash +python3 scripts/router-baselines.py logits.jsonl -o baselines.json +python3 -m pytest -q tests/decision/test_reference.py # offline tests of all of the above +``` + +## Tests + +```bash +ctest --test-dir build -R decision # py-json (golden + splitmix64 hashes), request, calib + spec cases, router, reference goldens +ctest --test-dir build -R laya-convert -LE python # C++ HF -> GGUF converter vs the Python converter's SHA-256 (tiny fixtures) +# (-R decision also runs test-decision-checkpoint-cli: llama-laya-cli -m , cache, identity) +python3 -m pytest -q tests/decision/test_reference.py # reference.py, card schema, calibration and baseline scripts +cd tools/server/tests +LLAMA_SERVER_BIN_PATH=../../../build/bin/llama-server python -m pytest -q unit/test_decision.py +# tokenizer parity with the checkpoint's HF tokenizer (needs transformers and the real GGUF) +python tests/laya/verify_tokenizer.py build/bin/llama-laya-cli laya-multilingual-f16.gguf /tokenizer +python tests/laya/verify_tokenizer.py build/bin/llama-laya-cli laya-en-f16.gguf /tokenizer +# logits against the PyTorch reference (needs the laya package; see tests/laya/README.md) +$LAYA_PY tests/laya/verify_reference.py ref items.jsonl ref.jsonl --english +python3 tests/laya/verify_reference.py cli build/bin/llama-laya-cli laya-en-f32.gguf ref.jsonl cli.jsonl +# the same items through llama-server --decision over HTTP (plan sequential, the server's threads and kernels) +python3 tests/laya/verify_reference.py server build/bin/llama-server laya-en-f16.gguf ref.jsonl server.jsonl +python3 tests/laya/verify_reference.py compare ref.jsonl cli.jsonl server.jsonl +``` + +The server tests are offline. The first `tiny_laya_decision_server()` call generates a random +tiny laya GGUF (`tests/decision/make_tiny_laya.py`, numpy + gguf-py) into `tools/server/tests/tmp`; +it is not a `ServerPreset`, so other test modules never build it. `tiny_laya_decision_server(english=True)` +uses a second one (`--english`: the `bytelevel-bpe` tokenizer and the temperature buckets of the +English checkpoints) and `tiny_laya_decision_server(q8=True)` a third (`--q8`: Q8_0 encoder +weights, which the repack buffers convert). The cache folder name carries a hash of the +generator, so a changed generator never reuses a stale file. `tests/decision/gen_golden.py` +writes the py-json golden files: `repr` of every power of two, 150 objects, and the SHA-256 of +30000 doubles and 1000 nested objects drawn from a splitmix64 stream that +`test-decision-json` draws the same way. CI runs both suites in the `decision-tests` job of +`.github/workflows/dev-build.yml` (Linux and Windows; warnings are errors on Linux), with +`ctest -R "decision|laya-convert" -LE python` (the converter tests included; the Python +cross-check needs torch and runs locally). They cover +response shapes, error codes 400/401/404/413/422/429/501/503, determinism, candidate +independence, start-up checks, the info routes and `-m ` (converted, then a cache +hit, the Python converter's bytes, the same answers as the Python GGUF, broken checkpoints, the +default cache locations; the tiny checkpoints of `tests/laya/convert`). With `--decision-debug`, two +environment variables make timing tests deterministic: +`LLAMA_DECISION_DEBUG_LOAD_DELAY_MS` (delay before the engine loads, for the 503 test) and +`LLAMA_DECISION_DEBUG_JOB_DELAY_MS` (delay before each job, for the 429 and shutdown tests). + +## Benchmark + +`llama-decision-bench` runs a suite of request bodies through the server code path in +process (request checks, engine, calibration, response text; no HTTP, no queue) and reports, +per request, the phases parse / tokenize / render / compute / post / total, p50 / p95 / p99, +CPU seconds (process user + system over the request), and the SHA-256 of the raw logits. +It also reports load time, RSS and memory footprint (macOS `phys_footprint`, Linux +`RssAnon`, Windows private bytes) after load and at the peak. + +```bash +cmake --build build -j --target llama-decision-bench llama-server +python3 tests/decision/bench/gen_suite.py # writes tests/decision/bench/suite.jsonl +./build/bin/llama-decision-bench -m laya-q8_0.gguf -f tests/decision/bench/suite.jsonl -t 4 --repeat 10 -o q8_0-t4.json + +# every KPI on one machine: bench per model and thread count, then llama-server --decision +BIN_DIR=./build/bin MODELS="laya-f16.gguf laya-q8_0.gguf" bash scripts/bench-decision.sh +python3 scripts/bench-decision-report.py build/bench-decision +``` + +Flags: `-m`, `-f` (suite), `-t` (default: the performance cores), `--repeat` (measured runs +per request, default 10), `--warmup` (default 1), `--plan`, `--spec`, `--kernels`, +`--max-items`, `--idle-ms N` (after the runs, sleep N ms and run the suite once more: first +request after idle), `--filter`, `--poll N` (threadpool polling level), `--no-mmap`, +`--mlock`, `--no-warmup` (no warm-up pass inside the load; `load` includes it otherwise), +`--warmup-tokens N` (size of that pass, default 64), `--blas-threads N` (BLAS backend threads, +default 0 = min(`-t`, 8)), `-o` (JSON). `scripts/bench-decision.sh` takes `KERNELS` for both tools. +Requests run interleaved (every repeat runs every request once), so slow drift such as heat +hits all requests alike. `tokenize` is a separate pass after each request that tokenizes its +distinct state pieces once; it is a part of `render`. Router requests run with or without a +router calibration. A request whose logits hash differs between runs is marked `det: NO`; +the report also compares the suite hash across thread counts. + +Suite lines: `{"id", "endpoint": "systemone" | "router", "group", "body"}`. The suite in +`tests/decision/bench` has the groups `systemone 1q` and `systemone 5q` (a ~170-token support +ticket), `router N=1/4/8` (executor cards of ~100 tokens, ~250-token tasks) and +`router N=1 t128` / `t512` (task length). + +`scripts/bench-decision.sh` writes into `OUT_DIR` (default `build/bench-decision`) one +`__machine.txt` (CPU, cores, OS, power source from `pmset` / `upower` / `powercfg`, low +power mode, load average and top CPU users before every run), one bench JSON per model and +thread count, and one `__server.json` per server run: time from spawn to `/health` 200 (K5), +RSS and footprint of the server, warm latency, and the first request after `IDLE_S` seconds +idle over HTTP (K6). `scripts/bench-decision-report.py` prints the tables (K1, K4, K5, K6, +K7, K9). Close other applications first: a busy machine makes p95 meaningless. + +Baseline before the Phase 4 work (2026-09-30, Apple M4 Max 12P + 4E, 48 GB, macOS 26.6.2, AC +power, low power mode off; one background process at 100% of one core; static Release build +with Metal, `laya-multilingual`, plan `sequential`, repeat 10, warmup 1). Latency in ms, +p50 / p95 over the requests of a group and their repeats: + +| group | f16 -t 4 | f16 -t 8 | q8_0 -t 4 | q8_0 -t 8 | +|---|---|---|---|---| +| systemone 1q (~220 tokens) | 214 / 231 | 112 / 122 | 143 / 156 | 78 / 84 | +| systemone 5q | 1178 / 1289 | 624 / 687 | 900 / 1030 | 486 / 563 | +| router N=1 (~480 tokens) | 540 / 559 | 286 / 299 | 459 / 473 | 247 / 259 | +| router N=4 | 2025 / 2103 | 1073 / 1123 | 1609 / 1706 | 870 / 931 | +| router N=8 | 4111 / 4429 | 2182 / 2367 | 3205 / 3543 | 1744 / 1937 | +| RSS / footprint after load, MiB | 748 / 875 | 748 / 875 | 637 / 764 | 637 / 764 | +| server spawn -> ready, ms | 389 | 370 | 342 | 340 | +| first so-1q after 60 s idle (HTTP) vs warm p50 | 1.07x | 1.11x | 1.11x | 1.19x | + +Compute is over 99.8% of every request (parse, render and post together stay under 0.5 ms; +tokenizing a request's state takes under 0.25 ms). CPU seconds per request are n_threads x wall time (worker threads spin), about 0.57 s +for q8_0 systemone 1q and 6.4 s for router N=4 at `-t 4`. Logits are bitwise identical across +all runs, across `-t 4` / `-t 8`, and between this build and a `GGML_BACKEND_DL` + +`GGML_CPU_ALL_VARIANTS` build without Metal (`apple_m4` variant, same latency); the DL build +uses 53 MiB less RSS and about 190 MiB less footprint after load. + +### Phase 4 CPU levers (same machine, 2026-09-30) + +Each lever was A/B-measured with `llama-decision-bench` against the baseline binary (suite +above, repeat 5, warmup 1) and kept only when it helped without breaking a gate. Numbers are +p50 in ms at `-t 8` unless noted. + +| lever | effect | logits | kept | +|---|---|---|---| +| persistent threadpool (registry proc-addresses, created once, poll 0) | no measurable change: latency, CPU seconds and the first request after idle within noise (poll 50: 1% slower) | bitwise same | yes: neutral; the CPU backend creates no threads per graph (the BLAS backend still does, two rows down) | +| QoS `USER_INITIATED` for the thread that runs the graphs (macOS) | not measurable on an idle machine (meant for a busy one, K8) | bitwise same | yes | +| default threads = performance cores (12 on M4 Max) | `-t 12` vs `-t 8`: 1.35x faster with the ggml kernels | bitwise same (thread-invariant) | yes | +| ... also with BLAS kernels (after the BLAS thread fix below) | `-t 12` vs `-t 8`, F16 / Q8_0, final bench (idle machine, repeat 10): router N=1 112 / 106 vs 124 / 122 ms, N=4 429 / 398 vs 465 / 465, systemone 1q 55 / 49 vs 53 / 50, systemone 5q 298 / 269 vs 290 / 282; in the thread grid (repeat 5 x 2, load average about 9) router between 2% slower and 8% faster, systemone 5-14% slower. CPU seconds +20-30% at `-t 12` | bitwise same | yes: faster where it matters (router); a client next to a chat model can pass a smaller `-t` (atomic-chat-core passes at most 8) | +| BLAS backend threads = min(`-t`, 8) instead of `-t` | ggml-blas (no OpenMP) converts each F16 / Q8_0 weight to F32 on `n - 1` new `std::async` threads, about 90 times per pass. `laya-multilingual` F16 at `-t 12`: 4 threads vs 12 router N=4 446 vs 494 ms, systemone 5q 312 vs 330, CPU s per N=4 request 2.86 vs 3.33; 8 threads = 4 threads within noise (router N=4 410-444 vs 412-449 over 3 rounds); at `-t 8`, 4 = 8; 1 thread is 1.2-1.5x slower (the conversion then runs on one core). The English checkpoint (4x larger weights) wants more: F16 at `-t 12`, 8 or 12 threads vs 4 router N=4 927-943 vs 963-975 ms, systemone 5q 629-648 vs 670-696. Q8_0: 1 to 12 threads within noise (`build-p4/bench/m1/`) | bitwise same (thread-invariant) | yes: 8 is the best measured for both encoders | +| `token_embd` in a read-only mapping + free the GGUF metadata after load | `default` kernels: Q8_0 RSS after load 637 -> 262 MiB, footprint 764 -> 389 MiB; F16 748 -> 373 / 875 -> 500 (`auto` adds the BLAS backend, about 18 MiB) | bitwise same (911 items, F16 and Q8_0) | yes, default | +| warm-up pass at load (64 tokens) | no measurable effect on the first request: it was already within 2% of warm (server so-1q first / warm 71.8 / 70.3 ms before, 71.2 / 70.6 after, `-t 8`), and a 752-token first request (`router N=1 t512`, `-t 12`, `auto`) takes 202 / 205 ms (F16) and 208 / 199 ms (Q8_0) with / without it (p50 193 / 188); load +25-30 ms, footprint after load +19 MiB. A 512-token warm-up costs another +26 MiB and +90 ms of load for the same first request (201 / 197 ms): not taken | none | yes, default (`--no-warmup`): starts the threads and faults in the weights; the compute buffer is sized for 64 tokens and grows on the first longer request | +| `repack` (CPU extra buffer types), Q8_0 | 1.6-1.7x faster: router N=1 243 -> 143, systemone 1q 76 -> 47 | changed: 1395 of 2604 questions bitwise same, max \|dlogit\| 5.4 vs `default` | opt-in | +| `repack`, F16 | no F16 repack kernel: unchanged | bitwise same | (no-op) | +| `blas` (Accelerate in the scheduler), F16 | 2.3x faster: router N=1 283 -> 123, systemone 1q 111 -> 52; CPU seconds 3.6-4x lower | closer to the reference (below) | yes, default via `auto` | +| `blas`, Q8_0 | 2.0x faster: router N=1 243 -> 119, systemone 1q 76 -> 49; CPU seconds 3x lower | closer to the reference (below) | yes, default via `auto` | +| `malloc_zone_pressure_relief` after load | no change in footprint | - | no (reverted) | + +Parity against the PyTorch reference (`laya-multilingual`, the 911 laya-eval items / 2604 +questions, every one with identical input ids; one expected refusal: the null state of +`scalar_state_0890`), on two code paths: + +- CLI: `llama-laya-cli -t 1` (the `build-parity/laya-eval` harness), which packs all + questions of an item into one graph (block-diagonal mask). +- server: `llama-server --decision` over HTTP (`tests/laya/verify_reference.py server`), plan + `sequential` (one graph per question), the default threads (the 12 performance cores; the + `auto` rows ran with 8, and a 12-thread rerun of F16 `auto` is bitwise identical on all 911 + items) and 4 BLAS threads (before the default became 8; the logits do not depend on the + BLAS threads either, K7). This is what a client of the server gets. Packing changes the + rounding (see "Plans"), so the two paths differ. + +| path, kernels | argmax agree | mean \|dlogit\| | max \|dlogit\| | mean TVD | max TVD | noul p>=0.5 agree | +|---|---|---|---|---|---|---| +| CLI, F16 `default` (Phase 1) | 2602 / 2604 | 0.0048 | 1.17 | 0.0012 | 0.21 | 715 / 715 | +| CLI, F16 `blas` | **2604 / 2604** | **0.0006** | **0.014** | 0.0001 | 0.001 | 715 / 715 | +| CLI, Q8_0 `default` (Phase 1) | 2529 / 2604 | 0.078 | 8.37 | 0.020 | 0.73 | 706 / 715 | +| CLI, Q8_0 `blas` | **2554 / 2604** | **0.047** | 8.09 | 0.011 | 0.51 | 708 / 715 | +| CLI, Q8_0 `repack` | 2538 / 2604 | 0.079 | 9.21 | 0.020 | 0.82 | 709 / 715 | +| server, F16 `default` (Linux / Windows default) | 2602 / 2604 | 0.0048 | 1.09 | 0.0012 | 0.21 | 715 / 715 | +| server, F16 `auto` = `blas` (macOS default) | **2604 / 2604** | **0.00055** | **0.0137** | 0.00014 | 0.0009 | 715 / 715 | +| server, Q8_0 `default` | 2530 / 2604 | 0.077 | 8.04 | 0.019 | 0.46 | 709 / 715 | +| server, Q8_0 `auto` = `blas` | **2554 / 2604** | **0.047** | 8.09 | 0.011 | 0.51 | 708 / 715 | + +The server F16 `auto` run of the DL build (CPU variants, no Metal) is bitwise identical to the +static one on all 911 items. Outputs: `build-p4/parity/final/` (server) and +`build-p4/parity/cli-*` (CLI). + +The ggml F16 matmul rounds the activations to F16 and the Q8_0 matmul quantizes them to +Q8_0; the BLAS path converts the weights to F32 and runs F32 sgemm, which is what the +reference does. That removes the F16 gap to the reference almost entirely (the two F16 flips +of Phase 1 are gone) and a third of the Q8_0 gap. `default` stays bitwise equal to Phase 1: +on the final tree the CLI raw logits of all 911 items (F16 and Q8_0) and the 7 CLI golden +cases (F16 and Q8_0 at `-t 1` / `-t 8`, 28 outputs, static and DL builds) are byte for byte the +Phase 1 ones. + +KPIs after Phase 4 (static Release build with Metal and Accelerate, `--decision-kernels +auto` = `cpu+blas`, repeat 10, warmup 1; `default` = the ggml kernels with every other lever; +p50 / p95 ms). The `auto` columns are from the run after the BLAS thread fix +(`build-p4/bench/final2-auto-report.md`), made with 4 BLAS threads before the default became +min(`-t`, 8) (4 and 8 measured equal for this encoder, table above). A rerun with the final +binary and 8 BLAS threads (`final3-auto`) hit intermittent background load (load average up +to 16): same logits hashes, p50 within 6% at `-t 8`, but its `-t 12` and server numbers are +disturbed (p95 up to 2.9x), so it is not used. `default` and `repack` are from the run before +the fix (`final-default` / `final-repack`), whose code paths it does not touch. Memory +is in MiB (2^20 bytes): RSS counts the resident pages of the mapped `token_embd`; footprint is +macOS `phys_footprint`, which does not count clean file-backed pages. + +| group | baseline f16 t8 | baseline q8_0 t8 | default q8_0 t12 | auto f16 t8 | auto f16 t12 | auto q8_0 t8 | auto q8_0 t12 | repack q8_0 t12 | +|---|---|---|---|---|---|---|---|---| +| systemone 1q | 112 / 122 | 78 / 84 | 58 / 62 | 53 / 58 | 55 / 59 | 50 / 54 | 49 / 55 | 39 / 51 | +| systemone 5q | 624 / 687 | 486 / 563 | 367 / 418 | 290 / 310 | 298 / 308 | 282 / 305 | 269 / 281 | 204 / 224 | +| router N=1 | 286 / 299 | 247 / 259 | 179 / 194 | 124 / 128 | 112 / 127 | 122 / 125 | 106 / 110 | 106 / 112 | +| router N=4 | 1073 / 1123 | 870 / 931 | 627 / 688 | 465 / 484 | 429 / 480 | 465 / 485 | 398 / 415 | 407 / 427 | +| router N=8 | 2182 / 2367 | 1744 / 1937 | 1264 / 1447 | 976 / 1018 | 895 / 918 | 917 / 1006 | 809 / 878 | 803 / 889 | +| router N=1 t128 / t512 | 196 / 509 | 139 / 388 | 102 / 283 | 86 / 229 | 80 / 193 | 82 / 228 | 75 / 188 | 67 / 208 | +| K4 bench after load, RSS / footprint | 748 / 875 | 637 / 764 | 264 / 390 | 393 / 519 | 393 / 519 | 281 / 408 | 282 / 408 | 264 / 390 | +| K4 bench after the first suite run, RSS / footprint | 809 / 775 | 698 / 664 | 335 / 292 | 457 / 414 | 459 / 416 | 345 / 302 | 347 / 304 | 332 / 289 | +| K4 bench peak, RSS / footprint | 810 / 890 | 699 / 788 | 347 / 437 | 459 / 550 | 462 / 566 | 347 / 438 | 350 / 438 | 333 / 436 | +| K4 server ready, RSS / footprint | 754 / 878 | 643 / 766 | 268 / 391 | 397 / 520 | 397 / 520 | 286 / 409 | 286 / 409 | - | +| K4 server after the requests and 2 x 60 s idle (one sample), RSS / footprint | 784 / 747 | 672 / 635 | 300 / 258 | 432 / 390 | 430 / 389 | 321 / 279 | 321 / 280 | - | +| K5 server spawn -> ready, ms | 370 | 340 | 290 | 324 | 322 | 295 | 306 | - | +| K5 server first so-1q / warm p50, ms | 104 / 103 | 72 / 70 | 50 / 49 | 53 / 50 | 52 / 51 | 49 / 46 | 47 / 47 | - | +| K6 so-1q after 60 s idle (HTTP) | 1.11x | 1.19x | 1.29x | 1.26x | 1.24x | 1.25x | 1.32x | - | +| K6 router N=4 after 60 s idle (HTTP) | 1.01x | 1.02x | 1.01x | 1.03x | 1.04x | 1.02x | 1.02x | - | +| K9 CPU s, systemone 1q | 0.90 | 0.61 | 0.68 | 0.22 | 0.30 | 0.20 | 0.27 | - | +| K9 CPU s, router N=4 | 8.58 | 6.98 | 7.66 | 2.29 | 2.77 | 2.25 | 2.53 | - | + +- K1 / D3: with `auto` at `-t 8` or `-t 12`, router N=1 p95 is 110-128 ms, N=2 about 250 ms + (two N=1 passes) and N=4 p95 415-485 ms, for F16 and Q8_0: inside the D3 goal (p95 <= 300 + ms for N=1-2, <= 1 s for N=4). At `-t 4` N=1 p95 is 173-176 ms and N=4 648-665 ms + (`final-auto`), so N=2 (about 340 ms) misses 300 ms there. +- K4: the target is <= 400 MB = 381 MiB for Q8_0. Measured as footprint it holds in the DL + build without Metal at every sample (below: 221 after load, 276 after the first run, 281 + peak). In the static build with Metal it does not hold after the load (`default` 390 MiB = + 409 MB, `auto` 408 MiB = 428 MB; the BLAS backend adds 18) nor at the peak (437-438 MiB), + and holds after the first requests (289-304 MiB in the bench). In every build with Metal + (the baseline too) the footprint falls by about 100 MiB during the first requests while RSS + rises: the Metal device the backend registry initializes costs 187 MiB of footprint right + after the load and about 26 MiB after the first requests (static 302-304 vs DL 276 MiB, + Q8_0 `auto`). The server's last sample (279-280 MiB) came after two idle minutes, one sample + each: not a steady state. RSS additionally counts the `token_embd` rows seen so far: +64 MiB + after one suite run here, and up to the whole 209 MiB (Q8_0; 393 MiB F16) as more of the + vocabulary appears (a 16 KB page holds about 20 Q8_0 rows). Those pages are clean and the + OS can drop them under pressure; footprint never counts them. +- K6: the first request after an idle minute pays a fixed 7-16 ms over HTTP (1.24-1.32x on + the 50 ms systemone 1q, 1.02-1.04x on router N=4), independent of the threadpool, the polling + level and the warm-up: the cores and caches waking up. +- K7: logits are bitwise identical across warmup, repeats, the run after idle, `-t 4` / `-t + 8` / `-t 12`, BLAS threads 1 / 2 / 4 / 8 / 12, and the static and DL builds, for every + kernel choice. +- K9: with BLAS the CPU time per request drops 3-4x (Accelerate runs the matmuls on the AMX + units instead of 8-12 spinning cores). +- Not measured: K2 (HTTP overhead), K3 (GFLOPS), K8 (p95 next to a generating chat model), + battery power, PyTorch / ONNX on the same machine. `llama-server` spawn -> ready was + 1.8 s once per freshly linked binary (macOS scans a new executable at its first launch); + those first runs are left out above. + +### D7: macOS acceleration (recommendation) + +Measured options, Q8_0 / F16 at `-t 12` (DL = `GGML_BACKEND_DL=ON GGML_CPU_ALL_VARIANTS=ON +BUILD_SHARED_LIBS=ON GGML_METAL=OFF GGML_NATIVE=OFF`, `apple_m4` variant picked at runtime): + +| build / kernels | router N=1 p50 / p95 | router N=4 p50 / p95 | footprint after load | footprint after the first suite run | footprint peak | logits | +|---|---|---|---|---|---|---| +| release-like static + Metal, `default` | 179 / 194 | 627 / 688 | 390 / 501 MiB | 292 / 398 MiB | 437 / 530 MiB | Phase 1 | +| static + Metal, `auto` (Accelerate) | 106 / 110 | 398 / 415 | 408 / 519 MiB | 304 / 416 MiB | 438 / 566 MiB | closer to reference | +| DL CPU variants, `auto` (Accelerate) | 107 / 113 | 406 / 417 | **221 / 333 MiB** | **276 / 389 MiB** | **281 / 393 MiB** | bitwise = static `auto` | +| static + Metal, `repack` (Q8_0) | 106 / 112 | 407 / 427 | 390 MiB | 289 MiB | 436 MiB | Q8_0-class | + +Latency is Q8_0; footprint is macOS `phys_footprint` in MiB, Q8_0 / F16. The `auto` rows are +the `final2` runs (4 BLAS threads, see the KPI note); DL F16 is from the run before the BLAS +thread fix, which does not change memory. + +Recommendation: + +1. **Accelerate first (done, no new binary).** The BLAS backend is part of every macOS + build (`GGML_BLAS` defaults to on for Apple), so `--decision-kernels auto` gives the + 2-2.3x speedup, 3-4x fewer CPU seconds and the better parity with the current release + binaries. It is the default of the decision engine; `llama-laya-cli` and the golden files + keep `default`. +2. **DL CPU variants for the decision process next**, when the app ships a dedicated + decision binary: same latency and bitwise the same logits as the static build, 187 MiB + less footprint right after the load and 157 MiB less at the peak (no Metal device; after + the first requests the gap shrinks to about 26 MiB), the Q8_0 <= 400 MB (381 MiB) footprint target met after the + load and at the peak, and an i8mm variant for M2+ without the SIGILL risk of a native build (risk 7). This + needs the extra `libggml-cpu-*.so` / `libggml-blas.so` in the bundle and signed, so it is + not wired into release CI here. Build note (opt-in, not in CI): + + ```bash + # decision-only macOS build: CPU variants loaded at runtime, Accelerate, no Metal + cmake -B build-decision-cpu -DCMAKE_BUILD_TYPE=Release -DGGML_BACKEND_DL=ON \ + -DGGML_CPU_ALL_VARIANTS=ON -DBUILD_SHARED_LIBS=ON -DGGML_METAL=OFF -DGGML_NATIVE=OFF + cmake --build build-decision-cpu -j --target llama-server + # bin/: llama-server, libggml*.dylib, libggml-cpu-apple_m1/m2_m3/m4.so, libggml-blas.so + ``` +3. **A separate static CPU build is not needed**: it would save the same Metal memory as + the DL build but loses the per-CPU variant choice. + +`repack` stays opt-in: on Q8_0 it is about as fast as Accelerate at `-t 12` (faster on short +systemone requests, 39 vs 49 ms) but keeps the Q8_0 activation rounding (Q8_0-class parity) +and spins all threads (about 12x wall time in CPU seconds). It is the lever for quantized +models where no Accelerate exists (Q4_0 / Q4_K on AVX2 and NEON); those platforms are not +measured here. + +## English checkpoints (`laya`, `laya-typed-decisions`) + +| checkpoint | encoder | ctx / head budget | tokenizer | calibration in the GGUF | +|---|---|---|---|---| +| `convaiinnovations/laya` | ModernBERT-large, 28 layers, d 1024, 421M | 512 / 192 | `bytelevel-bpe` (NFC) | `laya.temperature` + 6 `temperature_by_options` buckets | +| `convaiinnovations/laya-typed-decisions` | same | 1024 / 256 | same | same buckets, other base temperatures | +| `convaiinnovations/laya-multilingual` (default, D1) | mmBERT-base, 22 layers, d 768, 322M | 1024 / 256 | `metaspace-bpe` | none (`calibrated: false`) | + +```bash +python convert_hf_to_gguf.py --outfile laya-en-f16.gguf --outtype f16 +# or, same bytes, without Python (see "Converting without Python") +./build/bin/llama-laya-convert -o laya-en-f16.gguf --outtype f16 +./build/bin/llama-server --decision -m laya-en-f16.gguf --device none --port 8090 +``` + +The converter takes the special ids from the tokenizer (`[CLS]` 50281, `[SEP]` 50282, +`[MASK]` 50284, which is also `laya.marker_token_id`). A GGUF loads only if the mask id equals +`laya.marker_token_id` and every special id is inside the vocabulary; a `bytelevel-bpe` GGUF must +name `[CLS]`, `[SEP]` and `[MASK]` (the fallback ids 2 / 1 / 4 are the mmBERT ones). + +With 512 tokens, `laya` leaves about 316 tokens for a router state, and the default +`max_card_tokens` is 192 (3/8 of 512); the router probe finds the state split exact for this +vocabulary (`state_split: true`). + +Parity (Apple M4 Max, 2026-09-30, final tree). Tokenizer: 0 mismatches in 13647 strings, 10763 +of them English-heavy (`verify_tokenizer.py`), for both checkpoints, and 0 of 2000 router +head/tail splits (`laya-multilingual`: 0 in 13675). Logits: the 503 English items (1491 +questions; the letters of state and questions all ASCII) of the 911-item laya-eval set, PyTorch +reference fp32 (laya 0.3.21) against two paths (`verify_reference.py`): CLI = `llama-laya-cli +-t 1`, all questions of an item packed into one graph; server = `llama-server --decision` over +HTTP, plan `sequential` (the server runs used `-t 4`; logits are thread-invariant). Every +question had identical input ids and marker positions; the one refused item (null state) is +refused by both. `calibrated |dP|` compares the answers (temperatures and buckets applied; +reference rounded to 4 digits) with the reference `system_one` answers on 311 questions. + +| path, GGUF, kernels | argmax | max \|dlogit\| | mean \|dlogit\| | max TVD | calibrated max \|dP\| | +|---|---|---|---|---|---| +| CLI, `laya` F32, default | 1491/1491 | 4.2e-4 | 5.8e-6 | 2.0e-5 | 1e-4 | +| CLI, `laya` F16, default | 1489/1491 | 0.44 | 5.2e-3 | 1.7e-2 | 6e-3 | +| CLI, `laya` F16, blas | 1491/1491 | 1.3e-2 | 5.3e-4 | 1.1e-3 | 5e-4 | +| server, `laya` F16, default (the Linux / Windows default) | 1490/1491 | 0.24 | 5.2e-3 | 1.7e-2 | 5.8e-3 | +| server, `laya` F16, auto = blas (the macOS default) | 1491/1491 | 1.3e-2 | 5.3e-4 | 1.1e-3 | 4.6e-4 | +| CLI, `laya-typed-decisions` F32, default | 1491/1491 | 6.8e-5 | 1.3e-6 | 1.8e-5 | 1e-4 | +| CLI, `laya-typed-decisions` F16, default | 1491/1491 | 3.6e-2 | 1.3e-3 | 1.0e-2 | 6e-3 | +| CLI, `laya-typed-decisions` F16, blas | 1491/1491 | 3.9e-3 | 4.9e-4 | 1.1e-3 | 7e-4 | +| server, `laya-typed-decisions` F16, default | 1491/1491 | 3.8e-2 | 1.3e-3 | 1.1e-2 | 5.4e-3 | +| server, `laya-typed-decisions` F16, auto = blas | 1491/1491 | 4.6e-3 | 5.0e-4 | 1.2e-3 | 7.1e-4 | + +Every CLI run of the final tree (F32, F16 `default`, F16 `blas`, both checkpoints) is bitwise +identical to the run made before the last changes to the Unicode tables and `laya.cpp`. The F16 `default` flips are near-ties (reference +top-2 gaps 0.009 and 0.005; the server path keeps one of them). The act-head logits of these +checkpoints are 169 to several thousand in magnitude; the relative difference is at most 8e-5 +(F32), 8e-4 (F16 blas) and 6e-2 (F16 default), and the act probability (0 or 1 at these +magnitudes) never changes. Outputs: `build-p4/parity/final/` (`compare_en.json`, +`compare_td.json`). + +Latency (`llama-decision-bench`, same suite and machine, F16, kernels `auto` = Accelerate BLAS, +p50 / p95 ms; `build-p4/bench/english-report.md`). Measured with BLAS threads = `-t`, before +the default became min(`-t`, 8); for this encoder an interleaved A/B at `-t 12` found 8 and 12 +BLAS threads equal (router N=4 941 / 943 vs 940 / 927 ms, `build-p4/bench/m1/table-ab.md`), and +the logits do not depend on them. A rerun with the final binary under background load +(`build-p4/bench/english3`) was 5-10% slower at the p50, with identical logits hashes: + +| group | multilingual t8 | multilingual t12 | `laya` t8 | `laya` t12 | `laya-typed-decisions` t12 | +|---|---|---|---|---|---| +| systemone 1q | 52 / 55 | 54 / 59 | 120 / 129 | 116 / 125 | 119 / 122 | +| systemone 5q | 280 / 301 | 292 / 321 | 635 / 688 | 619 / 656 | 605 / 654 | +| router N=1 | 123 / 127 | 111 / 115 | 245 / 250 | 221 / 229 | 216 / 220 | +| router N=4 | 460 / 479 | 426 / 436 | 998 / 1030 | 907 / 939 | 893 / 915 | +| router N=8 | 930 / 1001 | 862 / 922 | 1874 / 1991 | 1693 / 1835 | 1670 / 1789 | +| compute per 1k tokens | 230-255 | 228-246 | 543-571 | 507-553 | 493-547 | +| footprint after load / peak, MiB | 519 / 546 | 519 / 550 | 943 / 959 | 944 / 962 | 943 / 959 | +| server ready, ms | - | 342 | 288 | 306 | 306 | + +- Per token the English encoder costs about 2.2x the multilingual one. The English BPE needs + about 10% fewer tokens for the same English text (router N=1: 418 vs 467), so a request + costs about 2x. Logits are identical at `-t 8` and `-t 12` for every model. +- D3 (p95 <= 300 ms for N=1-2, <= 1 s for N=4): the English checkpoints meet N=1 (229 ms) + and N=4 (939 ms) at `-t 12`; N=2 (about 450 ms) does not. +- Memory: F16 needs about 950 MiB of footprint; the 400 MB target would need a quantized recipe, and its + parity is not measured for these checkpoints. + +## Converting without Python (`llama-laya-convert`) + +```bash +./build/bin/llama-laya-convert -o laya-f16.gguf [--outtype f32|f16|q8_0] [--model-name NAME] [--verify-against ref.gguf] +./build/bin/llama-laya-convert --compare a.gguf b.gguf +``` + +A C++ port of `convert_hf_to_gguf.py` for laya checkpoints (`conversion/laya.py` and the classes +it inherits, gguf-py `SpecialVocab` and `Metadata`); it needs no Python and links ggml (plus `laya` for +its Windows path helper). The Python converter is +the reference: for all three checkpoints and `f32` / `f16` / `q8_0`, with and without +`--model-name`, the output is byte-identical to `convert_hf_to_gguf.py --outfile X --outtype T +[--model-name NAME]` (18 of 18 files, same SHA-256 and size). An f16 file takes 0.2-1.8 s on an +M4 Max (idle to shared with other jobs), 6-19x less than the Python converter in the same runs. +`--verify-against` prints the first difference (KV, tensor info, tensor data, then raw bytes). +Exit codes: 0 done / identical, 1 error (a file cannot be read, the conversion failed), 2 the files +differ. + +- `q8_0` is `convert_hf_to_gguf.py --outtype q8_0`: 1-D and `*_norm.weight` F32, rows that are not + whole Q8_0 blocks F16, every other 2-D weight Q8_0, including `token_embd`, `type_emb`, `scorer.*` + and `act_head.*`. That is not the Q8_0 recipe the accuracy figures of this document were measured + on (`tests/laya/quantize.sh` keeps those five at F16), and its accuracy is not measured, so + `-m DIR` does not offer it. For a served Q8_0 model, quantize the f16 GGUF with + `tests/laya/quantize.sh`. +- `general.*` follows gguf-py: `--model-name`, the README front matter (a YAML subset), and the + directory name. Like Python, an HF snapshot directory whose hash starts with a digit gives + `general.finetune=`, and without `--model-name` the name is the title-cased hash. +- Inputs the port does not cover are refused with a message instead of giving a different file: + a root `config.json`, `pytorch_model*.bin` (also a `model.safetensors.index.json` without any + `model*.safetensors` file: Python then takes the `.bin` path), non-float dtypes, tensor names + outside the laya table, rope scaling / experts / `quantization_config` / `id2label` in the + encoder config, `modules.json`, a `tokenizer_class` other than `PreTrainedTokenizerFast` / + `TokenizersBackend` (or, without one, a `tokenizer/config.json` with `model_type` or + `tokenizer_class`: AutoTokenizer would pick a model-specific class), `auto_map`, added tokens + whose AutoTokenizer round trip is not a known identity or U+2581 -> space, special tokens + AutoTokenizer would add, list-form chat templates, YAML beyond the subset for a used key, + non-finite weights with `q8_0`, absurd sizes Python cannot finish either (`num_hidden_layers` > + 65536, `vocab_size` > 2^24, `vocab_size` above the `token_embd` rows), JSON nested deeper than 127 + levels, and a `generation_config.json` with NaN / Infinity / lone surrogate escapes (Python's + `json` reads them; a plain syntax error is ignored, as in Python). The full list is in + `tools/laya/laya-convert.h`. +- Where Python loads a file through a strict library, the fields the port reads are held to the + same rules: every `added_tokens` flag must be a JSON bool and a `TemplateProcessing` must have + the `tokenizers` schema (as tokenizers 0.23 requires), and the README front matter must not + contain characters PyYAML's reader rejects. Fields the port does not read are not validated, + so Python can still reject a file this tool converts (example: a bad `padding_side` in + `tokenizer_config.json`, which transformers checks). +- Behaviour pinned to the reference environment (transformers 5.17, tokenizers 0.23): the named + special tokens of `tokenizer_config.json` and the values of a dict `extra_special_tokens` become + CONTROL; `clean_up_tokenization_spaces` is ignored for BPE. F32 -> F16 rounds like numpy on + AArch64 / x86-64 F16C (checked on all 2^32 inputs), NaN quieted with the top payload bits. +- Checkpoint files are untrusted: safetensors header length, offsets, dtype / shape / byte + counts are checked (overflow-safe) before any read; JSON nesting is limited before parsing + (copying a deeply nested value would overflow the stack); text processing is linear (a 4M-line + CRLF README or 300k YAML keys convert in 0.1-0.2 s); paths are UTF-8 (UTF-16 APIs on Windows). +- Output: written to a new, uniquely named `..tmp` (created exclusively, so never through + an existing file or symlink), read back with the gguf API, synced to disk (`F_FULLFSYNC` on + macOS: 0.08-0.15 s for 660 MB) and renamed. Nothing is left on failure. + +Tests: `ctest -R laya-convert` converts the tiny fixtures of `tests/laya/convert` (both tokenizer +families) against the SHA-256 of the Python output and runs the broken-input cases (CI runs it on +Linux and Windows); `test-laya-convert-py` (label `python`) converts fresh fixtures with both +converters (`LAYA_REF_PYTHON` names the interpreter; skipped without torch or without transformers +5.17 / tokenizers 0.23). To check the real checkpoints yourself: + +```bash +python convert_hf_to_gguf.py --outfile py.gguf --outtype f16 +./build/bin/llama-laya-convert -o cpp.gguf --outtype f16 --verify-against py.gguf # IDENTICAL to py.gguf +``` + +## Loading a Hugging Face checkpoint directly + +```bash +./build/bin/llama-server --decision -m ~/models/laya-multilingual --port 8090 # converts once, then loads +./build/bin/llama-server --decision -m ~/models/laya-multilingual --port 8090 # cache hit +./build/bin/llama-laya-cli -m ~/models/laya-multilingual -f tests/laya/demo_input.json +# options (server and CLI): --decision-convert-cache DIR --decision-convert-type f16|f32 +``` + +`-m` may name a laya checkpoint directory (the Hugging Face layout: `rl_agent_config.json`, +`encoder/config.json`, `tokenizer/`, `model*.safetensors`; an HF snapshot directory works as it +is). It is converted once with the C++ converter (`llama-laya-convert`, previous section) into a +GGUF cache, and the cached GGUF is then loaded exactly like `-m FILE`: one execution path, the +engine never reads the checkpoint. GGUF inputs work as before. + +- **Cache**: `//.gguf`. `` is `--decision-convert-cache`, else + `$LLAMA_CACHE/laya/gguf-cache`, else the user cache: macOS + `~/Library/Caches/llama.cpp/laya/gguf-cache`, Linux `$XDG_CACHE_HOME` or `~/.cache` + + `/llama.cpp/laya/gguf-cache`, Windows `%LOCALAPPDATA%\llama.cpp\laya\gguf-cache` (the layout of + common's `fs_get_cache_directory`, which `-mu` URL and docker downloads use; `-hf` uses the + Hugging Face hub cache instead). Nothing is written into the checkpoint directory: a cache inside + it is refused before anything is created. `` is the directory name, so the default model + name and spec `model_id` are the directory name (for an HF snapshot: the commit hash; set `-a` + for another alias). +- **Key**: the first 32 hex digits of a SHA-256 over the cache format, the converter version + (`LAYA_CONVERT_VERSION`, bumped with every change of the written bytes and with every input a + newer converter refuses, so older cache entries are not reused), the outtype, the directory name + (the converter derives `general.*` from it) and the files the converter can read: those directly + in the checkpoint root, in `encoder/` and in `tokenizer/` (sorted relative paths; dot-entries + such as `.git` or `.cache` skipped; at most 20000 entries): files up to 8 MiB by size + SHA-256 of + the content, larger files by size + mtime in ns + symlink target. Any other subdirectory counts by + its name only: the converter never reads below it (the `laya` repository keeps two more + checkpoints and eval data there). Files over 8 MiB are keyed by metadata because hashing them at + each start would cost more than converting: the in-tree SHA-256 takes 1.43 s for the 644 MB + `laya-multilingual` weights and 1.87 s for the 843 MB English ones. That covers the weights and + also the 34 MB `tokenizer.json` of `laya-multilingual`. Size + ns mtime change with every rewrite, + and in the HF cache the symlink target is the blob name, which is the content hash. Small files, + where an edit can keep the size and fall within the mtime granularity (a digit in a config), are + keyed by content. What the key does not see: a same-size rewrite of a file over 8 MiB that also + restores its mtime. +- **Writes are atomic and durable**: the conversion goes to a unique temporary name in the key + directory, is synced to disk and renamed into place (the directory is synced too), so a start + never sees a partial file and a power loss cannot leave a complete-looking file with zeroed data. + Concurrent cold starts on the same checkpoint each convert and the last rename wins with the same + bytes (8 simultaneous starts on an empty cache: 8 conversions, 1 file, identical outputs). + Temporary files older than 10 minutes in the key directory (a killed conversion) are removed + before the next conversion there. A checkpoint that changes while it is converted is refused (key + computed again afterwards). A cache entry that is not a readable laya GGUF with all its tensor + data is converted again; entries are never deleted, remove old key directories by hand. On POSIX, + a key directory or cached file owned by another user, writable by others, or a symlink is refused + (a shared `LLAMA_CACHE` could otherwise hand over another model). +- **Logs**: `decision: converted: in 1.04 s (...)` or `decision: cache hit: (...)` + (`laya:` in the CLI). `/props.decision` has `source` (`gguf` or `checkpoint-dir`), `cache_path` + and `checkpoint {dir, cache_dir, key, outtype, cache_hit, convert_ms, converter}`: `convert_ms` + is 0 on a cache hit, `converter` is the integer `LAYA_CONVERT_VERSION`. +- **Errors**: a directory without `rl_agent_config.json` ("is a directory but not a laya + checkpoint"), a checkpoint the converter refuses ("cannot convert checkpoint directory ...: + "), `--decision-convert-type q8_0`, and an unusable cache directory stop the + load with exit code 1 and leave nothing in the cache. +- **Cost** (M4 Max shared with other jobs, `laya-multilingual` f16, `llama-laya-cli --tokenize` of + one string, 3 rounds): first start 1.16-1.34 s including the 0.86-1.04 s conversion, cache hit + 0.32-0.36 s, the same GGUF with `-m FILE` 0.29-0.30 s (the key and the cache-entry check cost + about 40-60 ms). Peak RSS: 513-517 MiB for a converting start, 372-373 MiB for a cache hit or + `-m FILE`. + +**Identity with the Python converter.** The cached file is the output of `llama-laya-convert`: +for the three published checkpoints its bytes equal `convert_hf_to_gguf.py` without +`--model-name` (what `-m DIR` converts) in f32, f16 and q8_0, and with `--model-name` too (18 of 18 +files). On 67 inputs per cell (the 7 golden cases + 60 sampled from the parity sets), `llama-laya-cli +-m DIR` (the C++ cache, this build's loader) and the previous CLI and loader on the Python GGUF +print the same bytes apart from the `"model"` line: 6 of 6 cells (3 checkpoints x f16 / f32, 402 of +402). GGUF inputs are unchanged: on the 7 golden cases the CLI before and after this change prints +the same bytes (28 of 28: `laya-multilingual` f16 / q8_0 at `-t 1` / `-t 8`). 989 malformed +checkpoints (fuzzing under ASan + UBSan) gave no crash: 830 clean refusals and 159 accepted; the +Python converter wrote the same bytes for 158 of those and rejected the other (a bad +`padding_side`, a field the port does not read; see the previous section). `test_decision.py` and `test-decision-checkpoint-cli` check the same on the tiny +fixtures: the first start converts, the second hits the cache, the cached file has the SHA-256 of +the Python output (`tests/laya/convert/golden.sha256`; with `LAYA_REF_PYTHON` set the Python +converter also runs), and the answers with debug logits are identical to loading the Python GGUF. + +Known gaps: the conversion runs in the server process, and the allocator keeps what it freed: +a converting start peaks at 513-517 MiB against 372-373 MiB for a cache hit or `-m FILE` +(`laya-multilingual` f16, `llama-laya-cli`; mostly the 34 MB `tokenizer.json` parsed into a JSON +tree), and a server keeps part of that until the next start. Convert ahead (`llama-laya-cli -m DIR --tokenize` of one string, or one start) where that +matters. There is no cache eviction. On Windows the converter and the cache open their paths as +UTF-8 through UTF-16 with the helpers of the Windows fixes (`laya_utf8_to_wide`, `ggml_fopen`; +`llama-laya-convert` takes its arguments through `decision_utf8_args`, like `llama-laya-cli`; see +"Status and known gaps"), but `-m DIR` and `llama-laya-convert` have not been built or run there yet. + +## Status and known gaps + +- Router calibration: the tools exist (`fit-router-calibration.py`, `router-baselines.py`), + but no Platt block has been fitted on real outcome data yet. That needs the model team's + labelled router data and a router checkpoint. The Phase 2 acceptance numbers (decision + agreement at p = 0.95 against PyTorch, mean |dp|, ECE shift on >= 2000 held-out) are not + measured. + +- `semif-letters` (Arbiter-4B, JevK5) is not implemented; such a spec fails at load. +- English checkpoints: only F32 and F16 are measured; no quantized recipe, no router calibration + and no x86 run yet. +- laya: the reference's per-language temperatures and `answer_confidence` are not + implemented in the server; the act head (`action`) is not exposed. `llama-laya-cli` prints + both, in the reference answer shape. +- The ggml threadpool workers keep QoS `DEFAULT` on macOS (ggml sets no QoS on the threads it + creates; only the calling worker thread is raised). The first request after a long idle + pays a fixed ~20 ms (cores and caches waking up), independent of the threadpool. +- ggml-blas (without OpenMP) still starts `n_threads_blas - 1` threads for every weight + conversion and converts the same weights on every pass; caching the F32 weights or reusing + threads would need a change inside ggml (not done: ggml is left untouched). +- Windows: MSVC 2022 and 2026 (without `/WX`: upstream code has warnings) built the tree + *before* the Windows fixes on a Windows x64 runner and passed the decision gates there + (ctest, pytest, `verify_precision.py` with `PYTHONUTF8=1`, CLI t1 = t8). The fixes: model, + spec and input paths are opened as UTF-8 through UTF-16 (`CreateFileW`, + `std::filesystem::path`, `ggml_fopen`), `llama-laya-cli` takes its arguments from + `GetCommandLineW` and writes LF, and the Python helpers read child output as UTF-8. They + compile with MinGW-w64 GCC 15.2 (`-fsyntax-only -Wall -Wextra -Werror`, `_WIN32_WINNT` + 0x0601 and 0x0A00) and pass on macOS, but have not been run on Windows yet. diff --git a/common/arg.cpp b/common/arg.cpp index cc1a27cbf5bc..2d880a24c790 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1479,6 +1479,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex if (params.cpuparams.n_threads <= 0) { params.cpuparams.n_threads = std::thread::hardware_concurrency(); } + params.decision.threads_set = true; } ).set_env("LLAMA_ARG_THREADS")); add_opt(common_arg( @@ -3395,6 +3396,94 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.pooling_type = LLAMA_POOLING_TYPE_RANK; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_RERANKING")); + add_opt(common_arg( + {"--decision"}, + "serve a decision model (Decision API v1, see DECISION.md) instead of chat; requires -m (a GGUF file or a laya\n" + "Hugging Face checkpoint directory, converted once into a GGUF cache) (default: disabled)", + [](common_params & params) { + params.decision.enabled = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION")); + add_opt(common_arg( + {"--decision-convert-cache"}, "DIR", + "-m DIR (a laya Hugging Face checkpoint directory): where the converted GGUF is cached\n" + "(default: $LLAMA_CACHE/laya/gguf-cache, else the user cache: macOS ~/Library/Caches/llama.cpp/laya/gguf-cache,\n" + "Linux $XDG_CACHE_HOME or ~/.cache + /llama.cpp/laya/gguf-cache, Windows %LOCALAPPDATA%\\llama.cpp\\laya\\gguf-cache)", + [](common_params & params, const std::string & value) { + params.decision.convert_cache = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_CONVERT_CACHE")); + add_opt(common_arg( + {"--decision-convert-type"}, "TYPE", + string_format("-m DIR: weight type of the converted GGUF: f16 or f32 (default: %s; for Q8_0 quantize the f16 GGUF\n" + "with tests/laya/quantize.sh, which keeps the precision-sensitive tensors at F16)", params.decision.convert_type.c_str()), + [](common_params & params, const std::string & value) { + if (value != "f16" && value != "f32") { + throw std::invalid_argument("--decision-convert-type must be f16 or f32"); + } + params.decision.convert_type = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_CONVERT_TYPE")); + add_opt(common_arg( + {"--decision-spec"}, "FNAME", + "decision spec JSON that replaces the decision.spec of the GGUF (default: from the GGUF)", + [](common_params & params, const std::string & value) { + params.decision.spec_path = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_SPEC")); + add_opt(common_arg( + {"--decision-plan"}, "NAME", + "decision compute plan; laya: sequential, packed (default: from the spec)", + [](common_params & params, const std::string & value) { + params.decision.plan = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_PLAN")); + add_opt(common_arg( + {"--decision-kernels"}, "NAME", + "decision matmul kernels; laya: auto (blas when the BLAS backend is Accelerate, else default), default (ggml CPU),\n" + "repack (CPU repack buffers), blas (BLAS backend), repack+blas; kernels change the logits slightly\n" + "(default: from the spec, then auto)", + [](common_params & params, const std::string & value) { + if (value != "auto" && value != "default" && value != "repack" && value != "blas" && value != "repack+blas") { + throw std::invalid_argument("--decision-kernels must be auto, default, repack, blas or repack+blas"); + } + params.decision.kernels = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_KERNELS")); + add_opt(common_arg( + {"--decision-queue"}, "N", + string_format("decision requests that may wait before new ones get 429 (default: %d)", params.decision.queue), + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("--decision-queue must be >= 0"); + } + params.decision.queue = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_QUEUE")); + add_opt(common_arg( + {"--decision-max-items"}, "N", + string_format("max questions per /v1/systemone request and candidates per /v1/router/score request (default: %d)", params.decision.max_items), + [](common_params & params, int value) { + if (value < 1) { + throw std::invalid_argument("--decision-max-items must be >= 1"); + } + params.decision.max_items = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_MAX_ITEMS")); + add_opt(common_arg( + {"--decision-allow-uncalibrated"}, + "serve /v1/router/score without a router calibration: calibrated=false, p = sigmoid(logit) (default: disabled)", + [](common_params & params) { + params.decision.allow_uncalibrated = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_ALLOW_UNCALIBRATED")); + add_opt(common_arg( + {"--decision-debug"}, + "decision debug mode: raw logits and token ids in answers, POST /v1/decision/render, request logging (default: disabled)", + [](common_params & params) { + params.decision.debug = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DECISION_DEBUG")); add_opt(common_arg( {"--api-key"}, "KEY", "API key to use for authentication, multiple keys can be provided as a comma-separated list (default: none)", diff --git a/common/common.h b/common/common.h index 2748efd66af2..15da86fd2137 100644 --- a/common/common.h +++ b/common/common.h @@ -414,6 +414,21 @@ struct common_params_diffusion { bool add_gumbel_noise = false; // add gumbel noise to the logits if temp > 0.0 }; +// llama-server --decision (see DECISION.md) +struct common_params_decision { + bool enabled = false; + std::string spec_path = ""; // sidecar decision.spec, replaces the one in the GGUF // NOLINT + std::string plan = ""; // empty: plan from the spec // NOLINT + int32_t queue = 4; // waiting requests before 429 + int32_t max_items = 16; // questions per systemone request, candidates per router request + bool allow_uncalibrated = false; // router scores without a router calibration + bool debug = false; // raw logits, render endpoint, load delay for tests + std::string kernels = ""; // laya matmul kernels; empty: from the spec, then "auto" // NOLINT + bool threads_set = false; // -t given: otherwise the engine runs on the performance cores + std::string convert_cache = ""; // -m DIR: GGUF cache; empty: the user cache (llama.cpp/laya/gguf-cache) // NOLINT + std::string convert_type = "f16"; // -m DIR: f16 or f32 // NOLINT +}; + // reasoning API response format (not to be confused as chat template's reasoning format) // only used by server enum common_reasoning_format { @@ -499,6 +514,7 @@ struct common_params { struct common_params_speculative speculative; struct common_params_vocoder vocoder; struct common_params_diffusion diffusion; + struct common_params_decision decision; struct common_params_model model; diff --git a/conversion/__init__.py b/conversion/__init__.py index 854d24a1c51b..b1c675b023ab 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -147,6 +147,7 @@ "Eagle3DraftModel": "llama", "Eagle3Speculator": "llama", "Eagle3LlamaForCausalLM": "llama", + "LayaModel": "laya", "LlamaForCausalLMEagle3": "llama", "LlavaForConditionalGeneration": "llama", "LlavaStableLMEpochForCausalLM": "stablelm", diff --git a/conversion/base.py b/conversion/base.py index 8c233f4d5e4c..cf70dac39bbf 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -58,6 +58,11 @@ AnyModel = TypeVar("AnyModel", bound="type[ModelBase]") +# for checkpoints that ship no config.json, we will try to provide a synthetic one +HparamsMatcher = Callable[[Path], bool] +HparamsLoader = Callable[[Path], dict[str, Any]] + + class SentencePieceTokenTypes(IntEnum): NORMAL = 1 UNKNOWN = 2 @@ -77,6 +82,7 @@ class ModelBase: ModelType.TEXT: {}, ModelType.MMPROJ: {}, } + _hparams_loaders: list[tuple[HparamsMatcher, HparamsLoader]] = [] dir_model: Path ftype: gguf.LlamaFileType @@ -1111,6 +1117,24 @@ def get_model_part_names(dir_model: Path, prefix: str, suffix: str) -> list[str] return part_names + @staticmethod + def load_hparams_guess(dir_model: Path) -> dict[str, Any] | None: + # some models ship no config.json, will try to guess them + from conversion import load_all_models + load_all_models() + + for matcher, loader in ModelBase._hparams_loaders: + if matcher(dir_model): + return loader(dir_model) + return None + + @classmethod + def register_hparams_loader(cls, matcher: HparamsMatcher) -> Callable[[HparamsLoader], HparamsLoader]: + def inner(loader: HparamsLoader) -> HparamsLoader: + cls._hparams_loaders.append((matcher, loader)) + return loader + return inner + @staticmethod def load_hparams(dir_model: Path, is_mistral_format: bool): if is_mistral_format: @@ -1124,6 +1148,10 @@ def load_hparams(dir_model: Path, is_mistral_format: bool): config = AutoConfig.from_pretrained(dir_model, trust_remote_code=False).to_dict() except Exception as e: logger.warning(f"Failed to load model config from {dir_model}: {e}") + if not (dir_model / "config.json").is_file(): + config = ModelBase.load_hparams_guess(dir_model) + if config is not None: + return config logger.warning("Trying to load config.json instead") with open(dir_model / "config.json", "r", encoding="utf-8") as f: config = json.load(f) diff --git a/conversion/laya.py b/conversion/laya.py new file mode 100644 index 000000000000..a136f56f5cf0 --- /dev/null +++ b/conversion/laya.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +import json + +from pathlib import Path +from typing import Any, Callable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, gguf, logger +from .bert import ModernBertModel + + +@ModelBase.register_hparams_loader(lambda dir_model: (dir_model / "rl_agent_config.json").is_file()) +def _load_laya_hparams(dir_model: Path) -> dict[str, Any]: + """Laya checkpoints ship no root config.json; the encoder config lives in + encoder/config.json and the RL-agent hyperparameters in rl_agent_config.json.""" + with open(dir_model / "rl_agent_config.json", encoding="utf-8") as f: + rl_cfg = json.load(f) + + enc_cfg: dict[str, Any] = {} + enc_cfg_path = dir_model / "encoder" / "config.json" + if enc_cfg_path.is_file(): + with open(enc_cfg_path, encoding="utf-8") as f: + enc_cfg = json.load(f) + + hparams = { + **enc_cfg, + # force the laya architecture (root config is absent) + "architectures": ["LayaModel"], + "model_type": "laya", + } + # RL-agent decision head hyperparameters (defaults as in laya.agent) + hparams["head_layers"] = rl_cfg.get("head_layers", 2) + hparams["max_len"] = rl_cfg.get("max_len", 512) + hparams["head_max_len"] = rl_cfg.get("head_max_len", 192) + hparams["n_qtype"] = 3 # choice / score / noul + hparams["temperature"] = rl_cfg.get("temperature", [1.0, 1.0, 1.0]) + # ":" -> T, applied before the per-qtype temperature (laya.agent._decode_answers) + hparams["temperature_by_options"] = rl_cfg.get("temperature_by_options", {}) + hparams["act_classes"] = len(rl_cfg.get("act_costs", {})) + 1 + return hparams + + +@ModelBase.register("LayaModel") +class LayaModel(ModernBertModel): + model_arch = gguf.MODEL_ARCH.LAYA + + # laya checkpoints keep the tokenizer files under a tokenizer/ subdirectory + @property + def _tokenizer_dir(self) -> Path: + tok_dir = self.dir_model / "tokenizer" + return tok_dir if tok_dir.is_dir() else self.dir_model + + def _tokenizer_json(self) -> dict[str, Any]: + with open(self._tokenizer_dir / "tokenizer.json", encoding="utf-8") as f: + return json.load(f) + + def _tokenizer_kind(self, tj: dict[str, Any]) -> str: + """metaspace-bpe (laya-multilingual, mmBERT) or bytelevel-bpe (laya, laya-typed-decisions, + ModernBERT / OLMo BPE): the two tokenizers tools/laya ports. Anything else is refused.""" + pre = tj.get("pre_tokenizer") or {} + model = tj.get("model") or {} + if model.get("type") != "BPE" or model.get("dropout") or model.get("continuing_subword_prefix") or model.get("end_of_word_suffix"): + raise ValueError("laya: unsupported tokenizer model %r" % {k: v for k, v in model.items() if k not in ("vocab", "merges")}) + if pre.get("type") == "Metaspace": + return "metaspace-bpe" + if pre.get("type") == "ByteLevel": + if pre.get("add_prefix_space") or not pre.get("use_regex", True): + raise ValueError("laya: unsupported ByteLevel pre-tokenizer %r" % pre) + if model.get("byte_fallback") or model.get("ignore_merges"): + raise ValueError("laya: unsupported byte-level BPE options %r" % {k: v for k, v in model.items() if k not in ("vocab", "merges")}) + return "bytelevel-bpe" + raise ValueError("laya: unsupported pre-tokenizer %r" % pre) + + def _token_id(self, tj: dict[str, Any], content: str) -> int: + for at in tj.get("added_tokens", []): + if at["content"] == content: + return at["id"] + if content in tj["model"]["vocab"]: + return tj["model"]["vocab"][content] + raise ValueError("laya: token %r is not in the vocabulary" % content) + + def set_vocab(self): + tj = self._tokenizer_json() + with open(self._tokenizer_dir / "tokenizer_config.json", encoding="utf-8") as f: + tcfg = json.load(f) + + def special(name: str) -> int: + tok = tcfg.get(name) + if isinstance(tok, dict): + tok = tok.get("content") + if not isinstance(tok, str): + raise ValueError("laya: tokenizer_config.json has no %s" % name) + return self._token_id(tj, tok) + + # laya.common.build_sequence uses tok.cls_token_id, tok.sep_token_id and tok.mask_token_id + cls_id, sep_id, mask_id = special("cls_token"), special("sep_token"), special("mask_token") + + self.gguf_writer.add_marker_token_id(mask_id) + self._set_vocab_gpt2() + + # the special ids tools/laya reads: bos = [CLS], eos = sep = [SEP], mask, unk, pad + ids = {"bos": cls_id, "eos": sep_id, "sep": sep_id, "mask": mask_id} + if "unk_token" in tcfg: + ids["unk"] = special("unk_token") + if "pad_token" in tcfg: + ids["pad"] = special("pad_token") + self._special_vocab.special_token_ids.pop("cls", None) + self._special_vocab.special_token_ids.update(ids) + self._special_vocab.add_to_gguf(self.gguf_writer) + + kind = self._tokenizer_kind(tj) + self.gguf_writer.add_string("decision.laya.tokenizer", kind) + if kind == "bytelevel-bpe": + norm = tj.get("normalizer") + if norm is None: + self.gguf_writer.add_string("decision.laya.normalizer", "none") + elif norm.get("type") == "NFC": + self.gguf_writer.add_string("decision.laya.normalizer", "nfc") + else: + raise ValueError("laya: unsupported normalizer %r" % norm) + # HF AddedToken flags as (id, flags) pairs: bit 0 lstrip, bit 1 normalized + flags: list[int] = [] + for at in tj.get("added_tokens", []): + if at.get("rstrip") or at.get("single_word"): + raise ValueError("laya: added token %r uses rstrip / single_word" % at["content"]) + flags += [at["id"], (1 if at.get("lstrip") else 0) | (2 if at.get("normalized") else 0)] + self.gguf_writer.add_array("decision.laya.added_tokens", flags) + logger.info("laya: tokenizer %s, [CLS] %d, [SEP] %d, [MASK] %d", kind, cls_id, sep_id, mask_id) + + def get_vocab_base(self) -> tuple[list[str], list[int], str]: + # tokenizer.json / tokenizer_config.json live in the tokenizer/ subdir + saved = self.dir_model + self.dir_model = self._tokenizer_dir + try: + return super().get_vocab_base() + finally: + self.dir_model = saved + + def _set_vocab_gpt2(self) -> None: + tokens, toktypes, tokpre = self.get_vocab_base() + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_tokenizer_pre(tokpre) + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_types(toktypes) + + # written by set_vocab once the special ids are fixed + self._special_vocab = gguf.SpecialVocab(self._tokenizer_dir, load_merges=True) + + # the laya build_sequence always wraps with [CLS]/[SEP], so the llama.cpp + # side must add bos/sep the same way; SpecialVocab may have turned sep off + self._special_vocab.add_special_token.update({"bos": True, "eos": True, "sep": True}) + + def get_vocab_base_pre(self, tokenizer) -> str: + # "modern-bert" in llama.cpp is the English ModernBERT (OLMo BPE, GPT-2 regex). The multilingual + # checkpoint (mmBERT, Metaspace) keeps the same name; decision.laya.tokenizer tells them apart. + return "modern-bert" + + def set_gguf_parameters(self): + super().set_gguf_parameters() + + # decision head hyperparameters + self.gguf_writer.add_head_layers(self.hparams["head_layers"]) + self.gguf_writer.add_n_qtype(self.hparams["n_qtype"]) + self.gguf_writer.add_max_len(self.hparams["max_len"]) + self.gguf_writer.add_head_max_len(self.hparams["head_max_len"]) + self.gguf_writer.add_temperature(self.hparams["temperature"]) + self.gguf_writer.add_act_classes(self.hparams["act_classes"]) + tbo = self.hparams.get("temperature_by_options") or {} + if tbo: + arch = gguf.MODEL_ARCH_NAMES[self.model_arch] + self.gguf_writer.add_array(f"{arch}.temperature_by_options.buckets", list(tbo.keys())) + self.gguf_writer.add_array(f"{arch}.temperature_by_options.values", [float(v) for v in tbo.values()]) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + + # the temperature buffer is persisted as a KV array, not as a tensor + if name == "temperature": + return None + + # encoder tensors reuse the modern-bert naming (strip the encoder. prefix) + if name.startswith("encoder."): + name = name[len("encoder."):] + + # PyTorch nn.MultiheadAttention uses in_proj_weight / in_proj_bias; the + # laya decision head maps them onto the fused qkv gguf tensor. + if name.endswith("self_attn.in_proj_weight"): + name = name[:-len("in_proj_weight")] + "in_proj.weight" + elif name.endswith("self_attn.in_proj_bias"): + name = name[:-len("in_proj_bias")] + "in_proj.bias" + + return name, gen diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 77ca2c270e33..6c6eb3e59cec 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -159,6 +159,13 @@ class LLM: SWIGLU_CLAMP_EXP = "{arch}.swiglu_clamp_exp" SWIGLU_CLAMP_SHEXP = "{arch}.swiglu_clamp_shexp" HIDDEN_ACT = "{arch}.hidden_activation" + HEAD_LAYERS = "{arch}.head_layers" # laya: decision head transformer layers + N_QTYPE = "{arch}.n_qtype" # laya: question type count (choice/score/noul) + MARKER_TOKEN_ID = "{arch}.marker_token_id" # laya: token id marking option positions + MAX_LEN = "{arch}.max_len" # laya: max sequence length + HEAD_MAX_LEN = "{arch}.head_max_len" # laya: max head (option region) length + TEMPERATURE = "{arch}.temperature" # laya: per-qtype temperature (3 floats) + ACT_CLASSES = "{arch}.act_classes" # laya: action head class count DENSE_FEAT_IN_SIZE = "{arch}.{dense}_feat_in" DENSE_FEAT_OUT_SIZE = "{arch}.{dense}_feat_out" TARGET_LAYERS = "{arch}.target_layers" @@ -565,6 +572,7 @@ class MODEL_ARCH(IntEnum): MELLUM = auto() INKLING = auto() NANBEIGE = auto() + LAYA = auto() class VISION_PROJECTOR_TYPE(IntEnum): @@ -778,6 +786,18 @@ class MODEL_TENSOR(IntEnum): CLS = auto() # classifier CLS_OUT = auto() # classifier output projection CLS_NORM = auto() + TYPE_EMB = auto() # laya: question type embedding + HEAD_ATTN_QKV = auto() # laya: decision head attention qkv + HEAD_ATTN_OUT = auto() # laya: decision head attention output + HEAD_ATTN_NORM = auto() # laya: decision head attention pre-norm + HEAD_FFN_NORM = auto() # laya: decision head ffn pre-norm + HEAD_FFN_UP = auto() # laya: decision head ffn up + HEAD_FFN_DOWN = auto() # laya: decision head ffn down + SCORER_0 = auto() # laya: scorer LayerNorm + SCORER_1 = auto() # laya: scorer Linear(768,768) + SCORER_3 = auto() # laya: scorer Linear(768,1) + ACT_HEAD_0 = auto() # laya: act head Linear(d+4,256) + ACT_HEAD_2 = auto() # laya: act head Linear(256,2) CONV1D = auto() CONVNEXT_DW = auto() CONVNEXT_NORM = auto() @@ -1197,6 +1217,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.MELLUM: "mellum", MODEL_ARCH.INKLING: "inkling", MODEL_ARCH.NANBEIGE: "nanbeige", + MODEL_ARCH.LAYA: "laya", } VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = { @@ -1408,6 +1429,18 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.CLS: "cls", MODEL_TENSOR.CLS_OUT: "cls.output", MODEL_TENSOR.CLS_NORM: "cls.norm", + MODEL_TENSOR.TYPE_EMB: "type_emb", + MODEL_TENSOR.HEAD_ATTN_QKV: "head.{bid}.attn_qkv", + MODEL_TENSOR.HEAD_ATTN_OUT: "head.{bid}.attn_output", + MODEL_TENSOR.HEAD_ATTN_NORM: "head.{bid}.attn_norm", + MODEL_TENSOR.HEAD_FFN_NORM: "head.{bid}.ffn_norm", + MODEL_TENSOR.HEAD_FFN_UP: "head.{bid}.ffn_up", + MODEL_TENSOR.HEAD_FFN_DOWN: "head.{bid}.ffn_down", + MODEL_TENSOR.SCORER_0: "scorer.0", + MODEL_TENSOR.SCORER_1: "scorer.1", + MODEL_TENSOR.SCORER_3: "scorer.3", + MODEL_TENSOR.ACT_HEAD_0: "act_head.0", + MODEL_TENSOR.ACT_HEAD_2: "act_head.2", MODEL_TENSOR.CONV1D: "conv1d", MODEL_TENSOR.CONVNEXT_DW: "convnext.{bid}.dw", MODEL_TENSOR.CONVNEXT_NORM: "convnext.{bid}.norm", @@ -2063,6 +2096,31 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.CLS_OUT, MODEL_TENSOR.CLS_NORM, ], + MODEL_ARCH.LAYA: [ + # encoder: mmBERT (modern-bert naming) + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.TOKEN_EMBD_NORM, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_QKV, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_NORM, + # decision head + MODEL_TENSOR.TYPE_EMB, + MODEL_TENSOR.HEAD_ATTN_QKV, + MODEL_TENSOR.HEAD_ATTN_OUT, + MODEL_TENSOR.HEAD_ATTN_NORM, + MODEL_TENSOR.HEAD_FFN_NORM, + MODEL_TENSOR.HEAD_FFN_UP, + MODEL_TENSOR.HEAD_FFN_DOWN, + MODEL_TENSOR.SCORER_0, + MODEL_TENSOR.SCORER_1, + MODEL_TENSOR.SCORER_3, + MODEL_TENSOR.ACT_HEAD_0, + MODEL_TENSOR.ACT_HEAD_2, + ], MODEL_ARCH.NOMIC_BERT: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.TOKEN_EMBD_NORM, @@ -5165,6 +5223,15 @@ class VisionProjectorType: KEY_USE_PARALLEL_RESIDUAL = Keys.LLM.USE_PARALLEL_RESIDUAL KEY_TENSOR_DATA_LAYOUT = Keys.LLM.TENSOR_DATA_LAYOUT +# laya +KEY_HEAD_LAYERS = Keys.LLM.HEAD_LAYERS +KEY_N_QTYPE = Keys.LLM.N_QTYPE +KEY_MARKER_TOKEN_ID = Keys.LLM.MARKER_TOKEN_ID +KEY_MAX_LEN = Keys.LLM.MAX_LEN +KEY_HEAD_MAX_LEN = Keys.LLM.HEAD_MAX_LEN +KEY_TEMPERATURE = Keys.LLM.TEMPERATURE +KEY_ACT_CLASSES = Keys.LLM.ACT_CLASSES + # attention KEY_ATTENTION_HEAD_COUNT = Keys.Attention.HEAD_COUNT KEY_ATTENTION_HEAD_COUNT_KV = Keys.Attention.HEAD_COUNT_KV diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index 04735e49769b..51a2bf43155d 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -869,6 +869,27 @@ def add_swiglu_clamp_shexp(self, values: Sequence[float]) -> None: def add_hidden_act(self, value: str) -> None: self.add_string(Keys.LLM.HIDDEN_ACT.format(arch=self.arch), value) + def add_head_layers(self, value: int) -> None: + self.add_uint32(Keys.LLM.HEAD_LAYERS.format(arch=self.arch), value) + + def add_n_qtype(self, value: int) -> None: + self.add_uint32(Keys.LLM.N_QTYPE.format(arch=self.arch), value) + + def add_marker_token_id(self, value: int) -> None: + self.add_uint32(Keys.LLM.MARKER_TOKEN_ID.format(arch=self.arch), value) + + def add_max_len(self, value: int) -> None: + self.add_uint32(Keys.LLM.MAX_LEN.format(arch=self.arch), value) + + def add_head_max_len(self, value: int) -> None: + self.add_uint32(Keys.LLM.HEAD_MAX_LEN.format(arch=self.arch), value) + + def add_temperature(self, value: Sequence[float]) -> None: + self.add_array(Keys.LLM.TEMPERATURE.format(arch=self.arch), value) + + def add_act_classes(self, value: int) -> None: + self.add_uint32(Keys.LLM.ACT_CLASSES.format(arch=self.arch), value) + def add_expert_group_scale(self, value: float) -> None: self.add_float32(Keys.LLM.EXPERT_GROUP_SCALE.format(arch=self.arch), value) diff --git a/gguf-py/gguf/scripts/gguf_decision_spec.py b/gguf-py/gguf/scripts/gguf_decision_spec.py new file mode 100644 index 000000000000..641b831bea04 --- /dev/null +++ b/gguf-py/gguf/scripts/gguf_decision_spec.py @@ -0,0 +1,368 @@ +#!/usr/bin/env python3 +"""Get, set or verify the decision.spec contract of a GGUF without re-converting it. + + gguf_decision_spec.py get model.gguf + gguf_decision_spec.py set model.gguf spec.json [-o out.gguf] [--force] + gguf_decision_spec.py verify model.gguf [spec.json] + +decision.spec is a UTF-8 JSON string (see DECISION.md). `set` stores the file bytes as-is, +so its sha256 is the one llama-server --decision reports, and writes the mirror keys +decision.spec_version / layout / model_id / model_version that the server checks against it. +`get` writes the stored bytes and one "\n", without newline translation on any OS. + +`set` and `verify` apply the rules of the C++ loader (decision_spec_from_json in +tools/decision/decision-spec.cpp), so a spec that passes here also loads in the server. +Both run the cases of tests/decision/spec_cases.json (test-decision-calib and +tools/server/tests/unit/test_decision.py); change the two together. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import logging +import math +import os +import sys +from pathlib import Path + +# Necessary to load the local gguf package +if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists(): + sys.path.insert(0, str(Path(__file__).parent.parent.parent)) + +# gguf is imported by the commands only: validate_spec is stdlib-only for the tests + +logger = logging.getLogger("gguf-decision-spec") + +KEY_SPEC = "decision.spec" +KEY_VERSION = "decision.spec_version" +KEY_LAYOUT = "decision.layout" +KEY_MODEL_ID = "decision.model_id" +KEY_MODEL_VERSION = "decision.model_version" +MIRRORS = {KEY_LAYOUT: "layout", KEY_MODEL_ID: "model_id", KEY_MODEL_VERSION: "model_version"} +LAYOUTS = ("laya", "semif-letters") + + +INT32_MAX = 2**31 - 1 +QTYPES = ("noul", "choice", "score") +KERNELS = ("auto", "default", "repack", "blas", "repack+blas") # plan.kernels, as engine-laya.cpp reads it +LAYOUT_MAX_OPTIONS = {"laya": 20, "semif-letters": 16} +CONTRACTS = { # layout -> (input contracts, special-token contracts) + "laya": (("laya-v1", "laya-router-v1"), ("mask-to-space", "escape-control")), + "semif-letters": (("semif-v1",), ("escape",)), +} +CARD_SCHEMA = "atomic.executor-card/1" + + +def _reject_constant(name: str): + raise ValueError(f"{name} is not a JSON number") + + +def _is_int(v) -> bool: + return isinstance(v, int) and not isinstance(v, bool) + + +def _is_number(v) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + + +def _positive(v) -> bool: + return _is_number(v) and v > 0 + + +def _opt(obj: dict, key: str, check, what: str, default): + """Value of an optional key (null = absent), like get_opt in decision-spec.cpp.""" + v = obj.get(key) + if v is None: + return default + if not check(v): + raise ValueError(f"{key} must be {what}") + return v + + +def _opt_str(obj: dict, key: str, default): + return _opt(obj, key, lambda v: isinstance(v, str), "a string", default) + + +def _opt_count(obj: dict, key: str, default): + return _opt(obj, key, lambda v: _is_int(v) and 0 <= v <= INT32_MAX, "a non-negative integer", default) + + +def _is_uint_str(s: str) -> bool: + return s != "" and all("0" <= c <= "9" for c in s) + + +def _valid_bucket(b: str) -> bool: + if b == "*" or _is_uint_str(b): + return True + if len(b) > 1 and b.endswith("+"): + return _is_uint_str(b[:-1]) + lo, dash, hi = b.partition("-") + return dash != "" and _is_uint_str(lo) and _is_uint_str(hi) + + +def _bucket_rank(b: str, k: int) -> int: + """0 exact "N", 1 range "A-B", 2 open "N+", 3 "*", -1 no match (decision-calib.cpp).""" + if b == "*": + return 3 + if b.endswith("+"): + return 2 if k >= int(b[:-1]) else -1 + if "-" in b: + lo, _, hi = b.partition("-") + return 1 if int(lo) <= k <= int(hi) else -1 + return 0 if int(b) == k else -1 + + +def _check_temperature(t) -> None: + if not isinstance(t, dict): + raise ValueError("calibration.temperature must be an object") + for k, v in t.items(): + if k not in ("all",) + QTYPES: + raise ValueError(f"calibration.temperature: unknown question type {k!r}") + if isinstance(v, dict): + for b, x in v.items(): + if not _valid_bucket(b): + raise ValueError(f"calibration.temperature.{k}: bad option-count bucket {b!r}") + if not _positive(x): + raise ValueError(f"calibration.temperature.{k}.{b} must be a positive number") + elif not _positive(v): + raise ValueError(f"calibration.temperature.{k} must be a positive number or a bucket object") + + +def _covered(temperature: dict, qtype: str, k: int) -> bool: + entry = temperature.get(qtype, temperature.get("all")) + if entry is None: + return False + if not isinstance(entry, dict): + return True + return any(_bucket_rank(b, k) >= 0 for b in entry) + + +def _check_calibration(c, max_options: int) -> None: + if not isinstance(c, dict): + raise ValueError("calibration must be an object") + method = _opt_str(c, "method", "none") + required = _opt(c, "required", lambda v: isinstance(v, bool), "a boolean", False) + _opt_str(c, "version", "") + if method not in ("temperature", "none"): + raise ValueError('calibration.method must be "temperature" or "none"') + if "clamp" in c: + cl = c["clamp"] + if not isinstance(cl, list) or len(cl) != 2 or not _positive(cl[0]) or not _positive(cl[1]) or cl[0] > cl[1]: + raise ValueError("calibration.clamp must be [min, max] with 0 < min <= max") + temperature = c.get("temperature") + if temperature is not None: + _check_temperature(temperature) + calibrated = method == "temperature" and bool(temperature) + if required and not calibrated: + raise ValueError("calibration is required but has no temperatures") + if required: + # a required calibration never falls back to T = 1 + for qtype in QTYPES: + for k in range(2, (2 if qtype == "noul" else max_options) + 1): + if not _covered(temperature, qtype, k): + raise ValueError(f"calibration is required but has no temperature for {qtype} with {k} options") + + +def _check_router(r) -> None: + if not isinstance(r, dict): + raise ValueError("router must be an object or null") + try: + schema = _opt_str(r, "card_schema", CARD_SCHEMA) + renderer = _opt_str(r, "card_renderer", "card-v1") + _opt_count(r, "max_card_tokens", -1) + except ValueError as e: + raise ValueError(f"router.{e}") from None + if schema != CARD_SCHEMA: + raise ValueError(f"router.card_schema must be {CARD_SCHEMA!r}") + if renderer != "card-v1": + raise ValueError('router.card_renderer must be "card-v1"') + q = r.get("question") + if q is not None: + ins = q.get("instructions") if isinstance(q, dict) else None + if not isinstance(q, dict) or q.get("type") != "noul" or not isinstance(ins, str) or ins.strip() == "": + raise ValueError("router.question must be a noul question with instructions") + if q.get("criteria") is not None and not isinstance(q["criteria"], dict): + raise ValueError("router.question.criteria must be an object with true/false descriptions") + # the laya request rules for a noul question (laya_question_parse), checked at load + if isinstance(q.get("criteria"), dict) and not {str(k).lower() for k in q["criteria"]} <= {"true", "false"}: + raise ValueError("router.question.criteria must be keyed only true/false") + labels = q.get("labels") + if labels is not None: + ok = isinstance(labels, dict) and set(labels) == {"false", "true"} and all(isinstance(v, str) for v in labels.values()) + if not ok or not labels["false"].strip() or not labels["true"].strip() or labels["false"].strip() == labels["true"].strip(): + raise ValueError("router.question.labels must map exactly 'false' and 'true' to distinct non-empty strings") + c = r.get("calibration") + if c is not None: + if not isinstance(c, dict) or c.get("method") != "platt": + raise ValueError('router.calibration.method must be "platt"') + if not _is_number(c.get("a")) or not _is_number(c.get("b")): + raise ValueError("router.calibration needs finite numbers a and b") + + +def validate_spec(spec) -> None: + """Raise ValueError on anything decision_spec_from_json rejects (full specs only).""" + if not isinstance(spec, dict): + raise ValueError("decision spec must be a JSON object") + if not _is_int(spec.get("spec_version")) or spec["spec_version"] != 1: + raise ValueError("spec_version must be 1") + layout = spec.get("layout") + if not isinstance(layout, str) or layout not in LAYOUTS: + raise ValueError(f"layout must be one of {LAYOUTS}") + inputs, specials = CONTRACTS[layout] + _opt_str(spec, "model_id", "") + _opt_str(spec, "model_version", "") + input_contract = _opt_str(spec, "input_contract", inputs[0]) + special_tokens = _opt_str(spec, "special_tokens", specials[0]) + confidence = _opt_str(spec, "confidence", "laya" if layout == "laya" else "max_p") + if confidence not in ("laya", "typesafe", "max_p"): + raise ValueError('confidence must be "laya", "typesafe" or "max_p"') + if input_contract not in inputs: + raise ValueError(f"input_contract must be one of {inputs} for layout {layout}") + if special_tokens not in specials: + raise ValueError(f"special_tokens must be one of {specials} for layout {layout}") + if input_contract == "laya-router-v1" and special_tokens != "escape-control": + raise ValueError('input_contract "laya-router-v1" needs special_tokens "escape-control"') + max_options = 0 + limits = spec.get("limits") + if limits is not None: + if not isinstance(limits, dict): + raise ValueError("limits must be an object") + try: + max_options = _opt_count(limits, "max_options", 0) + _opt_count(limits, "max_candidates", 16) + _opt_count(limits, "max_prompt_tokens", 0) + except ValueError as e: + raise ValueError(f"limits.{e}") from None + layout_max = LAYOUT_MAX_OPTIONS[layout] + max_options = min(max_options, layout_max) if max_options > 0 else layout_max + if spec.get("calibration") is not None: + _check_calibration(spec["calibration"], max_options) + plan = spec.get("plan") + if plan is not None and (not isinstance(plan, dict) or ("name" in plan and not isinstance(plan["name"], str))): + raise ValueError("plan must be an object with a string name") + if plan is not None and "kernels" in plan and plan["kernels"] not in KERNELS: + raise ValueError("plan.kernels must be auto, default, repack, blas or repack+blas") + if spec.get("router") is not None: + _check_router(spec["router"]) + + +def parse_spec(text: str) -> dict: + """Parse and validate a spec; NaN/Infinity are rejected like the C++ parser.""" + spec = json.loads(text, parse_constant=_reject_constant) + validate_spec(spec) + return spec + + +def mirror_values(spec: dict) -> dict[str, str]: + return {key: spec[field] for key, field in MIRRORS.items() if isinstance(spec.get(field), str)} + + +def cmd_get(args) -> int: + import gguf + from gguf.scripts.gguf_new_metadata import get_field_data + reader = gguf.GGUFReader(args.model, "r") + text = get_field_data(reader, KEY_SPEC) + if text is None: + print(f"{args.model}: no {KEY_SPEC}", file=sys.stderr) + return 1 + # the stored bytes plus one newline, on every OS: print() would turn each \n into \r\n on + # Windows, and "get > spec.json" would no longer hash to the spec_sha256 the server reports + sys.stdout.flush() + sys.stdout.buffer.write(text.encode("utf-8") + b"\n") + sys.stdout.flush() + return 0 + + +def cmd_set(args) -> int: + import gguf + from gguf.scripts.gguf_new_metadata import MetadataDetails, copy_with_new_metadata, get_field_data + text = Path(args.spec).read_bytes().decode("utf-8") + spec = parse_spec(text) + + reader = gguf.GGUFReader(args.model, "r") + arch = get_field_data(reader, gguf.Keys.General.ARCHITECTURE) + if (arch == "laya") != (spec["layout"] == "laya"): + raise ValueError(f"layout {spec['layout']!r} does not fit a {arch!r} GGUF") + + out = Path(args.output) if args.output else Path(args.model) + in_place = out.resolve() == Path(args.model).resolve() + if out.exists() and not in_place and not args.force: + raise FileExistsError(f"{out} exists; pass --force to overwrite") + + new_metadata = { + KEY_SPEC: MetadataDetails(gguf.GGUFValueType.STRING, text), + KEY_VERSION: MetadataDetails(gguf.GGUFValueType.UINT32, 1), + } + mirrors = mirror_values(spec) + for key, value in mirrors.items(): + new_metadata[key] = MetadataDetails(gguf.GGUFValueType.STRING, value) + # stale mirror keys from an older spec must not outlive it + remove = [key for key in MIRRORS if key not in mirrors and reader.get_field(key) is not None] + + tmp = out.with_name(out.name + ".tmp") + writer = gguf.GGUFWriter(tmp, arch=arch, endianess=reader.endianess) + alignment = get_field_data(reader, gguf.Keys.General.ALIGNMENT) + if alignment is not None: + writer.data_alignment = alignment + copy_with_new_metadata(reader, writer, new_metadata, remove) + del reader + os.replace(tmp, out) + print(f"{out}: {KEY_SPEC} sha256 {hashlib.sha256(text.encode('utf-8')).hexdigest()}") + return 0 + + +def cmd_verify(args) -> int: + import gguf + from gguf.scripts.gguf_new_metadata import get_field_data + reader = gguf.GGUFReader(args.model, "r") + text = get_field_data(reader, KEY_SPEC) + if text is None: + print(f"{args.model}: no {KEY_SPEC}", file=sys.stderr) + return 1 + spec = parse_spec(text) + problems = [] + version = get_field_data(reader, KEY_VERSION) + if version is not None and version != spec["spec_version"]: + problems.append(f"{KEY_VERSION}={version} but the spec says {spec['spec_version']}") + for key, field in MIRRORS.items(): + value = get_field_data(reader, key) + if value is not None and value != spec.get(field): + problems.append(f"{key}={value!r} but the spec says {spec.get(field)!r}") + arch = get_field_data(reader, gguf.Keys.General.ARCHITECTURE) + if (arch == "laya") != (spec["layout"] == "laya"): + problems.append(f"layout {spec['layout']!r} does not fit a {arch!r} GGUF") + if args.spec is not None and Path(args.spec).read_bytes().decode("utf-8") != text: + problems.append(f"{KEY_SPEC} differs from {args.spec}") + for p in problems: + print(f"FAIL {p}", file=sys.stderr) + print(f"{args.model}: {KEY_SPEC} sha256 {hashlib.sha256(text.encode('utf-8')).hexdigest()} {'FAIL' if problems else 'OK'}") + return 1 if problems else 0 + + +def main() -> None: + parser = argparse.ArgumentParser(description="Get, set or verify the decision.spec metadata of a GGUF") + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("get", help="print decision.spec") + p.add_argument("model", type=Path) + p = sub.add_parser("set", help="store a spec file as decision.spec (+ mirror keys)") + p.add_argument("model", type=Path) + p.add_argument("spec", type=Path) + p.add_argument("-o", "--output", type=Path, help="write a copy instead of replacing the input") + p.add_argument("--force", action="store_true", help="overwrite an existing output file") + p = sub.add_parser("verify", help="check the mirror keys (and optionally the bytes of a spec file)") + p.add_argument("model", type=Path) + p.add_argument("spec", type=Path, nargs="?") + parser.add_argument("--verbose", action="store_true") + args = parser.parse_args() + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) + try: + rc = {"get": cmd_get, "set": cmd_set, "verify": cmd_verify}[args.command](args) + except (ValueError, FileExistsError, OSError) as e: + print(f"error: {e}", file=sys.stderr) + rc = 2 + sys.exit(rc) + + +if __name__ == "__main__": + main() diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index 1314de002241..e8edd978df7e 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -1382,6 +1382,26 @@ class TensorNameMap: MODEL_TENSOR.CLS_NORM: ( "head.norm", # modern-bert ), + + # laya decision head + MODEL_TENSOR.TYPE_EMB: ( + "type_emb", + ), + MODEL_TENSOR.SCORER_0: ( + "scorer.0", + ), + MODEL_TENSOR.SCORER_1: ( + "scorer.1", + ), + MODEL_TENSOR.SCORER_3: ( + "scorer.3", + ), + MODEL_TENSOR.ACT_HEAD_0: ( + "act_head.0", + ), + MODEL_TENSOR.ACT_HEAD_2: ( + "act_head.2", + ), ############################################################################# MODEL_TENSOR.CONVNEXT_DW: ( @@ -2601,6 +2621,26 @@ class TensorNameMap: # architecture-specific block mappings arch_block_mappings_cfg: dict[MODEL_ARCH, dict[MODEL_TENSOR, tuple[str, ...]]] = { + MODEL_ARCH.LAYA: { + MODEL_TENSOR.HEAD_ATTN_QKV: ( + "head.layers.{bid}.self_attn.in_proj", + ), + MODEL_TENSOR.HEAD_ATTN_OUT: ( + "head.layers.{bid}.self_attn.out_proj", + ), + MODEL_TENSOR.HEAD_ATTN_NORM: ( + "head.layers.{bid}.norm1", + ), + MODEL_TENSOR.HEAD_FFN_NORM: ( + "head.layers.{bid}.norm2", + ), + MODEL_TENSOR.HEAD_FFN_UP: ( + "head.layers.{bid}.linear1", + ), + MODEL_TENSOR.HEAD_FFN_DOWN: ( + "head.layers.{bid}.linear2", + ), + }, MODEL_ARCH.INKLING: { MODEL_TENSOR.ATTN_NORM: ( "model.layers.{bid}.attn_norm", diff --git a/scripts/bench-decision-pytorch.py b/scripts/bench-decision-pytorch.py new file mode 100644 index 000000000000..b6be1f781375 --- /dev/null +++ b/scripts/bench-decision-pytorch.py @@ -0,0 +1,713 @@ +#!/usr/bin/env python3 +"""PyTorch Laya reference on the llama-decision-bench suite: equal inputs first, then timing. + +Usage (run with the laya reference venv, e.g. ~/.cache/laya-ref/.venv/bin/python): + # 1. engine side: render every suite request through llama-server --decision --decision-debug + # (router states + token ids + raw logits of the engine) + bench-decision-pytorch.py inputs --server build/bin/llama-server --model laya-f32.gguf -t 2 \ + [--kernels K] [--spec FILE] [--suite tests/decision/bench/suite.jsonl] -o inputs.json + # 2. equal-input check: reference fp32 input ids and raw logits against the engine F32 ones + bench-decision-pytorch.py check --ckpt multilingual --inputs inputs.json -t 2 [--tol-logit 1e-3] -o check.json + # 3. timing (refused unless check.json passed for the same suite and checkpoint) + bench-decision-pytorch.py bench --ckpt multilingual --inputs inputs.json --check check.json -t 2 \ + [--dtype fp32|bf16] [--repeat 10] [--warmup 1] [--idle-ms 60000] [--router-mode sequential|batch] \ + [--filter TEXT] [--label pytorch] -o OUT_DIR + python3 scripts/bench-decision-report.py OUT_DIR ENGINE_DIR # side-by-side tables + +--ckpt is a checkpoint directory (with rl_agent_config.json) or a name found in the Hugging Face +cache: multilingual (convaiinnovations/laya-multilingual), laya (English), typed-decisions. + +Same requests. systemone bodies go to Agent.system_one as they are. A router request is one +independent noul sequence per candidate over "\\n\\nsuccess criterion: ...\\n\\ntask: ...". +That state is not rendered here: `inputs` takes it from the engine (POST /v1/decision/render), so +there is no second card renderer that could drift. The router question is spec.router.question of +the model (GGUF decision.spec or --spec), else the built-in one (DECISION.md, "laya mapping"). The +check then compares the reference input ids with the engine token ids byte for byte, so a wrong +question or state fails there, before any timing. + +Same boundaries as llama-decision-bench "total": body text -> JSON, request checks, tokenize, +forward, post-processing and the response text. Process start, model load and HTTP are outside. +The engine also renders the cards inside its total (string work, microseconds); here the states +come pre-rendered. Router timing: --router-mode sequential (default) calls system_one once per +candidate, one sequence each, as the engine plan does; batch sends all candidates through one +predict_batch (padded rows, the PyTorch throughput path) and is labelled as such. + +Measured per request: wall ms (warmup and repeat rounds interleaved over the suite, like the +engine), CPU seconds (getrusage user + system of the process, all threads), p50/p95/p99 with +linear interpolation. Per process: RSS / footprint after load, after warmup, peak (macOS +task_info as in decision-bench.cpp, Linux /proc/self/status), time to ready (process start -> +torch imported -> model loaded -> first answer), and with --idle-ms the first request after an +idle gap (every request once, as decision-bench --idle-ms). torch.set_num_threads(t), +set_num_interop_threads(1), inference_mode. fp32 is the reference; bf16 is the reference's own CPU +autocast (LAYA_CPU_AMP=bf16); when autocast falls back to fp32 the result says so. +""" + +import argparse +import ctypes +import ctypes.util +import hashlib +import json +import math +import os +import platform +import re +import resource +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.request + +T_SCRIPT = time.time() + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +DEFAULT_SUITE = os.path.join(ROOT, "tests", "decision", "bench", "suite.jsonl") +BENCH_NAME = "laya-pytorch-bench" +HF_NAMES = { + "multilingual": "convaiinnovations/laya-multilingual", + "laya-multilingual": "convaiinnovations/laya-multilingual", + "laya": "convaiinnovations/laya", + "english": "convaiinnovations/laya", + "typed-decisions": "convaiinnovations/laya-typed-decisions", + "laya-typed-decisions": "convaiinnovations/laya-typed-decisions", +} +# DECISION.md, "laya mapping"; used when the model spec has no router question +ROUTER_DEFAULT_QUESTION = { + "type": "noul", + "instructions": "Will the executor meet the success criterion on this task?", + "criteria": {"true": "meets the criterion", "false": "does not meet the criterion"}, +} + + +def die(msg): + print("error: " + msg, file=sys.stderr, flush=True) + sys.exit(1) + + +# +# suite, statistics, machine facts +# + +def load_suite(path, filt=None): + if not os.path.isfile(path): + die("no %s. Run: python3 tests/decision/bench/gen_suite.py" % path) + raw = open(path, "rb").read() + reqs, seen = [], set() + for n, line in enumerate(raw.decode("utf-8").splitlines(), 1): + if not line.strip(): + continue + r = json.loads(line) + if not isinstance(r.get("id"), str) or not isinstance(r.get("body"), dict): + die("%s:%d: needs a string id and an object body" % (path, n)) + if r["id"] in seen: + die("%s:%d: duplicate id %s" % (path, n, r["id"])) + seen.add(r["id"]) + r.setdefault("endpoint", "systemone") + r.setdefault("group", r["endpoint"]) + if r["endpoint"] not in ("systemone", "router"): + die("%s:%d: endpoint must be systemone or router" % (path, n)) + if filt and filt not in r["id"] and filt not in r["group"]: + continue + reqs.append(r) + if not reqs: + die("no requests in %s%s" % (path, " match " + filt if filt else "")) + return reqs, hashlib.sha256(raw).hexdigest() + + +def pct(v, p): + if not v: + return 0.0 + v = sorted(v) + pos = p / 100.0 * (len(v) - 1) + lo = int(math.floor(pos)) + hi = min(lo + 1, len(v) - 1) + return v[lo] + (v[hi] - v[lo]) * (pos - lo) + + +def stats(v): + return {"n": len(v), "mean": sum(v) / len(v) if v else 0.0, "min": min(v) if v else 0.0, "p50": pct(v, 50), + "p95": pct(v, 95), "p99": pct(v, 99), "max": max(v) if v else 0.0} + + +def sh(cmd): + try: + return subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout.strip() + except Exception: + return "" + + +def power_source(): + if sys.platform == "darwin": + m = re.search(r"'(.*?)'", sh(["pmset", "-g", "batt"])) + return m.group(1) if m else "" + for p in ("/sys/class/power_supply/AC/online", "/sys/class/power_supply/ACAD/online", "/sys/class/power_supply/ADP1/online"): + if os.path.exists(p): + return "AC Power" if open(p).read().strip() == "1" else "Battery Power" + return "" + + +def load_avg(): + try: + return " ".join("%.2f" % x for x in os.getloadavg()) + except OSError: + return "" + + +def top_cpu(): + out = sh(["ps", "-Ao", "pcpu=,comm=", "-r"] if sys.platform == "darwin" else ["ps", "-eo", "pcpu=,comm=", "--sort=-pcpu"]) + rows = [] + for line in out.splitlines()[:5]: + p, _, c = line.strip().partition(" ") + rows.append("%s %s" % (p, c.strip().split("/")[-1])) + return rows + + +def machine_facts(): + f = {"host": platform.node(), "kernel": " ".join(platform.uname()[i] for i in (0, 2, 4)), "python": sys.version.split()[0]} + if sys.platform == "darwin": + f["cpu"] = sh(["sysctl", "-n", "machdep.cpu.brand_string"]) + f["cores"] = "%s (%s P + %s E)" % (sh(["sysctl", "-n", "hw.physicalcpu"]), sh(["sysctl", "-n", "hw.perflevel0.physicalcpu"]), + sh(["sysctl", "-n", "hw.perflevel1.physicalcpu"])) + f["memory_gb"] = int(sh(["sysctl", "-n", "hw.memsize"]) or 0) // 2**30 + f["os"] = "macOS %s (%s)" % (sh(["sw_vers", "-productVersion"]), sh(["sw_vers", "-buildVersion"])) + m = re.search(r"(lowpowermode|powermode)\s+(\d+)", sh(["pmset", "-g"])) + f["low_power_mode"] = m.group(2) if m else "" + else: + try: + f["cpu"] = next(l.split(":", 1)[1].strip() for l in open("/proc/cpuinfo") if l.startswith("model name")) + except Exception: + f["cpu"] = platform.processor() + f["cores"] = "%d logical" % os.cpu_count() + try: + f["memory_gb"] = int(next(l.split()[1] for l in open("/proc/meminfo") if l.startswith("MemTotal"))) // 2**20 + except Exception: + pass + return f + + +# +# process facts (same numbers as decision-bench.cpp bench_mem_now / bench_cpu_seconds) +# + +def cpu_seconds(): + ru = resource.getrusage(resource.RUSAGE_SELF) + return ru.ru_utime + ru.ru_stime + + +_libc = ctypes.CDLL(ctypes.util.find_library("c")) if sys.platform == "darwin" else None + + +def mem_now(): + m = {"rss": -1, "rss_peak": -1, "footprint": -1, "footprint_peak": -1} + if sys.platform == "darwin": + # task_vm_info_data_t as uint64 words: resident_size [2], resident_size_peak [3], + # phys_footprint [18] (rev1), ledger_phys_footprint_peak [21] (rev3) + buf = (ctypes.c_uint64 * 64)() + count = ctypes.c_uint32(64 * 2) + task = ctypes.c_uint32.in_dll(_libc, "mach_task_self_") + if _libc.task_info(task, 22, ctypes.byref(buf), ctypes.byref(count)) == 0: # TASK_VM_INFO + n = count.value // 2 + m["rss"], m["rss_peak"] = int(buf[2]), int(buf[3]) + if n > 18: + m["footprint"] = int(buf[18]) + if n > 21: + m["footprint_peak"] = int(buf[21]) + elif os.path.exists("/proc/self/status"): + for line in open("/proc/self/status"): + k, _, v = line.partition(":") + if k in ("VmRSS", "VmHWM", "RssAnon"): + b = int(v.split()[0]) * 1024 + m[{"VmRSS": "rss", "VmHWM": "rss_peak", "RssAnon": "footprint"}[k]] = b + return m + + +def process_start(): + """Wall time of the process start and where it came from.""" + if os.environ.get("BENCH_SPAWN_T"): + return float(os.environ["BENCH_SPAWN_T"]), "BENCH_SPAWN_T" + try: + if sys.platform == "darwin": + # sysctl kern.proc.pid: kinfo_proc starts with extern_proc.p_starttime (timeval) + mib = (ctypes.c_int * 4)(1, 14, 1, os.getpid()) + buf = ctypes.create_string_buffer(1024) + size = ctypes.c_size_t(1024) + if _libc.sysctl(mib, 4, buf, ctypes.byref(size), None, 0) == 0: + sec = int.from_bytes(buf.raw[0:8], "little") + usec = int.from_bytes(buf.raw[8:12], "little") + t = sec + usec * 1e-6 + if 0 < T_SCRIPT - t < 600: + return t, "kern.proc.pid" + elif os.path.exists("/proc/self/stat"): + ticks = int(open("/proc/self/stat").read().rsplit(")", 1)[1].split()[19]) + since = time.clock_gettime(time.CLOCK_BOOTTIME) - ticks / os.sysconf("SC_CLK_TCK") + return time.time() - since, "/proc/self/stat" + except Exception: + pass + return T_SCRIPT, "script start (interpreter start not counted)" + + +# +# router question of the model spec +# + +def router_question(model_path, spec_path): + spec = None + if spec_path: + spec = json.load(open(spec_path, encoding="utf-8")) + else: + sys.path.insert(0, os.path.join(ROOT, "gguf-py")) + try: + import gguf + from gguf.scripts.gguf_new_metadata import get_field_data + except ImportError as e: + die("cannot import gguf-py (%s); run with the laya venv python or pass --spec" % e) + text = get_field_data(gguf.GGUFReader(model_path, "r"), "decision.spec") + spec = json.loads(text) if text else None + q = dict(ROUTER_DEFAULT_QUESTION) + r = (spec or {}).get("router") or {} + if r.get("question"): + q = dict(r["question"]) + if q.get("criteria") is None: + q["criteria"] = ROUTER_DEFAULT_QUESTION["criteria"] + return q, ("spec" if r.get("question") else "built-in") + + +# +# inputs: the engine's view of every request +# + +def start_server(server, model, threads, kernels, spec, log_path): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + cmd = [server, "--decision", "--decision-debug", "--decision-allow-uncalibrated", "-m", model, "--device", "none", + "-t", str(threads), "--host", "127.0.0.1", "--port", str(port), "--decision-max-items", "16"] + cmd += (["--decision-kernels", kernels] if kernels else []) + (["--decision-spec", spec] if spec else []) + print(" ".join(cmd), flush=True) + log = open(log_path, "w") + proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, LC_ALL="C")) + base = "http://127.0.0.1:%d" % port + t0 = time.time() + while True: + try: + with urllib.request.urlopen(base + "/health", timeout=2) as r: + if r.status == 200: + return proc, base, cmd + except Exception: + pass + if proc.poll() is not None or time.time() - t0 > 180: + proc.kill() + die("server did not start, see " + log_path) + time.sleep(0.2) + + +def post(base, path, body): + data = json.dumps(body, ensure_ascii=True).encode("ascii") + req = urllib.request.Request(base + path, data=data, headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=600) as r: + return json.loads(r.read().decode("utf-8")) + except urllib.error.HTTPError as e: + die("%s: http %d: %s" % (path, e.code, e.read().decode("utf-8", "replace")[:400])) + + +def cmd_inputs(a): + for p in (a.server, a.model): + if not os.path.exists(p): + die("missing " + p) + reqs, suite_sha = load_suite(a.suite, a.filter) + rq, rq_source = router_question(a.model, a.spec) + out = {"kind": "decision-inputs", "version": 1, "suite": a.suite, "suite_sha256": suite_sha, + "router_question": rq, "router_question_source": rq_source, "requests": []} + proc, base, cmd = start_server(a.server, a.model, a.threads, a.kernels, a.spec, a.output + ".server.log") + try: + props = json.loads(urllib.request.urlopen(base + "/props").read()) + out["engine"] = {"model": a.model, "cmd": cmd, "build_info": props.get("build_info"), "decision": props["decision"]} + d = props["decision"] + print("engine: layout %s, plan %s / router %s, kernels %s, %s threads, input_contract %s, special_tokens %s" % ( + d["layout"], d["plan"]["name"], d["plan"]["router"], d["plan"]["kernels"], d["plan"]["n_threads"], + d.get("input_contract"), d.get("special_tokens")), flush=True) + for r in reqs: + rec = {"id": r["id"], "endpoint": r["endpoint"], "group": r["group"], "body": r["body"], "items": []} + if r["endpoint"] == "systemone": + res = post(base, "/v1/systemone", r["body"]) + for qid in r["body"]["questions"]: + dbg = res["answers"][qid]["debug"] + rec["items"].append({"id": qid, "tokens": dbg["tokens"], "logits": dbg["logits"], "n_state_cut": dbg["n_state_cut"]}) + else: + ren = post(base, "/v1/decision/render", r["body"])["items"] + sc = post(base, "/v1/router/score", r["body"])["scores"] + if [x["id"] for x in ren] != [c["id"] for c in r["body"]["candidates"]] or [x["id"] for x in sc] != [x["id"] for x in ren]: + die("%s: render / score candidate order differs from the request" % r["id"]) + for x, s in zip(ren, sc): + if x["instructions"] != rq["instructions"] or x["type"] != "noul" or x["keys"] != ["false", "true"]: + die("%s: engine router question %r differs from %r (%s); pass --spec" % (r["id"], x["instructions"], rq["instructions"], rq_source)) + if s["debug"]["tokens"] != x["tokens"]: + die("%s/%s: /v1/router/score tokens differ from /v1/decision/render" % (r["id"], x["id"])) + rec["items"].append({"id": x["id"], "state": x["state"], "tokens": x["tokens"], "logits": s["debug"]["logits"], + "n_state_cut": x["n_state_cut"]}) + n_tok = sum(len(i["tokens"]) for i in rec["items"]) + print(" %-16s %-10s %2d items %5d tokens" % (r["id"], r["endpoint"], len(rec["items"]), n_tok), flush=True) + out["requests"].append(rec) + finally: + proc.terminate() + proc.wait(timeout=30) + with open(a.output, "w", encoding="utf-8") as f: + json.dump(out, f, ensure_ascii=False, indent=1) + print("wrote %s (%d requests; router question: %s)" % (a.output, len(out["requests"]), rq_source), flush=True) + + +# +# reference loading +# + +def resolve_ckpt(name): + if os.path.isfile(os.path.join(name, "rl_agent_config.json")): + path = os.path.abspath(name) + m = re.search(r"models--([^/]+)--([^/]+)/snapshots/[^/]+(?:/(\w[\w-]*))?$", path) + family = (m.group(3) and "laya-" + m.group(3)) or (m.group(2) if m else os.path.basename(path)) + return path, family + repo = HF_NAMES.get(name) + if not repo: + die("--ckpt %s: not a checkpoint directory and not one of %s" % (name, ", ".join(sorted(HF_NAMES)))) + hub = os.environ.get("HF_HUB_CACHE") or os.path.join(os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface")), "hub") + snaps = os.path.join(hub, "models--" + repo.replace("/", "--"), "snapshots") + cands = sorted((os.path.join(snaps, s) for s in os.listdir(snaps)) if os.path.isdir(snaps) else [], + key=os.path.getmtime, reverse=True) + cands = [c for c in cands if os.path.isfile(os.path.join(c, "rl_agent_config.json"))] + if not cands: + die("no %s in %s. Run: hf download %s" % (repo, hub, repo)) + return cands[0], repo.split("/")[1] + + +def load_torch(threads): + t0 = time.time() + import torch + torch.set_num_threads(threads) + torch.set_num_interop_threads(1) + return torch, (time.time() - t0) * 1000 + + +def load_agent(torch, ckpt, dtype): + os.environ["HF_HUB_OFFLINE"] = "1" + if dtype == "bf16": + os.environ["LAYA_CPU_AMP"] = "bf16" + else: + os.environ.pop("LAYA_CPU_AMP", None) + from laya.agent import Agent + agent = Agent(ckpt, device="cpu") + agent.model.eval() + if agent.device.type != "cpu": + die("reference is not on the CPU") + if dtype == "fp32" and (agent.amp_enabled or agent.dtype != torch.float32): + die("reference fp32 is not fp32 (LAYA_CPU_AMP set?)") + if dtype == "bf16" and not agent.amp_enabled: + die("reference did not enable bf16 autocast") + return agent + + +def torch_facts(torch, agent): + import laya + return {"torch": torch.__version__, "laya": getattr(laya, "__version__", "?"), "num_threads": torch.get_num_threads(), + "interop_threads": torch.get_num_interop_threads(), "mkldnn": torch.backends.mkldnn.is_available(), + "openmp": torch.backends.openmp.is_available(), "config": torch.__config__.show(), + "parallel_info": torch.__config__.parallel_info(), "max_len": agent.cfg.get("max_len"), + "head_max_len": agent.cfg.get("head_max_len")} + + +def read_inputs(path, suite_filter=None): + if not os.path.isfile(path): + die("no %s. Run: bench-decision-pytorch.py inputs --server BIN/llama-server --model laya-f32.gguf -t 2 -o %s" % (path, path)) + d = json.load(open(path, encoding="utf-8")) + if d.get("kind") != "decision-inputs": + die("%s is not a bench-decision-pytorch.py inputs file" % path) + if suite_filter: + d["requests"] = [r for r in d["requests"] if suite_filter in r["id"] or suite_filter in r["group"]] + if not d["requests"]: + die("no requests match " + suite_filter) + return d + + +# +# check: reference fp32 input ids and raw logits against the engine +# + +def reference_rows(torch, agent, state, questions): + """Agent request path without the answer rounding: {qid: (input_ids, raw logits)}.""" + from laya.agent import Agent + from laya.common import collate_items + qids = list(questions) + for qid in qids: + Agent._check_question(qid, questions[qid]) + internal = {qid: Agent._to_internal(questions[qid]) for qid in qids} + enc = agent._encode_state(state, qids, internal) + b = collate_items([enc], agent.tok.pad_token_id) + with torch.inference_mode(): + logits, _ = agent.model(b["input_ids"], b["attention_mask"], b["marker_pos"], b["marker_mask"], b["qtype"]) + logits = logits.float().numpy() + return {qid: (enc[r]["ids"], logits[r, :len(enc[r]["markers"])].tolist()) for r, qid in enumerate(qids)} + + +def softmax(z): + m = max(z) + e = [math.exp(x - m) for x in z] + s = sum(e) + return [x / s for x in e] + + +def cmd_check(a): + inp = read_inputs(a.inputs) + ckpt, family = resolve_ckpt(a.ckpt) + torch, _ = load_torch(a.threads) + agent = load_agent(torch, ckpt, "fp32") + print("reference %s (%s), fp32, %d threads; engine %s" % (family, ckpt, a.threads, inp["engine"]["model"]), flush=True) + rq = inp["router_question"] + rows, bad = [], [] + for r in inp["requests"]: + if r["endpoint"] == "systemone": + ref = reference_rows(torch, agent, r["body"]["state"], r["body"]["questions"]) + pairs = [(it["id"], ref[it["id"]], it) for it in r["items"]] + else: + pairs = [] + for it in r["items"]: + ref = reference_rows(torch, agent, it["state"], {it["id"]: rq}) + pairs.append((it["id"], ref[it["id"]], it)) + for qid, (ids, logits), it in pairs: + where = "%s/%s" % (r["id"], qid) + if ids != it["tokens"]: + first = next((i for i in range(min(len(ids), len(it["tokens"]))) if ids[i] != it["tokens"][i]), min(len(ids), len(it["tokens"]))) + bad.append("%s: input ids differ at %d (reference %d tokens, engine %d)" % (where, first, len(ids), len(it["tokens"]))) + continue + d = max(abs(x - y) for x, y in zip(logits, it["logits"])) + am = max(range(len(logits)), key=logits.__getitem__) == max(range(len(it["logits"])), key=it["logits"].__getitem__) + dp = max(abs(x - y) for x, y in zip(softmax(logits), softmax(it["logits"]))) + rows.append({"item": where, "n_tokens": len(ids), "max_abs_dlogit": d, "argmax_same": am, "max_abs_dp": dp, + "reference_logits": logits, "engine_logits": it["logits"]}) + if d > a.tol_logit or not am: + bad.append("%s: max|dlogit| %.3e%s" % (where, d, "" if am else ", argmax differs")) + worst = max(rows, key=lambda x: x["max_abs_dlogit"]) if rows else None + res = {"kind": "decision-equal-input-check", "version": 1, "passed": not bad, "suite_sha256": inp["suite_sha256"], + "inputs": os.path.abspath(a.inputs), "engine": {"model": inp["engine"]["model"], "kernels": inp["engine"]["decision"]["plan"]["kernels"], + "n_threads": inp["engine"]["decision"]["plan"]["n_threads"]}, + "reference": {"ckpt": ckpt, "family": family, "dtype": "fp32", "n_threads": a.threads}, "tol_logit": a.tol_logit, + "n_items": len(rows) + sum(1 for b in bad if "input ids" in b), "n_identical_inputs": len(rows), + "argmax_same": sum(1 for x in rows if x["argmax_same"]), + "max_abs_dlogit": worst["max_abs_dlogit"] if worst else None, "max_abs_dlogit_at": worst["item"] if worst else None, + "mean_abs_dlogit": sum(x["max_abs_dlogit"] for x in rows) / max(1, len(rows)), + "max_abs_dp": max((x["max_abs_dp"] for x in rows), default=None), "failures": bad, "items": rows} + with open(a.output, "w", encoding="utf-8") as f: + json.dump(res, f, indent=1) + print("equal inputs: %d / %d items with identical input ids, argmax same %d / %d, max|dlogit| %.3e (%s), max|dp| %.3e" % ( + res["n_identical_inputs"], res["n_items"], res["argmax_same"], len(rows), res["max_abs_dlogit"] or 0, res["max_abs_dlogit_at"], + res["max_abs_dp"] or 0), flush=True) + for b in bad[:20]: + print(" FAIL " + b, flush=True) + print("%s -> %s" % ("PASSED" if not bad else "FAILED (inputs differ: fix the harness, not the engine)", a.output), flush=True) + return 0 if not bad else 1 + + +# +# bench: timing through the reference API +# + +def cmd_bench(a): + t_spawn, spawn_src = process_start() + inp = read_inputs(a.inputs, a.filter) + ckpt, family = resolve_ckpt(a.ckpt) + check = None + if a.check: + if not os.path.isfile(a.check): + die("no %s. Run: bench-decision-pytorch.py check --ckpt %s --inputs %s -o %s" % (a.check, a.ckpt, a.inputs, a.check)) + check = json.load(open(a.check)) + if not check.get("passed"): + die("%s did not pass: timings would compare different inputs" % a.check) + if check["suite_sha256"] != inp["suite_sha256"] or os.path.realpath(check["reference"]["ckpt"]) != os.path.realpath(ckpt): + die("%s was made for another suite or checkpoint" % a.check) + elif not a.unchecked: + die("--check CHECK.json is required (or --unchecked, which marks the result untrusted)") + os.makedirs(a.output, exist_ok=True) + + rq = inp["router_question"] + reqs = [] + for r in inp["requests"]: + text = json.dumps(r["body"], ensure_ascii=False) + reqs.append({"id": r["id"], "endpoint": r["endpoint"], "group": r["group"], "text": text, + "states": [(it["id"], it["state"]) for it in r["items"]] if r["endpoint"] == "router" else None, + "n_items": len(r["items"]), "n_tokens": sum(len(it["tokens"]) for it in r["items"])}) + + facts = machine_facts() + facts.update({"power_source": power_source(), "loadavg_start": load_avg(), "top_cpu_start": top_cpu()}) + mem_start = mem_now() + t_import0 = time.time() + torch, import_ms = load_torch(a.threads) + t_torch = time.time() + cpu0 = cpu_seconds() + agent = load_agent(torch, ckpt, a.dtype) + t_loaded = time.time() + load_ms, load_cpu = (t_loaded - t_torch) * 1000, cpu_seconds() - cpu0 + mem_load = mem_now() + print("pytorch %s %s, %d threads (interop %d), router %s, %d requests, warmup %d, repeat %d, import %.0f ms, load %.0f ms" % ( + family, a.dtype, torch.get_num_threads(), torch.get_num_interop_threads(), a.router_mode, len(reqs), a.warmup, a.repeat, + import_ms, load_ms), flush=True) + + def run(r): + c0 = cpu_seconds() + t0 = time.perf_counter() + with torch.inference_mode(): + body = json.loads(r["text"]) + if r["endpoint"] == "systemone": + res = agent.system_one(body["state"], body["questions"]) + elif a.router_mode == "batch": + out = agent.predict_batch([s for _, s in r["states"]], {"router": rq}) + res = {"object": "router.scores", "scores": [{"id": cid, "p_success": o["answers"]["router"]["noul"]} + for (cid, _), o in zip(r["states"], out)]} + else: + scores = [] + for cid, state in r["states"]: + o = agent.system_one(state, {cid: rq}) + scores.append({"id": cid, "p_success": o["answers"][cid]["noul"]}) + res = {"object": "router.scores", "scores": scores} + text = json.dumps(res) + t1 = time.perf_counter() + c1 = cpu_seconds() + if r["endpoint"] == "router" and len(res["scores"]) != len(r["states"]): + die("%s: %d scores for %d candidates" % (r["id"], len(res["scores"]), len(r["states"]))) + ans = res.get("answers", res.get("scores")) + return (t1 - t0) * 1000, c1 - c0, hashlib.sha256(json.dumps(ans, sort_keys=True).encode()).hexdigest() + + series = {r["id"]: {"total_ms": [], "cpu_s": [], "hashes": set()} for r in reqs} + first = None + for w in range(a.warmup): + for r in reqs: + ms, _, h = run(r) + if first is None: + first = (r["id"], ms, time.time()) + series[r["id"]]["hashes"].add(h) + mem_warm = mem_now() + for k in range(a.repeat): + for r in reqs: + ms, cs, h = run(r) + if first is None: + first = (r["id"], ms, time.time()) + s = series[r["id"]] + s["total_ms"].append(ms) + s["cpu_s"].append(cs) + s["hashes"].add(h) + print("pytorch: repeat %d/%d" % (k + 1, a.repeat), flush=True) + mem_end = mem_now() + after_idle = None + if a.idle_ms > 0: + print("pytorch: idle %d ms" % a.idle_ms, flush=True) + time.sleep(a.idle_ms / 1000.0) + runs = [] + for r in reqs: + ms, cs, h = run(r) + series[r["id"]]["hashes"].add(h) + runs.append({"id": r["id"], "total_ms": ms, "cpu_s": cs, "p50_ms": pct(series[r["id"]]["total_ms"], 50)}) + after_idle = {"idle_ms": a.idle_ms, "runs": runs} + amp_end = bool(agent.amp_enabled) + dtype_eff = str(agent.dtype).replace("torch.", "") if amp_end else "float32" + if a.dtype == "bf16" and not amp_end: + print("warning: bf16 autocast fell back to fp32 on this CPU/torch build; the bf16 rows are fp32", flush=True) + + jreqs, groups, order = [], {}, [] + for r in reqs: + s = series[r["id"]] + if r["group"] not in groups: + order.append(r["group"]) + groups[r["group"]] = {"total_ms": [], "cpu_s": []} + groups[r["group"]]["total_ms"] += s["total_ms"] + groups[r["group"]]["cpu_s"] += s["cpu_s"] + jreqs.append({"id": r["id"], "endpoint": r["endpoint"], "group": r["group"], "n_items": r["n_items"], "n_tokens": r["n_tokens"], + "deterministic": len(s["hashes"]) == 1, "n_hashes": len(s["hashes"]), "total_ms": stats(s["total_ms"]), + "cpu_s": stats(s["cpu_s"]), "runs_total_ms": s["total_ms"], "runs_cpu_s": s["cpu_s"]}) + facts.update({"loadavg_end": load_avg(), "power_source_end": power_source(), "top_cpu_end": top_cpu()}) + tag = "pytorch-%s-%s%s" % (family, a.dtype, "-batch" if a.router_mode == "batch" else "") + res = { + "bench": BENCH_NAME, "version": 1, "model": ckpt, "family": family, "suite": inp["suite"], "suite_sha256": inp["suite_sha256"], + "inputs": os.path.abspath(a.inputs), "n_threads": a.threads, "interop_threads": torch.get_num_interop_threads(), + "dtype": a.dtype, "dtype_effective": dtype_eff, "autocast_end": amp_end, "router_mode": a.router_mode, + "repeat": a.repeat, "warmup": a.warmup, "machine": facts, "runtime": torch_facts(torch, agent), + "load": {"import_torch_ms": import_ms, "ms": load_ms, "cpu_s": load_cpu, "first_request_ms": first[1] if first else None, + "first_request_id": first[0] if first else None}, + "ready": {"process_start": spawn_src, "spawn_to_script_ms": (T_SCRIPT - t_spawn) * 1000, + "spawn_to_torch_ms": (t_torch - t_spawn) * 1000, "spawn_to_loaded_ms": (t_loaded - t_spawn) * 1000, + "spawn_to_first_answer_ms": (first[2] - t_spawn) * 1000 if first else None, + "note": "input checks before the import: %.0f ms" % ((t_import0 - T_SCRIPT) * 1000)}, + "memory": {"start": mem_start, "after_load": mem_load, "after_warmup": mem_warm, "end": mem_end}, + "deterministic": all(len(s["hashes"]) == 1 for s in series.values()), + "equal_input": ({"check": os.path.abspath(a.check), "passed": True, "engine": check["engine"], + "max_abs_dlogit": check["max_abs_dlogit"], "argmax_same": check["argmax_same"], "n_items": check["n_items"]} + if check else {"passed": False, "note": "--unchecked"}), + "groups": [{"group": g, "total_ms": stats(groups[g]["total_ms"]), "cpu_s": stats(groups[g]["cpu_s"])} for g in order], + "requests": jreqs, "after_idle": after_idle, + } + stamp = time.strftime("%Y%m%d-%H%M", time.gmtime()) + host = (platform.node().split(".")[0] or "host") + path = os.path.join(a.output, "%s__%s__%s__%s__t%d.json" % (host, a.label, stamp, tag, a.threads)) + with open(path, "w", encoding="utf-8") as f: + json.dump(res, f, indent=1) + + print("\n| %-16s | %5s | %6s | %9s | %9s | %9s | %7s | %3s |" % ("request", "items", "tokens", "p50 ms", "p95 ms", "p99 ms", "cpu_s", "det"), flush=True) + for r in jreqs: + print("| %-16s | %5d | %6d | %9.1f | %9.1f | %9.1f | %7.3f | %3s |" % ( + r["id"], r["n_items"], r["n_tokens"], r["total_ms"]["p50"], r["total_ms"]["p95"], r["total_ms"]["p99"], r["cpu_s"]["mean"], + "yes" if r["deterministic"] else "NO"), flush=True) + mib = lambda b: b / 2**20 if b >= 0 else -1 + print("\nmemory MiB: rss after load %.0f, rss peak %.0f, footprint after load %.0f, footprint peak %.0f" % ( + mib(mem_load["rss"]), mib(mem_end["rss_peak"]), mib(mem_load["footprint"]), mib(mem_end["footprint_peak"])), flush=True) + rd = res["ready"] + print("ready (%s): torch %.0f ms, loaded %.0f ms, first answer %.0f ms" % ( + spawn_src, rd["spawn_to_torch_ms"], rd["spawn_to_loaded_ms"], rd["spawn_to_first_answer_ms"] or -1), flush=True) + if after_idle: + f0 = after_idle["runs"][0] + print("after %d ms idle: %s %.1f ms (its p50 %.1f ms)" % (a.idle_ms, f0["id"], f0["total_ms"], f0["p50_ms"]), flush=True) + print("wrote " + path, flush=True) + return 0 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("inputs", help="render the suite through llama-server --decision --decision-debug") + p.add_argument("--server", required=True) + p.add_argument("--model", required=True) + p.add_argument("-t", "--threads", type=int, default=2) + p.add_argument("--kernels") + p.add_argument("--spec") + p.add_argument("--suite", default=DEFAULT_SUITE) + p.add_argument("--filter") + p.add_argument("-o", "--output", required=True) + p = sub.add_parser("check", help="reference fp32 against the engine logits of an inputs file") + p.add_argument("--ckpt", required=True) + p.add_argument("--inputs", required=True) + p.add_argument("-t", "--threads", type=int, default=2) + p.add_argument("--tol-logit", type=float, default=1e-3) + p.add_argument("-o", "--output", required=True) + p = sub.add_parser("bench", help="time the reference on the suite") + p.add_argument("--ckpt", required=True) + p.add_argument("--inputs", required=True) + p.add_argument("--check") + p.add_argument("--unchecked", action="store_true") + p.add_argument("-t", "--threads", type=int, default=4) + p.add_argument("--dtype", choices=("fp32", "bf16"), default="fp32") + p.add_argument("--repeat", type=int, default=10) + p.add_argument("--warmup", type=int, default=1) + p.add_argument("--idle-ms", type=int, default=0) + p.add_argument("--router-mode", choices=("sequential", "batch"), default="sequential") + p.add_argument("--filter") + p.add_argument("--label", default="pytorch") + p.add_argument("-o", "--output", required=True, help="output directory") + a = ap.parse_args() + if getattr(a, "threads", 1) < 1 or getattr(a, "repeat", 1) < 1 or getattr(a, "warmup", 0) < 0: + die("threads and repeat must be >= 1, warmup >= 0") + if a.cmd == "bench" and "__" in a.label: + die("--label must not contain '__' (the report splits file names on it)") + return {"inputs": cmd_inputs, "check": cmd_check, "bench": cmd_bench}[a.cmd](a) or 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/bench-decision-report.py b/scripts/bench-decision-report.py new file mode 100755 index 000000000000..78dd82f64f95 --- /dev/null +++ b/scripts/bench-decision-report.py @@ -0,0 +1,622 @@ +#!/usr/bin/env python3 +"""Turn scripts/bench-decision.sh results into markdown tables (KPIs K1, K4-K7, K9). + +Usage: + python3 scripts/bench-decision-report.py build/bench-decision [more dirs or files ...] [--stamp 20260930-0215] + [--family laya-f16=laya-multilingual ...] + +Reads __