From c1b8b1bc972f3b613f3d766cf0fd4ada8661a70a Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 02:55:52 +1100 Subject: [PATCH 01/16] 18 Oct field report: README status note and changelog --- CHANGELOG.md | 23 +++++++++++++++++++++++ README.md | 28 ++++++++++++++++++---------- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f7a10..80b7879 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## Unreleased — 2026-10-18 field report and governor v4.3 + +Imported selectively from three maintainer hand-off archives (Claude and Codex sessions, 15–18 Oct). Measured results, researched-only material and rejected proposals are kept apart and labelled. + +**Findings** ([FIELD-REPORT-20261018](docs/FIELD-REPORT-20261018.md)) +- Dedicated free VRAM is not a real fit. At a 57,344 window llama-server spilled 2.90 GiB into WDDM shared memory and decode fell to 20–22 tok/s. At 36,864 it ran at 26.7–28.3 tok/s with 1.23 GiB shared. On a busy desktop, 36–40K is now the stated safe window; larger windows are being re-qualified, not withdrawn. +- Open regression: `llama-bench tg32` is 16.0 → 13.0 tok/s on the same command (12 → 17 Oct), and warm decode is 43–48 → 28 tok/s. The cause is not found; the checks come first in [ROADMAP](docs/ROADMAP.md) (E0). +- q8_0 main KV is rejected by measurement: at 25K depth, prompt reading −53% and generation −57%, with 0.27 GiB saved. Raw logs are in `data/raw/ctxlab-20261017/`. + +**Governor** +- v3 → **v4.3** ([governor/README.md](governor/README.md)): null-safe sensing, pressure hysteresis, never unloads mid-request, KV slot save/restore (`slotlib.ps1`), power-plan hysteresis, footprint calibration, and Ollama's bundled `llama-server.exe` is no longer counted as the model. Fixes the published v3 loop crash (`needLog` uninitialised) when the governor starts with no model loaded. +- `profiles.json`: MAX/BALANCED `free_margin_gib` 1.35 → 2.5 and `auto.others_vram_max_gib` 2.5. ThinkingCap is the default variant, with `--spec-draft-p-min 0.5` and `--slot-save-path`. +- Tests: `test_governor.ps1` 111/0, `test_ctx.ps1` 7/7 (its function extraction now uses the PowerShell AST), and pytest `govpolicy`/`slotpolicy` 53/0. + +**Agents and docs** +- [agents/codex-lean/](agents/codex-lean/README.md): an opt-in `CODEX_HOME` that cuts Codex's start-up prompt from 12,235 to 3,010 tokens (measured). Not yet run on the 100-task eval. +- [CODEX-COMPAT.md](docs/CODEX-COMPAT.md): 26 request types against llama-server. Named and `required` `tool_choice` are not enforced; `text.format` is ignored on `/v1/responses` (top-level `response_format` works). +- [TRIED-AND-REJECTED.md](docs/TRIED-AND-REJECTED.md) and [ROADMAP.md](docs/ROADMAP.md) (E0–E5, each with pass/fail and rollback). +- [docs/research/](docs/research/README.md): a source-level study of the engine (DFlash per-round timing, coopmat/#30503, context budget) and an UNTESTED instrumentation diff and reasoning resolver. **Researched, not run on the card.** +- New data: `kv-cache-depth-20261017.csv`, `footprint-variants-20261017.csv`, `context-spill-20261018.csv`. Tuning-log rows 24–27 added. +- README: a status note, a "What's new" line, context guidance corrected to 36–40K on a busy desktop, and the governor margin text updated. +- Not imported: the outside "optimisation pack" (defective patch, unsafe build script; see TRIED-AND-REJECTED), private machine logs and live configs, and duplicate copies of the research pack. + ## Unreleased — 2026-10-17 field report - README front page refresh: hero banner, a four-step "recipe" for Qwen3.8-27B at 50+ tok/s on a B60 (copy-paste server line), the per-request decode headline (mean 53.3, 47-58 tok/s, from the existing `tune.txt` run) with its context caveats stated up front, and a project-scale card. diff --git a/README.md b/README.md index ac17c9c..dce76e1 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,17 @@ > **The fine print, up front.** 53 tok/s is per-request server decode with short prompts and a 65,536-token KV window allocated ([tune.txt](data/raw/tune.txt)). With 30-37K tokens of real conversation in the window, agent turns generate about 42 tok/s ([bench-history.csv](data/raw/bench-history.csv)). On 17 October a 53K window on a contended desktop fell to 22 tok/s, and 50-60K without loss is not yet qualified ([field report](docs/OPERATING-PROFILES-20261017.md)). Single runs on one workstation. -**17 October field report:** [B60 throughput recovery, desktop-safe AUTO profiles and context trade-offs](docs/OPERATING-PROFILES-20261017.md). Dated local observations; not a new benchmark headline or an installable runtime update. +> [!IMPORTANT] +> **Status, 18 October 2026.** The headline figures were measured on 10–16 October, and each links to its raw log. Since then, two findings have changed how we size the server: +> +> - **Large windows can spill.** Windows can push part of a process into *shared* system memory even while the card still reports free VRAM. At a 57K window, 2.9 GiB spilled and decode fell to 20–22 tok/s. Until the per-process budget is mapped, **36–40K is the safe window on a busy desktop**. The governor's margin is now 2.5 GiB. +> - **There is an open regression.** The same box is currently slower: 28 tok/s warm at a 36K window, against 43–48 on 15–16 October. `llama-bench` without the drafter is 19% lower on the same command. The cause hasn't been found; the checks are in the [roadmap](docs/ROADMAP.md). +> +> Details are in the [18 October field report](docs/FIELD-REPORT-20261018.md); the earlier [17 October report](docs/OPERATING-PROFILES-20261017.md) covers GPU contention. + +**What's new:** [governor v4.3](governor/README.md) with 170+ tests · [Codex/llama-server compatibility matrix](docs/CODEX-COMPAT.md) · [lean Codex home](agents/codex-lean/README.md) (start-up prompt 12,235 → 3,010 tokens) · [tried and rejected](docs/TRIED-AND-REJECTED.md) · [roadmap](docs/ROADMAP.md) · [engine research](docs/research/README.md) (researched, not run on the card) + +**Jump to:** [Recipe](#the-recipe-qwen38-27b-at-50-toks-on-an-arc-b60) · [Measured numbers](#measured-numbers) · [Quick start](#quick-start) · [Which card?](#which-intel-card-and-which-model-fits) · [Other B60 results](#how-it-compares-with-other-b60-results) · [Versions](#versions-used) · [Add your card](#add-your-card) · [FAQ](#faq) ## The recipe: Qwen3.8-27B at 50+ tok/s on an Arc B60 @@ -41,7 +51,7 @@ llama-server -m Qwen3.8-27B-UD-Q4_K_M.gguf -ngl 99 -fa on -c 65536 -ctk f16 -ctv ``` - Build the engine first with `engine\build.ps1` ([Quick start](#quick-start)): the prefill speed-up needs the vendored Intel FA patches; the drafter alone works on stock llama.cpp b11524. -- If your desktop uses more than about 1 GiB of VRAM, drop `-c` to 57344 or 61440. The [governor](governor/) does this sizing for you at every load. +- If your desktop uses more than about 1 GiB of VRAM, use a smaller `-c`. On a busy desktop 36864–40960 is the safe range until you have checked that llama-server isn't spilling into shared memory ([how to check](docs/FIELD-REPORT-20261018.md#1-dedicated-free-vram-is-not-a-real-fit)). The [governor](governor/) does this sizing for you at every load. - Free the card before you benchmark: `ollama ps`, then `ollama stop ` for anything listed, and close other GPU-heavy apps. - Optional: `--spec-draft-p-min 0.5` added a further 4.6% in eval-suite throughput (42.0 -> 43.94 tok/s, [tuning log](docs/TUNING-LOG.md) row 17). @@ -57,7 +67,7 @@ llama-server -m Qwen3.8-27B-UD-Q4_K_M.gguf -ngl 99 -fa on -c 65536 -ctk f16 -ctv ## What you get -- **A local coding model on a roughly A$1,000-1,240 Intel card.** Qwen3.8-27B (the ThinkingCap build is the default) on an Arc Pro B60 24GB: 53 tok/s mean per-request decode (47-58), 42-44 tok/s eval-suite throughput, 57-64K context. Prices are dated in [the card table](#which-intel-card-and-which-model-fits). +- **A local coding model on a roughly A$1,000-1,240 Intel card.** Qwen3.8-27B (the ThinkingCap build is the default) on an Arc Pro B60 24GB: 53 tok/s mean per-request decode (47-58), 42-44 tok/s eval-suite throughput, 64K context on a quiet desktop (36-40K while the PC is in use; see the status note above). Prices are dated in [the card table](#which-intel-card-and-which-model-fits). - **Local video generation.** LTX-2.5 text-to-video and image-to-video with sound through ComfyUI on XPU, a queue that hands the GPU from the LLM to ComfyUI and back, and an ffmpeg "finish at 1080p/2K/4K" step. See [docs/VIDEO-GEN.md](docs/VIDEO-GEN.md). - **A phone Studio.** A web app over Tailscale (never public): live GPU/VRAM telemetry, render progress and history, a Qwen code tab, installable as a PWA. PIN-gated approvals, with an optional 90-day remembered device. See [docs/GATEWAY.md](docs/GATEWAY.md) and [docs/STUDIO-P2-CONTRACTS.md](docs/STUDIO-P2-CONTRACTS.md). - **A Claude Code partner.** `ask_local` (stand-alone `qwen_mcp.py`) hands first-pass code and review tasks to the local model; Claude stays the gate. See [docs/LOCAL-LLM.md](docs/LOCAL-LLM.md). @@ -105,12 +115,10 @@ Linux notes: [engine/build-linux.sh](engine/build-linux.sh) builds the same engi ## Guides -[Setup](docs/SETUP.md) · [Tuning log](docs/TUNING-LOG.md) · [Video generation](docs/VIDEO-GEN.md) · [Upscale / finish](docs/UPSCALE.md) · [Studio contracts](docs/STUDIO-P2-CONTRACTS.md) · [Phone tool gateway](docs/GATEWAY.md) · [Local LLM delegation (`ask_local`)](docs/LOCAL-LLM.md) · [Token efficiency](docs/TOKEN-EFFICIENCY.md) · [Tool calling](docs/TOOL-CALLING.md) · [Reliability](docs/RELIABILITY.md) · [Chat UI, voice and tools](docs/PLATFORM.md) · [Intel FA](docs/INTEL-FA.md) · [FAQ](docs/FAQ.md) · [Interactive benchmarks](https://edagher92-coder.github.io/arc-llm-lab/) +[Setup](docs/SETUP.md) · [Tuning log](docs/TUNING-LOG.md) · [Video generation](docs/VIDEO-GEN.md) · [Upscale / finish](docs/UPSCALE.md) · [Studio contracts](docs/STUDIO-P2-CONTRACTS.md) · [Phone tool gateway](docs/GATEWAY.md) · [Local LLM delegation (`ask_local`)](docs/LOCAL-LLM.md) · [Token efficiency](docs/TOKEN-EFFICIENCY.md) · [Tool calling](docs/TOOL-CALLING.md) · [Reliability](docs/RELIABILITY.md) · [Chat UI, voice and tools](docs/PLATFORM.md) · [Intel FA](docs/INTEL-FA.md) · [Codex compatibility](docs/CODEX-COMPAT.md) · [Field report, 18 Oct](docs/FIELD-REPORT-20261018.md) · [Tried and rejected](docs/TRIED-AND-REJECTED.md) · [Roadmap](docs/ROADMAP.md) · [Engine research](docs/research/README.md) · [FAQ](docs/FAQ.md) · [Interactive benchmarks](https://edagher92-coder.github.io/arc-llm-lab/) If this is useful, a star helps other Arc owners find it. Questions or something wrong? [Open an issue](https://github.com/edagher92-coder/arc-llm-lab/issues/new/choose). -**Jump to:** [Results](#results-on-one-arc-pro-b60-24gb) · [Which card?](#which-intel-card-and-which-model-fits) · [Other B60 results](#how-it-compares-with-other-b60-results) · [Full Windows setup](#quick-start-windows-11-in-full) · [Versions](#versions-used) · [FAQ](#faq) · [Add your card](#add-your-card) - ## Results on one Arc Pro B60 24GB | | Stock llama.cpp Vulkan | This repo | Raw data | @@ -118,7 +126,7 @@ If this is useful, a star helps other Arc owners find it. Questions or something | Generation speed | 16 tok/s ‡ (no drafter) | **42.3 tok/s** ‡ (DFlash2 draft model, n=7; eval-suite throughput, wall-clock) | [compare-f16.txt](data/raw/compare-f16.txt), [tune.txt](data/raw/tune.txt) | | Reading new input at 32K context | 118 tok/s | **420 tok/s** | [compare-f16.txt](data/raw/compare-f16.txt) | | 3 agent turns at 30–37K context | 201 s † | **55–57 s** § | [server-test.txt](data/raw/server-test.txt), [bench-history.csv](data/raw/bench-history.csv) | -| Context window | n/a | up to **64K** (57–61K typical while the PC is in use) ¶ | [vram-budget-64k.csv](data/vram-budget-64k.csv) | +| Context window | n/a | up to **64K** on a quiet desktop (36–40K safe while the PC is in use) ¶ | [vram-budget-64k.csv](data/vram-budget-64k.csv) | | 100-task hidden-checker agent eval, 32K window | n/a | **97/100** Claude Code (1.54 completed tasks/min) · **95/100** Codex ¶¶ | [RELIABILITY.md](docs/RELIABILITY.md) | ¶¶ Sustained 10-step sessions at 48K/64K: Codex **10/10** and **10/10**, Claude Code **10/10** and **9/10**. Single runs; 95% CI 91.5–99% for 97/100. Detail in [Reliability](#reliability-not-just-speed). @@ -130,7 +138,7 @@ All speed figures are single runs (-r 1) unless noted. ‡ 42.3 tok/s is eval-suite throughput (wall-clock, prompt processing included): generated tokens divided by total wall-clock across the 8 eval requests (7 coding tasks and 1 web page), in the `n7 ub256 dkv-q8` row of [tune.txt](data/raw/tune.txt). The per-request server decode speeds in that run were 47–58 tok/s, mean 53.3. We quote 42.3 as the conservative headline. 16 tok/s is `llama-bench` `tg32` on an empty context with no draft model (16.05 in [compare-f16.txt](data/raw/compare-f16.txt)), a different measurement, so the two are not like-for-like.
† Stock engine with the drafter, observed before logging was in place; the raw log was not retained. Re-run planned. Treat as an observation, not a reproducible measurement ([what we have no raw log for](data/raw/README.md#not-retained)).
§ 54.9 s on the first Intel FA build; 56.7 s on the final tuned configuration at 57,344 context; an intermediate run at 61,440 context took 52.2 s. All three are in the logs ([agent-turns.csv](data/agent-turns.csv)).
-¶ 64K (65,536) is the configured maximum and the VRAM budget in the CSV. Context is sized from the VRAM free at each load; the logged runs loaded 61,440 and 57,344 tokens. +¶ 64K (65,536) is the configured maximum and the VRAM budget in the CSV. Context is sized from the VRAM free at each load; the logged runs loaded 61,440 and 57,344 tokens. Shared-memory use wasn't recorded for those runs. On 18 October a 57,344 window spilled 2.9 GiB into shared memory on a busy desktop, so larger windows are being re-qualified ([field report](docs/FIELD-REPORT-20261018.md)). Test PC: Ryzen 7 3700X, B550, 32 GB DDR4, Windows 11, Intel Arc Pro B60 24GB. B60 prices in Australia (a snapshot, not a recommendation): A$1,240 for an ASRock B60 Creator ([gpuprix](https://gpuprix.com/australia/gpus/arc-pro-b60), updated 2026-10-07) and A$999 including GST for an ASRock Arc Pro B60 Passive 24GB OEM card (PCCaseGear, 2026-10-10; a passive card has no fan of its own and needs strong airflow). @@ -213,7 +221,7 @@ Other people publish Qwen3.8-27B numbers for the same card, so we put them side 1. **Intel's flash-attention prefill kernel makes long-context agents usable, but only with an f16 KV cache.** It reads prompts 3.6× faster at 32K depth (118 to 420 tok/s) and gains nothing with a q4 KV cache (101 versus 101). The kernel comes from llama.cpp [PR #29357](https://github.com/ggml-org/llama.cpp/pull/29357), which its author **closed without merging** on 2026-09-25 and whose branch was later force-pushed. This repo therefore vendors the two commits in [engine/patches/](engine/patches/) with checksums and attribution, and the build applies them to b11524. → [docs/INTEL-FA.md](docs/INTEL-FA.md) 2. **Speculative decoding is the biggest single win for generation.** A small DFlash2 draft model takes a 27B dense model from 16 to 42 tok/s with identical output quality on our seven coding tasks. → [docs/TUNING-LOG.md](docs/TUNING-LOG.md) -3. **Keep a margin of free VRAM (the governor keeps 1.35 to 3 GiB, depending on profile) and turn llama.cpp's auto-fit off.** The one run that fell short (draft length 15, 0.96 GiB free) dropped from 42 to 27 tok/s, but two other runs at 1.04 and 0.71 GiB free did not, so the exact threshold is not established ([details](docs/TUNING-LOG.md)). On Windows auto-fit quietly spills into shared memory. +3. **Keep a margin of free VRAM (the governor keeps 2.5 GiB in MAX and BALANCED, 3 GiB in LEAN), turn llama.cpp's auto-fit off, and watch shared memory.** Windows gives each process a dedicated-memory budget below the card's total, and allocations beyond it go to system memory over PCIe. Free VRAM can look fine while the model slows down: a 57K window spilled 2.9 GiB and fell to 20–22 tok/s. Read the process's `Shared Usage` counter, not just free VRAM ([field report](docs/FIELD-REPORT-20261018.md#1-dedicated-free-vram-is-not-a-real-fit)). 4. **`-ub 256` plus a q8 draft KV cache frees 0.55 GiB at no speed cost.** That is the difference between 57K and 64K of context. 5. **Make context overflow an error, not a silent loss.** We pass `--no-context-shift` explicitly (it is also the default in b11524), so a conversation that outgrows the server's context gets an HTTP 400 instead of quietly dropping old tokens, and the agent wrappers size their window to server context minus 8K so the client compacts first. Compaction is done by Claude Code or Codex, and a summary can still lose detail; the sustained-session test in [docs/RELIABILITY.md](docs/RELIABILITY.md) checks for that. @@ -349,6 +357,6 @@ Got an A770, B580, B570, B50, B70, B60 or another Intel GPU? Run [bench/arc-benc - Qwen models and [Unsloth](https://huggingface.co/unsloth) GGUFs. - [whisper.cpp](https://github.com/ggml-org/whisper.cpp), [Kokoro](https://github.com/thewh1teagle/kokoro-onnx) and [Open WebUI](https://docs.openwebui.com/). -Built and measured by **Elie Dagher**, with Claude as engineering pair. MIT licensed ([LICENSE](LICENSE)). To cite this repository, use [CITATION.cff](CITATION.cff) (GitHub's "Cite this repository" button reads it). +Built and measured by **Elie Dagher**, with Claude and Codex as engineering pairs. The source-level engine study in [docs/research/](docs/research/README.md) was prepared with Gemini. MIT licensed ([LICENSE](LICENSE)). To cite this repository, use [CITATION.cff](CITATION.cff) (GitHub's "Cite this repository" button reads it). This repository is about running local LLMs on Intel Arc GPUs (Arc Pro B60, B580, B570, B50, B70 and A770, Battlemage and Xe2) with llama.cpp on Vulkan: 24GB VRAM setups, Qwen 27B coding agents, benchmarks against Ollama and LM Studio, and flash-attention and speculative-decoding results. From 57dd0806250399755be7e7db40199d550052d2c8 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 02:56:43 +1100 Subject: [PATCH 02/16] Governor v4.3 with tests; margin 2.5 GiB --- governor/README.md | 39 ++ governor/governor.ps1 | 784 ++++++++++++++++++++++++++++++------ governor/govpolicy.py | 298 ++++++++++++++ governor/launch.ps1 | 82 +++- governor/profiles.json | 430 ++++++++++++-------- governor/qwen.ps1 | 32 +- governor/slotlib.ps1 | 485 ++++++++++++++++++++++ governor/slotpolicy.py | 433 ++++++++++++++++++++ governor/test_ctx.ps1 | 21 + governor/test_governor.ps1 | 257 ++++++++++++ governor/test_govpolicy.py | 292 ++++++++++++++ governor/test_slotpolicy.py | 426 ++++++++++++++++++++ 12 files changed, 3257 insertions(+), 322 deletions(-) create mode 100644 governor/README.md create mode 100644 governor/govpolicy.py create mode 100644 governor/slotlib.ps1 create mode 100644 governor/slotpolicy.py create mode 100644 governor/test_ctx.ps1 create mode 100644 governor/test_governor.ps1 create mode 100644 governor/test_govpolicy.py create mode 100644 governor/test_slotpolicy.py diff --git a/governor/README.md b/governor/README.md new file mode 100644 index 0000000..1f75be9 --- /dev/null +++ b/governor/README.md @@ -0,0 +1,39 @@ +# Governor (v4.3) + +The governor keeps the local Qwen server sized to what the PC is doing. It picks a profile (MAX when you're away, BALANCED while you work, LEAN under load) and sizes the context window to the VRAM actually free at each load. It never unloads while a request is in flight, and it saves the KV slot before its own reloads so agents keep their cached prefix. It runs hidden in the user session as the scheduled task "Local Qwen Governor" under Windows PowerShell 5.1. + +## What changed since v3 (15–17 October 2026) + +| Version | Change | Why | +|---|---|---| +| v4 | Null-safe sensing: an invalid counter sample keeps the last good value and is marked degraded, never acted on. Pressure must persist 60 s; refits happen at most every 15 min; nothing unloads with a request in flight. KV slot save/restore. `status.json` is written on every sample | v3's loop crashed every 16 s whenever it started with no model loaded, and single bad samples caused reload churn | +| v4.1 | Post-launch BASELINE, refit only when *other* apps grew ≥ 0.5 GiB, footprint calibration (`calib.json`), repeat-refit guard | A tight fit refitted itself every 15 min for ever | +| v4.2 | Power-plan hysteresis (`GovPowerDecide`) | 104 power-plan flips in 400 log lines | +| v4.3 | `ProcIds` and `launch.ps1` count only llama-server processes under `C:\AI\llama.cpp\` | Ollama ships its own `llama-server.exe`; an idle Ollama model was being counted as ours | +| 18 Oct defaults | MAX/BALANCED `free_margin_gib` 1.35 → **2.5**; `auto.others_vram_max_gib` 2.5 | A fit on dedicated free VRAM spilled 2.9 GiB into shared memory at a 57K window ([field report](../docs/FIELD-REPORT-20261018.md)) | + +`slotlib.ps1` holds slot save/restore; `govpolicy.py` and `slotpolicy.py` mirror the pure decision functions so they can be tested with pytest. + +## Tests + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File governor\test_governor.ps1 # 111 passed, 0 failed +powershell -NoProfile -ExecutionPolicy Bypass -File governor\test_ctx.ps1 # 7/7 +python -m pytest governor -q # 53 passed +``` + +These counts come from PowerShell 7.4 and Python 3.12 on Linux, with the Windows-only reads stubbed. The tests write to a temp folder, never to the production log. + +## Install or upgrade + +1. Back up your current `C:\AI\governor\` folder. +2. Copy this folder over it. `profiles.json` uses the repo's model paths (`C:/AI/models/...`), so check them against your disk first. +3. Run the tests above. +4. Restart only the governor task; the model keeps running. `--slot-save-path` takes effect at the next server start. + +Then check: + +- `qwen status` shows a `Governor:` line and no "N s old" warning. +- `qwen log` shows `governor start ... v4` and no `loop error` lines. + +**What this folder is.** This is the reference implementation with tests. The maintainer's own machine carries some extra local edits that are not published: a media-playback veto and CPU/RAM gates for MAX. So `qwen status` on that machine can show fields this copy doesn't write. diff --git a/governor/governor.ps1 b/governor/governor.ps1 index cede6ec..b8b064c 100644 --- a/governor/governor.ps1 +++ b/governor/governor.ps1 @@ -1,5 +1,21 @@ -# Qwen governor: adapts the local model to how the PC is being used. Runs hidden in the user session. -# Never interrupts a request: reloads/unloads only happen when the model has been quiet. +# Qwen governor v4 (2026-10-15): adapts the local model to how the PC is being used. Runs hidden in the user session +# as the scheduled task "Local Qwen Governor". Windows PowerShell 5.1. +# +# Rules of this file +# - Never interrupts a request: every unload re-checks /slots and /metrics for a request in flight first. +# - One failed read (PDH counter, JSON file, HTTP to llama-swap/llama-server, process query) never kills the loop +# and never becomes a number we act on: readings are validated, invalid ones keep the last good value and are +# marked degraded. status.json is written on EVERY sample, degraded or not. +# - Pressure must persist (pressure_persist_sec, 60 s) before any unload/re-fit; re-fits and upgrades happen at +# most once per refit_min_interval_min (15 min). The KV slot is saved before a governor-initiated unload and +# restored after the relaunch (slotlib.ps1), so agent clients keep their cached prefix. +# - The power plan (GovPowerDecide, v4.2) has hysteresis: upgrades at once, downgrades one step per power.dwell_min +# (10) and only after the lower demand persisted for the whole dwell; BALANCED floor while an agent client is active; +# SAVER only when the PC is idle >= 15 min AND the model quiet >= 15 min. Every transition is logged with its reason. +# - The pure decision functions (Gov*) mirror govpolicy.py, which has the pytest suite (test_govpolicy.py). +# Change a rule in both places (GovPowerDecide is PowerShell-only so far). `. governor.ps1 -FunctionsOnly` loads +# them for test_governor.ps1. +param([switch]$FunctionsOnly) $ErrorActionPreference = 'Continue' $dir = 'C:\AI\governor' $swap = 'http://127.0.0.1:8090' @@ -8,8 +24,16 @@ $ids = @('qwen3.8-27b', 'qwen3.8-27b-turbo', 'qwen3.8-27b-long', 'qwen3.8-27b-bi $ports = @{ 'qwen3.8-27b' = 10001; 'qwen3.8-27b-turbo' = 10003; 'qwen3.8-27b-long' = 10004; 'qwen3.8-27b-big' = 10005 } $script:curId = $model; $script:curPort = 10001 $task = 'Local Qwen (llama-swap)' -$vramTotal = 25641877504.0 # Arc Pro B60 heap 0 (vulkaninfo) +$script:vramTotalGib = 23.88 # Arc Pro B60 heap 0 (vulkaninfo); overridden by profiles.json vram.total_gib +# constants mirrored in govpolicy.py +$GOV_LOADED_MIN_ADAPTER_GIB = 8.0 +$GOV_LOADED_MIN_LLAMA_GIB = 4.0 +$GOV_OTHERS_JUMP_GIB = 4.0 +$GOV_OTHERS_CONFIRM_SAMPLES = 4 +$GOV_OTHERS_PLAUSIBLE_MAX_GIB = 8.0 + +try { Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public static class IdleTime { @@ -18,177 +42,677 @@ public static class IdleTime { public static double Seconds() { var l = new LASTINPUTINFO(); l.cbSize = (uint)Marshal.SizeOf(l); if (!GetLastInputInfo(ref l)) return 0; return ((uint)Environment.TickCount - l.dwTime) / 1000.0; } } -'@ +'@ -ErrorAction Stop +} catch {} +# ============================================================ logging ============================================================ function Log($m) { $f = "$dir\governor.log" try { if ((Test-Path $f) -and (Get-Item $f).Length -gt 5MB) { Move-Item $f "$f.1" -Force } } catch {} - "$(Get-Date -f s) $m" | Add-Content $f + try { "$(Get-Date -f s) $m" | Add-Content $f -ErrorAction Stop } catch { try { Start-Sleep -Milliseconds 200; "$(Get-Date -f s) $m" | Add-Content $f -ErrorAction Stop } catch {} } +} +$script:onceKeys = @{} +function LogOnce($key, $m) { if (-not $script:onceKeys.ContainsKey($key)) { $script:onceKeys[$key] = (Get-Date); Log $m } } +# log a repeating condition once, then at most every $everyMin minutes +function LogEvery($key, $everyMin, $m) { + $t = $script:onceKeys[$key] + if (($null -eq $t) -or (((Get-Date) - $t).TotalMinutes -ge $everyMin)) { $script:onceKeys[$key] = (Get-Date); Log $m } +} +function ClearOnce($key) { if ($script:onceKeys.ContainsKey($key)) { $script:onceKeys.Remove($key) } } + +# ============================================================ null-safe helpers ============================================================ +# Run a read; never throw. Returns @{ ok; value; err }. +function Attempt([scriptblock]$sb) { + try { $v = & $sb; return @{ ok = $true; value = $v; err = $null } } + catch { return @{ ok = $false; value = $null; err = $_.Exception.Message } } +} +# Run a read and return its value or $fallback. Never throws. +function Try1([scriptblock]$sb, $fallback = $null) { $r = Attempt $sb; if ($r.ok -and ($null -ne $r.value)) { return $r.value }; return $fallback } +function GovIsNum($v) { ($v -is [int]) -or ($v -is [long]) -or ($v -is [double]) -or ($v -is [decimal]) -or ($v -is [single]) -or ($v -is [int16]) -or ($v -is [uint32]) -or ($v -is [uint64]) } +function GovClamp($v, $lo, $hi) { if ($v -lt $lo) { return $lo }; if ($v -gt $hi) { return $hi }; return $v } +function ReadJsonFile($path, $fallback = $null) { + try { if (Test-Path -LiteralPath $path) { return (Get-Content -LiteralPath $path -Raw -ErrorAction Stop | ConvertFrom-Json) } } catch {} + return $fallback } -function Key { (Get-Content 'C:\AI\llama-swap\api-key.txt' -Raw).Trim() } +function ReadTextFile($path, $fallback = $null) { + try { if (Test-Path -LiteralPath $path) { return ([string](Get-Content -LiteralPath $path -Raw -ErrorAction Stop)).Trim() } } catch {} + return $fallback +} +function WriteText($path, $text) { [IO.File]::WriteAllText($path, [string]$text, (New-Object System.Text.UTF8Encoding($false))) } +function Key { $k = ReadTextFile 'C:\AI\llama-swap\api-key.txt' ''; return $k } +# HTTP JSON GET/POST to llama-swap (authenticated). Throws on failure: wrap with Attempt/Try1. function Api($method, $path, $body = $null, $timeout = 10) { $h = @{ Authorization = "Bearer $(Key)" } if ($body) { return Invoke-RestMethod -Method $method -Uri "$swap$path" -Headers $h -Body ($body | ConvertTo-Json -Depth 5) -ContentType 'application/json' -TimeoutSec $timeout } return Invoke-RestMethod -Method $method -Uri "$swap$path" -Headers $h -TimeoutSec $timeout } -function Mode { try { $m = (Get-Content "$dir\mode.txt" -ErrorAction Stop).Trim().ToUpper(); if ($m -in 'AUTO','MAX','BALANCED','LEAN','OFF') { return $m } } catch {}; 'AUTO' } +function HttpJson($uri, $timeout = 5) { return Try1 { Invoke-RestMethod -Uri $uri -TimeoutSec $timeout } $null } +function HttpText($uri, $timeout = 5) { return Try1 { (Invoke-WebRequest -Uri $uri -UseBasicParsing -TimeoutSec $timeout).Content } $null } +# PDH: each path is queried on its own (one flaky counter must not spoil the others) and only samples whose +# Status is 0 are returned. A failed query ("Internal performance counter API call failed", 800007d8) or an +# invalid sample set gives @(), never zeros. +function Counters([string[]]$paths) { + $out = @() + foreach ($p in $paths) { + $r = Attempt { Get-Counter -Counter $p -ErrorAction SilentlyContinue } + if (-not $r.ok -or $null -eq $r.value) { continue } + foreach ($smp in @($r.value.CounterSamples)) { if ($null -ne $smp -and $smp.Status -eq 0) { $out += $smp } } + } + return $out +} +# process ids by name; always a real array (possibly empty), never $null and never @($null) +function ProcIds($name) { + # v4.3 (2026-10-17): 'llama-server' means OUR engine only (C:\AI\llama.cpp\*). Ollama ships its own llama-server.exe + # (C:\Apps\Ollama\lib\ollama\); on 17 Oct its llama3.2:3b runner (3.07 GiB, 24 h keep-alive) was booked as the model, + # so 'others' read 3 GiB low, the fit over-committed and free VRAM sat at 0.56 GiB (calib.json 15:44). + $out = @() + $r = Attempt { Get-Process -Name $name -ErrorAction Stop } + if ($r.ok) { foreach ($x in @($r.value)) { if ($null -eq $x) { continue } + if ($name -eq 'llama-server') { $p = $null; try { $p = $x.Path } catch {}; if ($p -and ($p -notlike 'C:\AI\llama.cpp\*')) { continue } } + $out += [int]$x.Id } } + return ,$out +} +function Mode { $m = ReadTextFile "$dir\mode.txt" 'AUTO'; $m = $m.ToUpper(); if ($m -in 'AUTO','MAX','BALANCED','LEAN','OFF') { return $m }; 'AUTO' } +function PowerMode { $p = ReadTextFile "$dir\power.txt" 'AUTO'; $p = $p.ToUpper(); if ($p -in 'AUTO','PERFORMANCE','BALANCED','SAVER') { return $p }; 'AUTO' } +function CfgNum($obj, $name, $default) { try { $v = $obj.$name; if (GovIsNum $v) { return [double]$v } } catch {}; return [double]$default } +function CfgBool($obj, $name, $default) { try { $v = $obj.$name; if ($v -is [bool]) { return $v }; if (GovIsNum $v) { return ($v -ne 0) } } catch {}; return [bool]$default } + +# ============================================================ pure decisions (mirror govpolicy.py) ============================================================ +# Turn the two PDH readings into trusted numbers. Returns @{ m = ; suspect = }. +function GovValidateVram($adapterGib, $llamaGib, $totalGib, $loaded, $llamaAlive, $lastGood, $suspectCount, $starting = $false) { + $warn = @() + $lg = $lastGood + $adapterOk = (GovIsNum $adapterGib) -and ($adapterGib -ge 0.0) -and ($adapterGib -le $totalGib * 1.05) + if (-not $adapterOk) { $warn += "adapter counter invalid ($adapterGib)" } + elseif ($loaded -and $adapterGib -lt $GOV_LOADED_MIN_ADAPTER_GIB) { $adapterOk = $false; $warn += ('adapter counter reads {0:F2} GiB while the model is loaded (impossible)' -f $adapterGib) } + if (-not $adapterOk) { + if ($lg) { $m = [ordered]@{ used = $lg.used; free = $lg.free; llama = $lg.llama; others = $lg.others; ok = $false; warn = $warn }; return @{ m = $m; suspect = $suspectCount } } + return @{ m = [ordered]@{ used = $null; free = $null; llama = $null; others = $null; ok = $false; warn = $warn }; suspect = $suspectCount } + } + $used = [double]$adapterGib + $free = GovClamp ($totalGib - $used) 0.0 $totalGib + $llamaOk = (GovIsNum $llamaGib) -and ($llamaGib -ge 0.0) -and ($llamaGib -le $used + 0.5) + if ($llamaOk -and $loaded -and $llamaGib -lt $GOV_LOADED_MIN_LLAMA_GIB) { $llamaOk = $false; $warn += ('process counter reads {0:F2} GiB for a loaded model (lagging)' -f $llamaGib) } + if (-not $llamaOk -and (GovIsNum $llamaGib) -and -not $loaded) { $llamaOk = $true } + $lgOthersNum = ($null -ne $lg) -and (GovIsNum $lg.others) + if ($llamaOk) { $llama = GovClamp ([double]$llamaGib) 0.0 $used } + elseif ($loaded -and $lgOthersNum) { $llama = GovClamp ($used - [double]$lg.others) 0.0 $used } + elseif ($loaded) { $llama = $used } + else { $llama = 0.0 } + if (-not $llamaAlive -and -not $loaded) { $llama = 0.0 } + $others = GovClamp ($used - $llama) 0.0 $totalGib + $ok = $true + if ($starting) { + $warn += 'model starting: keeping last good others' + if ($lgOthersNum) { $others = [double]$lg.others; $llama = GovClamp ($used - $others) 0.0 $used } else { $others = $null } + $m = [ordered]@{ used = [math]::Round($used, 2); free = [math]::Round($free, 2); llama = [math]::Round($llama, 2); others = $(if ($null -eq $others) { $null } else { [math]::Round($others, 2) }); ok = $false; warn = $warn } + return @{ m = $m; suspect = $suspectCount } + } + if ($lgOthersNum -and ([math]::Abs($others - [double]$lg.others) -gt $GOV_OTHERS_JUMP_GIB)) { + $suspectCount++ + if ($suspectCount -lt $GOV_OTHERS_CONFIRM_SAMPLES) { + $warn += ('others jumped {0:F2} -> {1:F2} GiB; keeping last good until confirmed ({2}/{3})' -f [double]$lg.others, $others, $suspectCount, $GOV_OTHERS_CONFIRM_SAMPLES) + $others = [double]$lg.others; $llama = GovClamp ($used - $others) 0.0 $used; $ok = $false + } else { $warn += "others change confirmed after $suspectCount samples"; $suspectCount = 0 } + } else { $suspectCount = 0 } + if (($null -ne $others) -and ($others -gt $GOV_OTHERS_PLAUSIBLE_MAX_GIB) -and -not $loaded -and $llamaAlive) { + $warn += ('others {0:F2} GiB with a llama-server alive but not ready: ignoring' -f $others) + if ($lgOthersNum) { $others = [double]$lg.others } else { $others = $null } + $ok = $false + } + $m = [ordered]@{ used = [math]::Round($used, 2); free = [math]::Round($free, 2); llama = [math]::Round($llama, 2); others = $(if ($null -eq $others) { $null } else { [math]::Round($others, 2) }); ok = $ok; warn = $warn; llama_measured = ($llamaOk -and $ok -and $loaded -and (GovIsNum $llamaGib) -and ($llamaGib -ge $GOV_LOADED_MIN_LLAMA_GIB)) } + return @{ m = $m; suspect = $suspectCount } +} +# Available RAM in GB: 0 or an absurd value is a failed PDH sample, not an empty machine. Returns @{ gb; ok }. +function GovValidateRam($ramGb, $lastGoodGb) { + if ((GovIsNum $ramGb) -and ($ramGb -ge 0.05) -and ($ramGb -le 2048.0)) { return @{ gb = [double]$ramGb; ok = $true } } + return @{ gb = $lastGoodGb; ok = $false } +} +# Consecutive samples of REAL pressure; invalid samples reset it (a reading we cannot trust is no evidence). +# A re-fit must mean OTHER apps grew: low free VRAM alone is the model's own steady state after a tight fit (2026-10-16: +# ctx 40960 left 0.65 GiB free and v4.0 re-fitted onto the same footprint every 15 min). free < threshold counts only when +# others has grown >= $growthMin since the post-launch baseline; no baseline -> it does not count. free < $hardFloor always counts. +function GovPressureStep($count, $freeGib, $ramGb, $vramOk, $ramOk, $freeThreshold, $ramCritical, $othersGib = $null, $baselineOthers = $null, $growthMin = 0.5, $hardFloor = 0.25) { + $now = $false + if ($vramOk -and (GovIsNum $freeGib)) { + if ($freeGib -lt $hardFloor) { $now = $true } + elseif (($freeGib -lt $freeThreshold) -and (GovIsNum $othersGib) -and (GovIsNum $baselineOthers) -and (($othersGib - $baselineOthers) -ge $growthMin)) { $now = $true } + } + if ($ramOk -and (GovIsNum $ramGb) -and ($ramGb -lt $ramCritical)) { $now = $true } + if ($now) { return ($count + 1) }; return 0 +} +function GovPressureReason($freeGib, $ramGb, $freeThreshold, $ramCritical, $othersGib = $null, $baselineOthers = $null, $hardFloor = 0.25) { + $parts = @() + if ((GovIsNum $freeGib) -and ($freeGib -lt $hardFloor)) { $parts += ('free VRAM {0:F2} GiB < hard floor {1:F2}' -f [double]$freeGib, [double]$hardFloor) } + elseif ((GovIsNum $freeGib) -and ($freeGib -lt $freeThreshold)) { + if ((GovIsNum $othersGib) -and (GovIsNum $baselineOthers)) { $parts += ('free VRAM {0:F2} GiB < {1:F2} with others {2:+0.00;-0.00} GiB since baseline {3:F2}' -f [double]$freeGib, [double]$freeThreshold, ([double]$othersGib - [double]$baselineOthers), [double]$baselineOthers) } + else { $parts += ('free VRAM {0:F2} GiB < {1:F2}' -f [double]$freeGib, [double]$freeThreshold) } + } + if ((GovIsNum $ramGb) -and ($ramGb -lt $ramCritical)) { $parts += ('RAM {0:F2} GB < {1:F2}' -f [double]$ramGb, [double]$ramCritical) } + if ($parts.Count -eq 0) { return 'no pressure' }; return ($parts -join ', ') +} +# After a launch the counters settle: take the baseline on the $need-th consecutive loaded sample with valid VRAM, a directly +# measured llama share and a known n_ctx. Returns @{ count; take }. +function GovBaselineReady($loaded, $vramOk, $llamaMeasured, $nCtx, $stableCount, $need = 2) { + if ($loaded -and $vramOk -and $llamaMeasured -and (GovIsNum $nCtx) -and ($nCtx -gt 0)) { $stableCount++; return @{ count = $stableCount; take = ($stableCount -ge $need) } } + return @{ count = 0; take = $false } +} +function GovPredictedLlamaGib($baseGib, $ctx, $kvKibPerToken, $overheadGib = 0.0) { return ([double]$baseGib + [double]$overheadGib + [double]$ctx * [double]$kvKibPerToken / 1048576.0) } +# Learn the footprint launch.ps1's model misses (drafter KV, mmproj, compute buffers): EMA of (measured - predicted), clamped. +# Returns @{ overhead; predicted; delta }. +function GovCalibrate($prevOverhead, $llamaActualGib, $baseGib, $ctx, $kvKibPerToken, $alpha = 0.5, $maxOverhead = 1.5, $minOverhead = -0.5) { + $predicted = [double]$baseGib + [double]$ctx * [double]$kvKibPerToken / 1048576.0 + $raw = [double]$llamaActualGib - $predicted + $delta = GovClamp $raw $minOverhead $maxOverhead + if (GovIsNum $prevOverhead) { $new = [double]$prevOverhead + $alpha * ($delta - [double]$prevOverhead) } else { $new = $delta } + return @{ overhead = [math]::Round($new, 2); predicted = [math]::Round($predicted, 2); delta = [math]::Round($raw, 2) } +} +# What launch.ps1 adds to base_gib: the learned overhead, never negative. +function GovLaunchOverhead($calibEntry, $enabled = $true, $maxOverhead = 1.5) { + if (-not $enabled -or ($null -eq $calibEntry)) { return 0.0 } + $v = $null; try { $v = $calibEntry.overhead_gib } catch {} + if (-not (GovIsNum $v)) { return 0.0 } + return [math]::Round((GovClamp ([double]$v) 0.0 $maxOverhead), 2) +} +# After a re-fit that landed on the same ctx (+- one step) as before, block further re-fits until others changed >= $growthMin. +function GovRefitRepeatBlocked($prevCtx, $newCtx, $othersNow, $othersAtRefit, $growthMin = 0.5, $step = 4096) { + if (-not ((GovIsNum $prevCtx) -and (GovIsNum $newCtx))) { return $false } + if ([math]::Abs([double]$newCtx - [double]$prevCtx) -gt $step) { return $false } + if ((GovIsNum $othersNow) -and (GovIsNum $othersAtRefit) -and ([math]::Abs([double]$othersNow - [double]$othersAtRefit) -ge $growthMin)) { return $false } + return $true +} +# Which profile AUTO wants this sample ($a = profiles.json 'auto'). Invalid readings never push LEAN. +function GovProfileChoice($mode, $idleSec, $ramGb, $ramOk, $othersGib, $othersOk, $cpuHighCount, $a) { + if ($mode -ne 'AUTO' -and $mode -ne 'OFF') { return $mode } + $pressure = ($ramOk -and (GovIsNum $ramGb) -and ($ramGb -lt (CfgNum $a 'ram_floor_gb' 3.5))) -or + ($othersOk -and (GovIsNum $othersGib) -and ($othersGib -gt (CfgNum $a 'others_vram_lean_gib' 3.5))) -or + ($cpuHighCount -ge 8) + if ($pressure) { return 'LEAN' } + if (($idleSec -ge (CfgNum $a 'idle_for_max_sec' 600)) -and $ramOk -and (GovIsNum $ramGb) -and ($ramGb -ge (CfgNum $a 'ram_for_max_gb' 8.0)) -and + $othersOk -and (GovIsNum $othersGib) -and ($othersGib -lt (CfgNum $a 'others_vram_max_gib' 3.0))) { return 'MAX' } + return 'BALANCED' +} +# One sample's action from a hashtable of inputs (see govpolicy.decide). Returns @{ action; reason }. +# action: none | unload | refit | upgrade | idle-unload | prewarm +function GovDecide($s) { + if ($s.mode -eq 'OFF') { + if ($s.loaded -and ($s.in_flight -eq $false) -and ($s.quiet_sec -ge 30)) { return @{ action = 'unload'; reason = 'mode OFF' } } + return @{ action = 'none'; reason = 'mode OFF' } + } + if ($s.loaded) { + if ($null -eq $s.in_flight) { return @{ action = 'none'; reason = 'slot state unknown' } } + if ($s.in_flight -eq $true) { return @{ action = 'none'; reason = 'request in flight' } } + $persistent = ($s.pressure_count -gt 0) -and (($s.pressure_count * $s.sample_sec) -ge $s.persist_sec) + if ($persistent -and ($s.quiet_sec -ge 30)) { + $hf = 0.25; if (GovIsNum $s.hard_floor) { $hf = $s.hard_floor } + $why = GovPressureReason $s.free_gib $s.ram_gb $s.free_threshold $s.ram_critical $s.others_gib $s.baseline_others $hf + if ($s.committed -eq 'LEAN') { return @{ action = 'unload'; reason = "pressure, LEAN ($why)" } } + if (($s.cur_id -eq 'qwen3.8-27b-long') -or $s.emergency) { return @{ action = 'none'; reason = "pressure but protected ($why)" } } + if ($s.refit_blocked) { return @{ action = 'none'; reason = "pressure but a re-fit would repeat the same ctx; waiting for others to change ($why)" } } + if ($s.since_refit_min -ge $s.refit_interval_min) { return @{ action = 'refit'; reason = ('{0} for {1}s -> re-fit context ({2})' -f $why, ($s.pressure_count * $s.sample_sec), $s.committed) } } + return @{ action = 'none'; reason = ('pressure persists but re-fit rate-limited ({0:F0}/{1} min)' -f [double]$s.since_refit_min, $s.refit_interval_min) } + } + if (($s.idle_unload_min -gt 0) -and ($s.quiet_sec -ge $s.idle_unload_min * 60)) { + if ($s.agent_active) { return @{ action = 'none'; reason = 'idle but an agent client is active: stay warm' } } + return @{ action = 'idle-unload'; reason = ('idle {0} min in {1}' -f [math]::Round($s.quiet_sec / 60), $s.committed) } + } + if (($s.loaded_profile -eq 'LEAN') -and ($s.committed -ne 'LEAN') -and ($s.quiet_sec -ge $s.quiet_before_reload_sec) -and ($s.since_refit_min -ge $s.refit_interval_min)) { + return @{ action = 'upgrade'; reason = "upgrade LEAN -> $($s.committed)" } } + if (($s.loaded_profile -eq 'BALANCED') -and ($s.committed -eq 'MAX') -and ($s.quiet_sec -ge $s.max_upgrade_quiet_min * 60) -and ($s.since_refit_min -ge $s.refit_interval_min)) { + return @{ action = 'upgrade'; reason = 'upgrade BALANCED -> MAX' } } + return @{ action = 'none'; reason = 'steady' } + } + if (($s.state -eq 'stopped') -and -not $s.other_running -and ($s.since_prewarm_min -ge $s.prewarm_cooldown_min)) { + if ($s.committed -eq 'MAX') { return @{ action = 'prewarm'; reason = 'PC idle - keep model warm in MAX' } } + if ($s.agent_active -and ($s.committed -ne 'LEAN')) { return @{ action = 'prewarm'; reason = 'agent client active - keep model warm' } } + } + return @{ action = 'none'; reason = "not loaded ($($s.state))" } +} +# Windows power plan with hysteresis (v4.2, 2026-10-16: v4.1 flipped the plan 104 times in 400 log lines, driven by CPU +# bursts from agent clients). Upgrades are immediate; downgrades go ONE step at a time and only after the lower demand +# has persisted for the whole dwell AND the current plan has been held for the dwell. While an agent client is active +# (codex/claude process, or a model request within agent_recent_min) the floor is BALANCED. SAVER needs the PC idle +# (no input) for saver_idle_min AND the model quiet for saver_model_quiet_min AND calm CPU. +# $st: @{ now = ; entered = ; down_since = ; cpu_busy = } (mutated and returned) +# $in: @{ t = ; mode = AUTO|PERFORMANCE|BALANCED|SAVER; cpu = ; idle_sec; quiet_sec; model_busy; agent_active; cfg = profiles.json 'power' } +# Returns @{ st; want; apply = ; reason; why }. +$GOV_POWER_RANK = @{ SAVER = 0; BALANCED = 1; PERFORMANCE = 2 } +function GovPowerDecide($st, $in) { + $p = $in.cfg + $dwellSec = (CfgNum $p 'dwell_min' 10) * 60.0 + $saverIdleSec = (CfgNum $p 'saver_idle_min' 15) * 60.0 + $saverQuietSec = (CfgNum $p 'saver_model_quiet_min' 15) * 60.0 + $recentSec = CfgNum $p 'perf_model_recent_sec' 120 + $busyPct = CfgNum $p 'cpu_busy_pct' 40 + $busySamples = [int](CfgNum $p 'cpu_busy_samples' 2) + $calmPct = CfgNum $p 'cpu_calm_pct' 25 + if ($null -eq $st) { $st = @{ now = $null; entered = $in.t; down_since = $null; cpu_busy = 0 } } + $cpu = $in.cpu; if (-not (GovIsNum $cpu)) { $cpu = 30.0 } # unknown CPU: neutral + $busy = 0; if (GovIsNum $st.cpu_busy) { $busy = [int]$st.cpu_busy } + if ($cpu -ge $busyPct) { $busy++ } elseif ($cpu -lt $calmPct) { $busy = 0 } + $st.cpu_busy = $busy + $idle = 0.0; if (GovIsNum $in.idle_sec) { $idle = [double]$in.idle_sec } + $quiet = 0.0; if (GovIsNum $in.quiet_sec) { $quiet = [double]$in.quiet_sec } + if ($in.mode -ne 'AUTO') { $want = [string]$in.mode; $why = "power mode $($in.mode)" } + elseif ($in.model_busy) { $want = 'PERFORMANCE'; $why = 'model busy' } + elseif ($quiet -lt $recentSec) { $want = 'PERFORMANCE'; $why = ('model request {0}s ago' -f [math]::Round($quiet)) } + elseif ($busy -ge $busySamples) { $want = 'PERFORMANCE'; $why = ('cpu {0}% for {1} samples' -f $cpu, $busy) } + elseif ($in.agent_active) { $want = 'BALANCED'; $why = 'agent client active (floor)' } + elseif (($idle -ge $saverIdleSec) -and ($quiet -ge $saverQuietSec) -and ($cpu -lt $calmPct)) { $want = 'SAVER'; $why = ('PC idle {0} min, model quiet {1} min' -f [math]::Round($idle / 60), [math]::Round($quiet / 60)) } + else { $want = 'BALANCED'; $why = 'PC in use' } + $apply = $null; $reason = '' + $now = $st.now + if ($null -eq $now) { $apply = $want; $reason = "startup: $why" } + elseif ($in.mode -ne 'AUTO') { if ($want -ne $now) { $apply = $want; $reason = $why } } + elseif ($GOV_POWER_RANK[$want] -gt $GOV_POWER_RANK[$now]) { $apply = $want; $reason = "up: $why" } + elseif ($GOV_POWER_RANK[$want] -lt $GOV_POWER_RANK[$now]) { + if ($null -eq $st.down_since) { $st.down_since = $in.t } + $held = ($in.t - $st.entered).TotalSeconds + $lowFor = ($in.t - $st.down_since).TotalSeconds + if (($held -ge $dwellSec) -and ($lowFor -ge $dwellSec)) { + $step = $null; foreach ($k in $GOV_POWER_RANK.Keys) { if ($GOV_POWER_RANK[$k] -eq ($GOV_POWER_RANK[$now] - 1)) { $step = $k } } # one level down + $apply = $step; $reason = ('down after {0} min: {1}' -f [math]::Round($lowFor / 60), $why) + } + } else { $st.down_since = $null } + if ($apply) { $st.now = $apply; $st.entered = $in.t; $st.down_since = $null } + return @{ st = $st; want = $want; apply = $apply; reason = $reason; why = $why } +} +# Context that fits (same formula as launch.ps1): (total - margin - others - base) GiB of KV, rounded down to 4096, clamped. +function GovFitCtx($totalGib, $marginGib, $othersGib, $baseGib, $kvKibPerToken, $ctxMin, $ctxMax, $overheadGib = 0.0) { + $kib = ([double]$totalGib - [double]$marginGib - [double]$othersGib - [double]$baseGib - [double]$overheadGib) * 1048576.0 + $ctx = 0; if ($kib -gt 0) { $ctx = [int]([math]::Floor($kib / [double]$kvKibPerToken / 4096) * 4096) } + return [math]::Max([int]$ctxMin, [math]::Min([int]$ctxMax, $ctx)) +} -function Sense { - $s = [ordered]@{ idle_sec = [math]::Round([IdleTime]::Seconds()) } - $c = Get-Counter -Counter '\Memory\Available MBytes','\Processor(_Total)\% Processor Time','\GPU Adapter Memory(*)\Dedicated Usage' -ErrorAction SilentlyContinue - if (-not $c -and $script:lastSense) { return $script:lastSense } # transient PDH failure: reuse last good sample, never act on zeros - $smp = $c.CounterSamples - $s.ram_avail_gb = [math]::Round((($smp | ? Path -like '*available mbytes').CookedValue | measure -Sum).Sum / 1024, 2) - $s.cpu_total = [math]::Round((($smp | ? Path -like '*processor(_total)*').CookedValue | measure -Sum).Sum, 1) - $vUsed = (($smp | ? Path -like '*gpu adapter memory*').CookedValue | measure -Sum).Sum - $pids = @(Get-Process llama-server -ErrorAction SilentlyContinue | % Id) - $llamaV = 0.0; $llamaCpu = 0.0 - if ($pids.Count) { - $g = (Get-Counter '\GPU Process Memory(*)\Dedicated Usage' -ErrorAction SilentlyContinue).CounterSamples - foreach ($id in $pids) { $llamaV += (($g | ? InstanceName -like "pid_$($id)_*").CookedValue | measure -Sum).Sum } - $pc = (Get-Counter '\Process(llama-server*)\% Processor Time' -ErrorAction SilentlyContinue).CounterSamples - $llamaCpu = (($pc.CookedValue | measure -Sum).Sum) / [Environment]::ProcessorCount - } - $s.vram_used_gib = [math]::Round($vUsed / 1GB, 2) - $s.vram_free_gib = [math]::Round(($vramTotal - $vUsed) / 1GB, 2) - $s.vram_llama_gib = [math]::Round($llamaV / 1GB, 2) - $s.vram_others_gib = [math]::Round(($vUsed - $llamaV) / 1GB, 2) - $s.cpu_others = [math]::Round([math]::Max(0, $s.cpu_total - $llamaCpu), 1) - $script:lastSense = $s; $s +# ============================================================ loop error accounting / self-heal ============================================================ +$script:errStreak = 0; $script:errTotal = 0; $script:lastError = $null; $script:lastErrorAt = $null; $script:heals = 0 +function ReInit { + $script:lastGoodVram = $null; $script:lastGoodRam = $null; $script:suspect = 0; $script:needLog = @(); $script:ctxCache = $null + $script:pressureCount = 0; $script:senseWarn = @(); $script:statusDraft = $null + Set-Variable -Name candidate -Value $null -Scope Script; Set-Variable -Name count -Value 0 -Scope Script; Set-Variable -Name cpuHigh -Value 0 -Scope Script +} +function NoteLoopError($er) { + $msg = $er.Exception.Message; $line = $null; try { $line = $er.InvocationInfo.ScriptLineNumber } catch {} + $script:errStreak++; $script:errTotal++; $script:lastError = "$msg (line $line)"; $script:lastErrorAt = Get-Date + if ($script:errStreak -eq 1) { Log "loop error at line ${line}: $msg" } + elseif ($script:errStreak % 20 -eq 0) { Log "loop error x$($script:errStreak) (last at line ${line}: $msg)" } + if (($script:errStreak -eq 4) -or (($script:errStreak -gt 4) -and ($script:errStreak % 40 -eq 0))) { ReInit; $script:heals++; Log "self-heal: state re-initialised after $($script:errStreak) consecutive loop errors" } +} + +if ($FunctionsOnly) { return } + +# ============================================================ sensing ============================================================ +# slotlib (slot save/restore) is optional: without it the governor behaves as before, minus the restore. +$script:slotLib = $false; $script:slots = $null; $script:warmJob = $null +try { . "$dir\slotlib.ps1"; $script:slotLib = $true; $script:SlotLogPath = "$dir\governor.log" } catch {} + +$script:lastGoodVram = $null; $script:lastGoodRam = $null; $script:suspect = 0; $script:senseWarn = @() +# post-launch baseline (others/free/ctx when the counters settled) and the learned footprint per variant (calib.json) +$script:baseline = $null; $script:baseStable = 0; $script:baseStarted = $null +$script:refitPrevCtx = $null; $script:refitOthers = $null; $script:refitBlocked = $false +function VariantOf($id) { return (Try1 { $cfg.variants.PSObject.Properties | ForEach-Object { $_.Value } | Where-Object { $_.id -eq $id } | Select-Object -First 1 } $null) } +function CalibRead { $c = ReadJsonFile "$dir\calib.json"; if ($null -eq $c) { return [pscustomobject]@{} }; return $c } +function CalibEntry($id) { $c = CalibRead; $pr = $c.PSObject.Properties[$id]; if ($pr) { return $pr.Value }; return $null } +function CalibWrite($id, $entry) { + try { + $c = CalibRead + if ($c.PSObject.Properties[$id]) { $c.PSObject.Properties.Remove($id) } + $c | Add-Member -NotePropertyName $id -NotePropertyValue $entry + WriteText "$dir\calib.json.tmp" ($c | ConvertTo-Json -Depth 5) + Move-Item -LiteralPath "$dir\calib.json.tmp" -Destination "$dir\calib.json" -Force + } catch { Log "calib write error: $($_.Exception.Message)" } +} +function Sense($loaded, $starting) { + $s = [ordered]@{ idle_sec = [int](Try1 { [math]::Round([IdleTime]::Seconds()) } 0) } + $warn = @() + # each counter path is its own PDH query (see Counters): a flaky GPU counter can no longer zero the RAM/CPU samples + $smp = Counters @('\Memory\Available MBytes', '\Processor(_Total)\% Processor Time') + $ramRaw = $null; $cpuRaw = $null + foreach ($x in $smp) { if ($x.Path -like '*available mbytes') { $ramRaw = [double]$x.CookedValue / 1024.0 } elseif ($x.Path -like '*processor(_total)*') { $cpuRaw = [double]$x.CookedValue } } + $ram = GovValidateRam $ramRaw $script:lastGoodRam + if ($ram.ok) { $script:lastGoodRam = $ram.gb } else { $warn += "RAM counter invalid ($ramRaw)" } + $s.ram_avail_gb = $(if ($null -eq $ram.gb) { $null } else { [math]::Round([double]$ram.gb, 2) }); $s.ram_ok = $ram.ok + if ((GovIsNum $cpuRaw) -and $cpuRaw -ge 0 -and $cpuRaw -le 100) { $s.cpu_total = [math]::Round($cpuRaw, 1) } else { $s.cpu_total = $null; $warn += 'CPU counter invalid' } + # GPU adapter: max over adapters (the B60 is the only one with dedicated memory; virtual adapters read 0) + $ad = Counters @('\GPU Adapter Memory(*)\Dedicated Usage') + $adapterGib = $null + foreach ($x in $ad) { $v = [double]$x.CookedValue / 1GB; if (($null -eq $adapterGib) -or ($v -gt $adapterGib)) { $adapterGib = $v } } + # GPU per-process: the llama-server share + $llamaIds = ProcIds 'llama-server' + $llamaGib = $null; $llamaCpu = 0.0 + if ($llamaIds.Count) { + $g = Counters @('\GPU Process Memory(*)\Dedicated Usage') + if ($g.Count) { $llamaGib = 0.0; foreach ($x in $g) { foreach ($lid in $llamaIds) { if ($x.InstanceName -like "pid_$($lid)_*") { $llamaGib += [double]$x.CookedValue / 1GB } } } } + $pc = Counters @('\Process(llama-server*)\% Processor Time') + if ($pc.Count) { $sum = 0.0; foreach ($x in $pc) { $sum += [double]$x.CookedValue }; $llamaCpu = $sum / [Environment]::ProcessorCount } + } + $vr = GovValidateVram $adapterGib $llamaGib $script:vramTotalGib $loaded ($llamaIds.Count -gt 0) $script:lastGoodVram $script:suspect $starting + $script:suspect = $vr.suspect + $m = $vr.m + if ($m.ok) { $script:lastGoodVram = $m } + $warn += @($m.warn) + $s.vram_total_gib = $script:vramTotalGib + $s.vram_used_gib = $m.used; $s.vram_free_gib = $m.free; $s.vram_llama_gib = $m.llama; $s.vram_others_gib = $m.others; $s.vram_ok = $m.ok + $s.llama_measured = [bool]$m.llama_measured + $s.vram_adapter_raw_gib = $(if ($null -eq $adapterGib) { $null } else { [math]::Round($adapterGib, 2) }) + $s.vram_llama_raw_gib = $(if ($null -eq $llamaGib) { $null } else { [math]::Round($llamaGib, 2) }) + $s.cpu_others = $(if ($null -eq $s.cpu_total) { $null } else { [math]::Round([math]::Max(0, $s.cpu_total - $llamaCpu), 1) }) + $s.llama_pids = $llamaIds.Count + $script:senseWarn = $warn + return $s +} +# Is a request in flight on the loaded server? $true / $false / $null (= could not tell). +function InFlight($port) { + $known = $false; $busy = $false + $sl = HttpJson "http://127.0.0.1:$port/slots" 5 + if ($null -ne $sl) { $known = $true; foreach ($x in @($sl)) { if ($x.is_processing -eq $true) { $busy = $true } } } + $met = HttpText "http://127.0.0.1:$port/metrics" 5 + if ($met) { + $known = $true + foreach ($name in 'requests_processing', 'requests_deferred') { + $mm = [regex]::Match($met, "(?m)^llamacpp:$name\s+([0-9.eE+-]+)") + if ($mm.Success) { $v = 0.0; if ([double]::TryParse($mm.Groups[1].Value, [ref]$v) -and $v -gt 0) { $busy = $true } } + } + } + if (-not $known) { return $null } + return $busy } function ModelState { - $st = [ordered]@{ loaded = $false; state = 'stopped'; other_running = $null; processing = $false; tokens = $null; n_ctx = $null } - try { $r = (Api GET '/running').running } catch { $we = $_.Exception; $st.state = $(if (($we -is [System.Net.WebException]) -and -not $we.Response) { 'swap-down' } else { 'api-error' }); return $st } - foreach ($m in @($r)) { - if ($ids -contains $m.model) { $st.state = $m.state; $st.loaded = ($m.state -eq 'ready'); $script:curId = $m.model - $script:curPort = $ports[$m.model] } - elseif ($m.model) { $st.other_running = $m.model } + $st = [ordered]@{ loaded = $false; state = 'stopped'; other_running = $null; processing = $null; tokens = $null; n_ctx = $null; prompt_tokens = 0; id = $script:curId } + $r = Attempt { (Api GET '/running' $null 10).running } + if (-not $r.ok) { + $st.state = 'api-error' + if ($r.err -match 'Unable to connect|actively refused|connection could not be made|The remote name|timed out|No connection') { $st.state = 'swap-down' } + return $st + } + foreach ($x in @($r.value)) { + if ($null -eq $x) { continue } + if ($ids -contains $x.model) { $st.state = [string]$x.state; $st.loaded = ($x.state -eq 'ready'); $script:curId = $x.model; $script:curPort = $ports[$x.model] } + elseif ($x.model) { $st.other_running = [string]$x.model } } $st.id = $script:curId if ($st.loaded) { - try { - $sl = Invoke-RestMethod "http://127.0.0.1:$($script:curPort)/slots" -TimeoutSec 5 - $st.processing = [bool](@($sl) | ? { $_.is_processing }) - $st.prompt_tokens = [int](@($sl) | % { [int]$_.n_prompt_tokens + [int]$_.params.n_predict } | measure -Maximum).Maximum - if (-not $script:ctxCache) { $script:ctxCache = (Invoke-RestMethod "http://127.0.0.1:$($script:curPort)/props" -TimeoutSec 5).default_generation_settings.n_ctx } - $st.n_ctx = $script:ctxCache - $met = Invoke-WebRequest "http://127.0.0.1:$($script:curPort)/metrics" -UseBasicParsing -TimeoutSec 5 - $st.tokens = ([regex]::Matches($met.Content, '(?m)^llamacpp:(prompt_tokens_total|tokens_predicted_total)\s+([\d.e+]+)') | % { [double]$_.Groups[2].Value } | measure -Sum).Sum - } catch {} + $st.processing = InFlight $script:curPort + $sl = HttpJson "http://127.0.0.1:$($script:curPort)/slots" 5 + if ($null -ne $sl) { + $mx = 0 + foreach ($x in @($sl)) { $n = 0; try { $n = [int]$x.n_prompt_tokens + [int]$x.params.n_predict } catch {}; if ($n -gt $mx) { $mx = $n } } + $st.prompt_tokens = $mx + } + if (-not $script:ctxCache) { $p = HttpJson "http://127.0.0.1:$($script:curPort)/props" 5; if ($null -ne $p) { $script:ctxCache = Try1 { [int]$p.default_generation_settings.n_ctx } $null } } + $st.n_ctx = $script:ctxCache + $met = HttpText "http://127.0.0.1:$($script:curPort)/metrics" 5 + if ($met) { + $sum = 0.0; $any = $false + foreach ($mm in [regex]::Matches($met, '(?m)^llamacpp:(prompt_tokens_total|tokens_predicted_total)\s+([\d.e+]+)')) { $v = 0.0; if ([double]::TryParse($mm.Groups[2].Value, [ref]$v)) { $sum += $v; $any = $true } } + if ($any) { $st.tokens = $sum } + } } else { $script:ctxCache = $null } - $st + return $st +} +function LoadedEmergency { $j = ReadJsonFile "$dir\running.json"; if ($j) { return [bool](Try1 { $j.emergency } $false) }; return $false } +function LoadedProfile { $j = ReadJsonFile "$dir\running.json"; if ($j) { return (Try1 { [string]$j.profile } $null) }; return $null } +function AgentActive($a, $quietSec) { + $names = @('codex', 'claude') + try { if ($a.agent_processes) { $names = @($a.agent_processes | ForEach-Object { [string]$_ }) } } catch {} + $found = @() + foreach ($n in $names) { if ((ProcIds $n).Count -gt 0) { $found += $n } } + $recentMin = CfgNum $a 'agent_recent_min' 10 + $recent = $script:sawActivity -and ($quietSec -le $recentMin * 60) + return @{ active = (($found.Count -gt 0) -or $recent); procs = $found; recent = $recent } +} + +# ============================================================ actions ============================================================ +$script:unloadResult = 'failed'; $script:prewarmOk = $false +function StopWarmJob { + $j = $script:warmJob; if (-not $j) { return } + $was = $j.State + try { Stop-Job $j -ErrorAction SilentlyContinue; Remove-Job $j -Force -ErrorAction SilentlyContinue } catch {} + $script:warmJob = $null + if ($script:slotLib) { try { SlotClearPhase "$dir\phase.json" } catch {} } + if ($was -eq 'Running') { Log 'restore warm-up job stopped before unload' } +} +function ReapWarmJob { + $j = $script:warmJob; if (-not $j) { return } + if ($j.State -eq 'Running') { + if (((Get-Date) - $j.PSBeginTime).TotalSeconds -le 600) { return } + Stop-Job $j -ErrorAction SilentlyContinue; Log 'warm-up job exceeded 10 min and was stopped' + } + try { Receive-Job $j -ErrorAction SilentlyContinue -ErrorVariable je | Out-Null; if ($je) { Log "warm-up job error: $($je[0])" } } catch {} + Remove-Job $j -Force -ErrorAction SilentlyContinue; $script:warmJob = $null + if ($script:slotLib) { try { SlotClearPhase "$dir\phase.json" } catch {} } +} +# Every governor-initiated unload goes through here. Result in $script:unloadResult: ok | busy | failed. +function Unload($why) { + $script:unloadResult = 'failed' + StopWarmJob + # a request may have started since the sample was taken: re-check right now + $busy = InFlight $script:curPort + if ($busy -eq $true) { Log "UNLOAD postponed ($why): a request is in flight"; $script:unloadResult = 'busy'; return } + if ($null -eq $busy) { Log "UNLOAD postponed ($why): slot state unknown"; $script:unloadResult = 'busy'; return } + if ($script:slotLib -and $script:slots) { + $go = $true + try { + $kv = Try1 { $cfg.variants.PSObject.Properties | ForEach-Object { $_.Value } | Where-Object { $_.id -eq $script:curId } | Select-Object -First 1 } $null + $sv = @(SlotSave $script:slots $script:curId $script:curPort (SlotModelPath $cfg $script:curId) $script:ctxCache $kv); $go = [bool]$sv[-1] + SlotPrune $script:slots $ids + } catch { Log "slot save error: $($_.Exception.Message)" } + if (-not $go) { Log "UNLOAD postponed ($why): a request started during the slot save"; $script:unloadResult = 'busy'; return } + } + # llama-swap waits for the process to exit before answering: 90 s, not 10 (the old 10 s timeout produced 'unload failed' + # followed by a relaunch on top of the dying server, which is how others=21 GiB got measured at launch) + $r = Attempt { Api POST "/api/models/unload/$($script:curId)" $null 90 } + if ($r.ok) { Log "UNLOAD ($why)"; $script:lastReload = Get-Date; $script:ctxCache = $null; $script:unloadResult = 'ok' } + else { Log "unload failed: $($r.err)" } +} +# wait (max $sec) for every llama-server process to be gone so the next launch measures clean VRAM +function WaitServerGone($sec) { + $t = Get-Date + while (((Get-Date) - $t).TotalSeconds -lt $sec) { if ((ProcIds 'llama-server').Count -eq 0) { return $true }; Start-Sleep -Seconds 1 } + return ((ProcIds 'llama-server').Count -eq 0) } -function LoadedEmergency { try { [bool](Get-Content "$dir\running.json" -Raw | ConvertFrom-Json).emergency } catch { $false } } -function LoadedProfile { try { (Get-Content "$dir\running.json" -Raw | ConvertFrom-Json).profile } catch { $null } } -function Unload($why) { try { Api POST "/api/models/unload/$($script:curId)" | Out-Null; Log "UNLOAD ($why)"; $script:lastReload = Get-Date; $script:ctxCache = $null } catch { Log "unload failed: $($_.Exception.Message)" } } function Prewarm($why) { - $script:lastPrewarm = Get-Date; $script:lastBusy = $script:lastPrewarm # a fresh load is not 'idle': otherwise idle_unload_min kills it on the next sample + $script:prewarmOk = $false + $script:lastPrewarm = Get-Date; $script:lastBusy = $script:lastPrewarm # a fresh load is not 'idle' try { - $hdr = "$dir\.auth-header"; "Authorization: Bearer $(Key)" | Set-Content $hdr -NoNewline - $body = "$dir\.prewarm.json"; '{"model":"' + $script:curId + '","max_tokens":1,"messages":[{"role":"user","content":"hi"}],"chat_template_kwargs":{"enable_thinking":false}}' | Set-Content $body -NoNewline - Start-Process curl.exe -WindowStyle Hidden -ArgumentList '-s','-m','300','-o','NUL','-H',('@' + $hdr),'-H','"Content-Type: application/json"','--data-binary',('@' + $body),"$swap/v1/chat/completions" | Out-Null - Log "PREWARM ($why)" + if ($script:warmJob -and $script:warmJob.State -eq 'Running') { Log "PREWARM skipped ($why): previous warm-up job still running"; return } + $sc = $null + if ($script:slotLib -and $script:slots) { $sc = Try1 { SlotRestorePlan $script:slots $script:curId (SlotModelPath $cfg $script:curId) } $null } + if ($sc) { + $jp = @{ swap = $swap; key = (Key); id = $script:curId; port = $script:curPort; model_path = (SlotModelPath $cfg $script:curId); dir = $script:slots.dir; headroom = $script:slots.headroom; log = "$dir\governor.log"; phase_file = "$dir\phase.json" } + $script:warmJob = Start-Job -ScriptBlock { param($lib, $jp) . $lib; SlotWarmFlow $jp } -ArgumentList "$dir\slotlib.ps1", $jp + Log "PREWARM ($why) restore-first" + } else { + $hdr = "$dir\.auth-header"; "Authorization: Bearer $(Key)" | Set-Content $hdr -NoNewline + $body = "$dir\.prewarm.json"; '{"model":"' + $script:curId + '","max_tokens":1,"messages":[{"role":"user","content":"hi"}],"chat_template_kwargs":{"enable_thinking":false}}' | Set-Content $body -NoNewline + Start-Process curl.exe -WindowStyle Hidden -ArgumentList '-s','-m','300','-o','NUL','-H',('@' + $hdr),'-H','"Content-Type: application/json"','--data-binary',('@' + $body),"$swap/v1/chat/completions" | Out-Null + Log "PREWARM ($why)" + } + $script:prewarmOk = $true } catch { Log "prewarm failed: $($_.Exception.Message)" } } -# ---- smart Windows power plan: SAVER when nobody is using the PC or the model, PERFORMANCE under load ---- +# unload, then prewarm only if the unload really happened and the old server is gone +function UnloadThenPrewarm($why, $pwWhy) { + Unload $why + if ($script:unloadResult -ne 'ok') { return } + $script:lastRefit = Get-Date + if (-not (WaitServerGone 45)) { Log 'old llama-server still alive 45 s after unload; prewarm deferred to the next sample' ; $script:pendingPrewarm = @{ why = $pwWhy; tries = 0 }; return } + Start-Sleep -Seconds 2 # let the driver release the VRAM before launch.ps1 measures + Prewarm $pwWhy + if (-not $script:prewarmOk) { $script:pendingPrewarm = @{ why = $pwWhy; tries = 0 } } +} + +# ---- smart Windows power plan: SAVER when nobody is using the PC or the model, PERFORMANCE under load; hysteresis in GovPowerDecide ---- $planGuid = @{ PERFORMANCE = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'; BALANCED = '381b4222-f694-41f0-9685-ff5bb260df2e'; SAVER = 'a1841308-3541-4fab-bc81-f71556f20b4a' } -$script:powNow = $null; $script:powCand = $null; $script:powCount = 0; $script:cpuBusy = 0 -function PowerMode { try { $p = (Get-Content "$dir\power.txt" -ErrorAction Stop).Trim().ToUpper(); if ($p -in 'AUTO','PERFORMANCE','BALANCED','SAVER') { return $p } } catch {}; 'AUTO' } -function ApplyPower($s, $quietSec, $modelBusy) { +$script:pow = @{ now = $null; entered = (Get-Date); down_since = $null; cpu_busy = 0 } +$script:powWhy = '' +function ApplyPower($s, $quietSec, $modelBusy, $agentActive) { $pm = PowerMode - if ($s.cpu_total -ge 40) { $script:cpuBusy++ } elseif ($s.cpu_total -lt 25) { $script:cpuBusy = 0 } - if ($pm -ne 'AUTO') { $want = $pm } - elseif ($modelBusy -or $quietSec -lt 120 -or $script:cpuBusy -ge 2) { $want = 'PERFORMANCE' } - elseif ($s.idle_sec -ge 600 -and $quietSec -ge 300 -and $s.cpu_total -lt 25) { $want = 'SAVER' } - else { $want = 'BALANCED' } - if ($want -eq $script:powCand) { $script:powCount++ } else { $script:powCand = $want; $script:powCount = 1 } - $rank = @{ SAVER = 0; BALANCED = 1; PERFORMANCE = 2 } - $up = ($script:powNow -eq $null) -or ($rank[$want] -gt $rank[$script:powNow]) - if ($want -ne $script:powNow -and ($up -or $script:powCount -ge 4 -or $pm -ne 'AUTO')) { - $act = (powercfg /getactivescheme) -replace '.*GUID:\s*([0-9a-f-]+).*', '$1' - if ($act.Trim() -ne $planGuid[$want]) { powercfg /setactive $planGuid[$want] | Out-Null; Log "power $($script:powNow) -> $want (idle=$($s.idle_sec)s modelQuiet=$([math]::Round($quietSec))s cpu=$($s.cpu_total)%)" } - $script:powNow = $want - } - $script:powNow + $pcfg = $null; try { $pcfg = $cfg.power } catch {} + $in = @{ t = (Get-Date); mode = $pm; cpu = $s.cpu_total; idle_sec = $s.idle_sec; quiet_sec = $quietSec; model_busy = [bool]$modelBusy; agent_active = [bool]$agentActive; cfg = $pcfg } + $prev = $script:pow.now + $r = GovPowerDecide $script:pow $in + $script:pow = $r.st + $script:powWhy = $r.why + if ($r.apply) { + $act = [string](Try1 { (powercfg /getactivescheme) -replace '.*GUID:\s*([0-9a-f-]+).*', '$1' } '') + if ($act.Trim() -ne $planGuid[$r.apply]) { + powercfg /setactive $planGuid[$r.apply] | Out-Null + Log "power $prev -> $($r.apply) ($($r.reason); idle=$($s.idle_sec)s modelQuiet=$([math]::Round($quietSec))s cpu=$($s.cpu_total)% agent=$([bool]$agentActive))" + } + } + $script:pow.now } function SetPriority($prof) { - $want = if ($prof -eq 'MAX') { 'Normal' } else { 'BelowNormal' } - Get-Process llama-server -ErrorAction SilentlyContinue | % { try { if ("$($_.PriorityClass)" -ne $want) { $_.PriorityClass = $want } } catch {} } + $want = 'BelowNormal'; if ($prof -eq 'MAX') { $want = 'Normal' } + Get-Process llama-server -ErrorAction SilentlyContinue | ForEach-Object { try { if ("$($_.PriorityClass)" -ne $want) { $_.PriorityClass = $want } } catch {} } } -# ---- main loop ---- -$cfg = Get-Content "$dir\profiles.json" -Raw | ConvertFrom-Json; $A = $cfg.auto +# ============================================================ loop state, self-heal ============================================================ +$cfg = ReadJsonFile "$dir\profiles.json" +if (-not $cfg) { Log 'FATAL: profiles.json unreadable at start'; exit 1 } +$A = $cfg.auto +$script:vramTotalGib = CfgNum $cfg.vram 'total_gib' 23.88 $committed = 'BALANCED'; $candidate = $null; $count = 0 -$lastBusy = Get-Date; $lastTokens = $null; $script:lastReload = (Get-Date).AddHours(-1); $script:lastPrewarm = (Get-Date).AddHours(-1) -$script:lastOthers = 1.5; $swapFails = 0; $lastRestart = (Get-Date).AddHours(-1); $cpuHigh = 0; $script:lastTsStart = (Get-Date).AddHours(-1) +$script:lastBusy = Get-Date; $lastTokens = $null; $script:lastReload = (Get-Date).AddHours(-1); $script:lastPrewarm = (Get-Date).AddHours(-1); $script:lastRefit = (Get-Date).AddHours(-1) +$swapFails = 0; $lastRestart = (Get-Date).AddHours(-1); $cpuHigh = 0; $script:lastTsStart = (Get-Date).AddHours(-1) +$script:needLog = @(); $script:pressureCount = 0; $script:sawActivity = $false; $script:pendingPrewarm = $null +$script:statusDraft = $null; $script:lastDecision = @{ action = 'none'; reason = 'startup' } if (-not (Test-Path "$dir\mode.txt")) { 'AUTO' | Set-Content "$dir\mode.txt" } -Set-Content "$dir\desired.txt" $committed -Log "governor start pid=$PID" +Try1 { Set-Content "$dir\desired.txt" $committed } | Out-Null +Try1 { New-Item -ItemType Directory -Force -Path "$dir\public" | Out-Null } | Out-Null +Log "governor start pid=$([System.Diagnostics.Process]::GetCurrentProcess().Id) v4" +if (-not $script:slotLib) { Log 'slotlib.ps1 not loaded: slot save/restore is off' } +else { try { $script:slots = SlotCfg $cfg; if ($script:slots) { SlotDirReady $script:slots.dir; SlotPrune $script:slots $ids; Log "slots on: dir=$($script:slots.dir) max_files=$($script:slots.max_files) max_gib=$($script:slots.max_gib) min_tokens=$($script:slots.min_tokens)" } else { Log 'slots off (slots.enabled false, or slots.dir / --slot-save-path not wired)' } } catch { Log "slot init error: $($_.Exception.Message)" } } + +# ============================================================ main loop ============================================================ while ($true) { + $sampleOk = $true + $now = Get-Date try { - $cfg = Get-Content "$dir\profiles.json" -Raw | ConvertFrom-Json; $A = $cfg.auto - $mode = Mode; $s = Sense; $m = ModelState; $now = Get-Date - # model is ready but its per-process GPU counter reads ~0: its own VRAM would be booked as 'others' (bogus LEAN + unload). Keep last good value. - if ($m.loaded -and $s.vram_llama_gib -lt 4 -and $s.vram_used_gib -gt 12) { $s.vram_others_gib = $script:lastOthers; $s.vram_llama_gib = [math]::Round($s.vram_used_gib - $script:lastOthers, 2) } elseif ($m.loaded -or $m.state -eq 'stopped') { $script:lastOthers = $s.vram_others_gib } # never learn 'others' while a model is starting (its counter lags) + $c2 = ReadJsonFile "$dir\profiles.json"; if ($c2 -and $c2.auto) { $cfg = $c2; $A = $cfg.auto; $script:vramTotalGib = CfgNum $cfg.vram 'total_gib' $script:vramTotalGib } else { LogEvery 'cfg' 30 'profiles.json unreadable: using the last good configuration' } + $sampleSec = [int](CfgNum $A 'sample_sec' 15); if ($sampleSec -lt 5) { $sampleSec = 5 } + if ($script:slotLib) { ReapWarmJob; $script:slots = Try1 { SlotCfg $cfg } $script:slots } + $mode = Mode + $m = ModelState + $s = Sense $m.loaded ($m.state -eq 'starting') + if ($script:senseWarn.Count) { LogEvery 'sense' 10 ("sense degraded: " + ($script:senseWarn -join '; ')) } else { ClearOnce 'sense' } # --- watchdog for llama-swap --- if ($m.state -eq 'swap-down') { $swapFails++ - if ($swapFails -ge 3 -and ($now - $lastRestart).TotalMinutes -ge 5) { Log "WATCHDOG: llama-swap not responding, restarting task"; Stop-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue; Get-Process llama-swap -ErrorAction SilentlyContinue | Stop-Process -Force; Get-Process llama-server -ErrorAction SilentlyContinue | ? { $_.Path -like 'C:\AI\*' } | Stop-Process -Force; Start-Sleep 3; Start-ScheduledTask -TaskName $task; $lastRestart = $now; $swapFails = 0 } + if ($swapFails -ge 3 -and ($now - $lastRestart).TotalMinutes -ge 5) { Log 'WATCHDOG: llama-swap not responding, restarting task'; Stop-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue; Get-Process llama-swap -ErrorAction SilentlyContinue | Stop-Process -Force; Get-Process llama-server -ErrorAction SilentlyContinue | Where-Object { $_.Path -like 'C:\AI\*' } | Stop-Process -Force; Start-Sleep 3; Start-ScheduledTask -TaskName $task; $lastRestart = $now; $swapFails = 0 } } else { $swapFails = 0 } # --- keep Tailscale's user backend alive (without tailscale-ipn the daemon sits in NoState and remote access dies) --- - if (-not (Get-Process tailscale-ipn -ErrorAction SilentlyContinue) -and (Test-Path 'C:\Program Files\Tailscale\tailscale-ipn.exe') -and ($now - $script:lastTsStart).TotalMinutes -ge 5) { - $script:lastTsStart = $now; Start-Process 'C:\Program Files\Tailscale\tailscale-ipn.exe'; Log 'WATCHDOG: tailscale-ipn was not running - started it' } + if (((ProcIds 'tailscale-ipn').Count -eq 0) -and (Test-Path 'C:\Program Files\Tailscale\tailscale-ipn.exe') -and ($now - $script:lastTsStart).TotalMinutes -ge 5) { + $script:lastTsStart = $now; Try1 { Start-Process 'C:\Program Files\Tailscale\tailscale-ipn.exe' } | Out-Null; Log 'WATCHDOG: tailscale-ipn was not running - started it' } # --- activity of the model --- - if ($m.processing -or ($m.tokens -ne $null -and $lastTokens -ne $null -and $m.tokens -ne $lastTokens) -or $m.state -eq 'starting') { $lastBusy = $now } + $tokMoved = ($null -ne $m.tokens) -and ($null -ne $lastTokens) -and ($m.tokens -ne $lastTokens) + if (($m.processing -eq $true) -or $tokMoved -or $m.state -eq 'starting') { $script:lastBusy = $now; if ($m.processing -eq $true -or $tokMoved) { $script:sawActivity = $true } } $lastTokens = $m.tokens - $quietSec = ($now - $lastBusy).TotalSeconds - # --- live-session tracking (largest prompt seen in the last 60 min) for session-protected resizing --- - if ($m.prompt_tokens -gt 0) { $script:needLog += ,@($now, [int]$m.prompt_tokens) } - $script:needLog = @($script:needLog | ? { ($now - $_[0]).TotalMinutes -le 60 }) - $sessNeed = [int](($script:needLog | % { $_[1] } | measure -Maximum).Maximum) - Set-Content "$dir\session-need.txt" $sessNeed - $power = $null; try { $power = ApplyPower $s $quietSec ($m.processing -or $m.state -eq 'starting') } catch { Log "power error: $($_.Exception.Message)" } - # --- choose profile --- - if ($s.cpu_others -ge $A.others_cpu_lean_pct) { $cpuHigh++ } else { $cpuHigh = 0 } - $pressure = ($s.ram_avail_gb -lt $A.ram_floor_gb) -or ($s.vram_others_gib -gt $A.others_vram_lean_gib) -or ($cpuHigh -ge 8) - if ($mode -ne 'AUTO' -and $mode -ne 'OFF') { $want = $mode } - elseif ($pressure) { $want = 'LEAN' } - elseif ($s.idle_sec -ge $A.idle_for_max_sec -and $s.ram_avail_gb -ge $A.ram_for_max_gb -and $s.vram_others_gib -lt $A.others_vram_max_gib) { $want = 'MAX' } - else { $want = 'BALANCED' } + $quietSec = ($now - $script:lastBusy).TotalSeconds + # --- live-session tracking (largest prompt seen in the last 60 min) for session-protected resizing in launch.ps1 --- + if ($m.prompt_tokens -gt 0) { $script:needLog += ,([pscustomobject]@{ t = $now; n = [int]$m.prompt_tokens }) } + $keep = @(); foreach ($e in @($script:needLog)) { if (($null -ne $e) -and (($now - $e.t).TotalMinutes -le 60)) { $keep += $e } } + $script:needLog = $keep + $sessNeed = 0; foreach ($e in $script:needLog) { if ($e.n -gt $sessNeed) { $sessNeed = [int]$e.n } } + Try1 { Set-Content "$dir\session-need.txt" $sessNeed } | Out-Null + $agent = AgentActive $A $quietSec # needed by the power plan (BALANCED floor) and by the decision below + $power = $null; try { $power = ApplyPower $s $quietSec (($m.processing -eq $true) -or $m.state -eq 'starting') $agent.active } catch { Log "power error: $($_.Exception.Message)" } + # --- choose profile (confirm_samples in a row; invalid readings never push LEAN) --- + if (($null -ne $s.cpu_others) -and ($s.cpu_others -ge (CfgNum $A 'others_cpu_lean_pct' 85))) { $cpuHigh++ } else { $cpuHigh = 0 } + $want = GovProfileChoice $mode $s.idle_sec $s.ram_avail_gb $s.ram_ok $s.vram_others_gib $s.vram_ok $cpuHigh $A if ($want -eq $candidate) { $count++ } else { $candidate = $want; $count = 1 } - if ($want -ne $committed -and ($count -ge $A.confirm_samples -or $mode -ne 'AUTO')) { Log "profile $committed -> $want (idle=$($s.idle_sec)s ram=$($s.ram_avail_gb)GB othersVRAM=$($s.vram_others_gib)GiB cpuOthers=$($s.cpu_others)%)"; $committed = $want; Set-Content "$dir\desired.txt" $committed } - $loadedProf = if ($m.loaded) { LoadedProfile } else { $null } - if ($m.loaded) { SetPriority $committed } - # --- actions (never while busy) --- - $sinceReload = ($now - $script:lastReload).TotalMinutes - if ($mode -eq 'OFF') { - if ($m.loaded -and -not $m.processing -and $quietSec -ge 30) { Unload 'mode OFF' } - } elseif ($m.loaded -and -not $m.processing) { - $acute = ($s.vram_free_gib -lt $A.vram_free_pressure_gib) -or ($s.ram_avail_gb -lt $A.ram_floor_gb) -or ($s.vram_others_gib -gt $A.others_vram_lean_gib) - $idleLimit = $cfg.profiles.$committed.idle_unload_min - if ($acute -and $quietSec -ge 30) { - if ($committed -eq 'LEAN') { Unload "pressure, LEAN" } - elseif ($sinceReload -ge 3 -and $script:curId -ne 'qwen3.8-27b-long' -and -not (LoadedEmergency)) { Unload "free VRAM $($s.vram_free_gib) GiB < $($A.vram_free_pressure_gib) -> re-fit context ($committed)"; Prewarm "re-fit as $committed" } + if ($want -ne $committed -and ($count -ge (CfgNum $A 'confirm_samples' 4) -or $mode -ne 'AUTO')) { + Log "profile $committed -> $want (idle=$($s.idle_sec)s ram=$($s.ram_avail_gb)GB othersVRAM=$($s.vram_others_gib)GiB cpuOthers=$($s.cpu_others)%)"; $committed = $want; Try1 { Set-Content "$dir\desired.txt" $committed } | Out-Null } + $loadedProf = $null; if ($m.loaded) { $loadedProf = LoadedProfile; SetPriority $committed } + # --- post-launch baseline and footprint calibration --- + $started = $null; try { $rj = ReadJsonFile "$dir\running.json"; if ($rj -and $rj.started) { $started = [string]$rj.started } } catch {} + if (-not $m.loaded) { $script:baseline = $null; $script:baseStable = 0 } + elseif ($script:baseline -and ($script:baseStarted -ne $started)) { $script:baseline = $null; $script:baseStable = 0 } # a new server: new baseline + if ($m.loaded -and -not $script:baseline) { + $br = GovBaselineReady $m.loaded $s.vram_ok $s.llama_measured $m.n_ctx $script:baseStable + $script:baseStable = $br.count + if ($br.take) { + $script:baseline = [ordered]@{ others = $s.vram_others_gib; free = $s.vram_free_gib; used = $s.vram_used_gib; llama = $s.vram_llama_gib; ctx = [int]$m.n_ctx; id = $script:curId; t = $now.ToString('s') } + $script:baseStarted = $started + $vv = VariantOf $script:curId; $cal = $null + if ($vv -and (GovIsNum $vv.base_gib) -and (GovIsNum $vv.kv_kib_per_token)) { + $cc = $cfg.calibration; $alpha = CfgNum $cc 'alpha' 0.5; $maxO = CfgNum $cc 'max_overhead_gib' 1.5 + $prev = $null; $pe = CalibEntry $script:curId; if ($pe) { $prev = Try1 { [double]$pe.overhead_gib } $null } + $cal = GovCalibrate $prev $s.vram_llama_gib $vv.base_gib $m.n_ctx $vv.kv_kib_per_token $alpha $maxO + $n = 1; if ($pe) { $n = (Try1 { [int]$pe.samples } 0) + 1 } + CalibWrite $script:curId ([ordered]@{ overhead_gib = $cal.overhead; last_delta_gib = $cal.delta; predicted_gib = $cal.predicted; measured_gib = $s.vram_llama_gib; ctx = [int]$m.n_ctx; others_gib = $s.vram_others_gib; free_gib = $s.vram_free_gib; samples = $n; updated = $now.ToString('s') }) + } + $calTxt = ''; if ($cal) { $calTxt = (' predicted={0} measured={1} delta={2:+0.00;-0.00} overhead->{3}' -f $cal.predicted, $s.vram_llama_gib, $cal.delta, $cal.overhead) } + Log ("BASELINE ctx={0} others={1} free={2} llama={3}{4}" -f $m.n_ctx, $s.vram_others_gib, $s.vram_free_gib, $s.vram_llama_gib, $calTxt) + # a re-fit that landed on the same ctx as before: block re-fits until others changes + if ($script:refitPrevCtx) { $script:refitBlocked = GovRefitRepeatBlocked $script:refitPrevCtx $m.n_ctx $s.vram_others_gib $script:refitOthers (CfgNum $A 'others_growth_gib' 0.5); if ($script:refitBlocked) { Log "re-fit landed on ctx $($m.n_ctx) again (was $($script:refitPrevCtx)); further re-fits wait for others to change" }; $script:refitPrevCtx = $null } } - elseif ($idleLimit -gt 0 -and $quietSec -ge $idleLimit * 60) { Unload "idle $([math]::Round($quietSec/60)) min in $committed" } - elseif ($loadedProf -eq 'LEAN' -and $committed -ne 'LEAN' -and $quietSec -ge $A.model_quiet_sec_before_reload -and $sinceReload -ge 10) { Unload "upgrade LEAN -> $committed"; Prewarm "upgrade to $committed" } - elseif ($loadedProf -eq 'BALANCED' -and $committed -eq 'MAX' -and $quietSec -ge $A.max_upgrade_quiet_min * 60 -and $sinceReload -ge 10) { Unload "upgrade BALANCED -> MAX"; Prewarm "upgrade to MAX" } - } elseif (-not $m.loaded -and $m.state -eq 'stopped' -and $committed -eq 'MAX' -and -not $m.other_running -and ($now - $script:lastPrewarm).TotalMinutes -ge $A.prewarm_cooldown_min) { - $script:curId = $model; $script:curPort = $ports[$model]; Prewarm 'PC idle - keep model warm in MAX' } - # --- status for humans / remote --- + if ($script:refitBlocked -and (GovIsNum $s.vram_others_gib) -and (GovIsNum $script:refitOthers) -and ([math]::Abs($s.vram_others_gib - $script:refitOthers) -ge (CfgNum $A 'others_growth_gib' 0.5))) { $script:refitBlocked = $false; Log 'others changed since the repeated re-fit: re-fits allowed again' } + # --- pressure with hysteresis (relative to the baseline) --- + $freeThr = CfgNum $A 'vram_free_pressure_gib' 1.1; $ramCrit = CfgNum $A 'ram_critical_gb' 1.5; $growth = CfgNum $A 'others_growth_gib' 0.5; $hardFloor = CfgNum $A 'vram_free_hard_floor_gib' 0.25 + $bOthers = $null; if ($script:baseline) { $bOthers = $script:baseline.others } + if ($m.loaded) { $script:pressureCount = GovPressureStep $script:pressureCount $s.vram_free_gib $s.ram_avail_gb $s.vram_ok $s.ram_ok $freeThr $ramCrit $s.vram_others_gib $bOthers $growth $hardFloor } else { $script:pressureCount = 0 } + # --- a prewarm that could not start is retried (max 5 samples) unless the model is back already --- + if ($script:pendingPrewarm) { + if ($m.loaded -or $m.state -eq 'starting' -or $script:pendingPrewarm.tries -ge 5) { $script:pendingPrewarm = $null } + elseif ((ProcIds 'llama-server').Count -eq 0) { $script:pendingPrewarm.tries++; Prewarm $script:pendingPrewarm.why; if ($script:prewarmOk) { $script:pendingPrewarm = $null } } + } + # --- decide and act (never while busy) --- + $din = @{ mode = $mode; loaded = $m.loaded; state = $m.state; in_flight = $m.processing; quiet_sec = $quietSec + pressure_count = $script:pressureCount; sample_sec = $sampleSec; persist_sec = (CfgNum $A 'pressure_persist_sec' 60) + committed = $committed; loaded_profile = $loadedProf; idle_unload_min = (CfgNum $cfg.profiles.$committed 'idle_unload_min' 0) + since_refit_min = ($now - $script:lastRefit).TotalMinutes; refit_interval_min = (CfgNum $A 'refit_min_interval_min' 15) + since_prewarm_min = ($now - $script:lastPrewarm).TotalMinutes; prewarm_cooldown_min = (CfgNum $A 'prewarm_cooldown_min' 10) + cur_id = $script:curId; emergency = $(if ($m.loaded) { LoadedEmergency } else { $false }); agent_active = $agent.active; other_running = $m.other_running + free_gib = $s.vram_free_gib; ram_gb = $s.ram_avail_gb; free_threshold = $freeThr; ram_critical = $ramCrit + others_gib = $s.vram_others_gib; baseline_others = $bOthers; hard_floor = $hardFloor; refit_blocked = $script:refitBlocked + quiet_before_reload_sec = (CfgNum $A 'model_quiet_sec_before_reload' 120); max_upgrade_quiet_min = (CfgNum $A 'max_upgrade_quiet_min' 20) } + $d = GovDecide $din + $script:lastDecision = $d + switch ($d.action) { + 'unload' { Unload $d.reason } + 'idle-unload' { Unload $d.reason } + 'refit' { $script:refitPrevCtx = $m.n_ctx; $script:refitOthers = $s.vram_others_gib; UnloadThenPrewarm $d.reason "re-fit as $committed" } + 'upgrade' { UnloadThenPrewarm $d.reason "upgrade to $committed" } + 'prewarm' { $script:curId = $model; $script:curPort = $ports[$model]; Prewarm $d.reason } + default { if ($d.reason -like 'pressure persists*') { LogEvery 'ratelimit' 5 $d.reason } elseif ($d.reason -like 'pressure but protected*') { LogEvery 'protected' 15 $d.reason } } + } + # --- status draft (completed and written below, even when something above failed) --- $status = [ordered]@{ time = $now.ToString('s'); mode = $mode; profile = $committed; loaded = $m.loaded; loaded_profile = $loadedProf; state = $m.state - processing = $m.processing; n_ctx = $m.n_ctx; model_quiet_min = [math]::Round($quietSec / 60, 1); other_model = $m.other_running } + processing = $m.processing; n_ctx = $m.n_ctx; model_quiet_min = [math]::Round($quietSec / 60, 1); other_model = $m.other_running } foreach ($k in $s.Keys) { $status[$k] = $s[$k] } # expected context if the default model were (re)loaded now with the current profile - try { $vd = $cfg.variants.default; $pp = $cfg.profiles.$committed; $oth = if ($m.loaded) { $s.vram_others_gib } else { $s.vram_used_gib } - $ec = [int]([math]::Floor((($cfg.vram.total_gib - $pp.free_margin_gib - $oth - $vd.base_gib) * 1MB) / $vd.kv_kib_per_token / 4096) * 4096) - $status['expected_ctx'] = [math]::Max([int]$pp.ctx_min, [math]::Min([int]$vd.ctx_max, $ec)) } catch {} + try { $vd = $cfg.variants.default; $pp = $cfg.profiles.$committed; $oth = $s.vram_others_gib; if (-not $m.loaded -and ($null -ne $s.vram_used_gib) -and ($s.llama_pids -eq 0)) { $oth = $s.vram_used_gib } + $oh = GovLaunchOverhead (CalibEntry $vd.id) (CfgBool $cfg.calibration 'enabled' $true) (CfgNum $cfg.calibration 'max_overhead_gib' 1.5) + if ($null -ne $oth) { $status['expected_ctx'] = GovFitCtx $script:vramTotalGib (CfgNum $pp 'free_margin_gib' 1.5) $oth (CfgNum $vd 'base_gib' 17.15) (CfgNum $vd 'kv_kib_per_token' 64.5) (CfgNum $pp 'ctx_min' 32768) (CfgNum $vd 'ctx_max' 65536) $oh; $status['calib_overhead_gib'] = $oh } } catch {} $status['model_id'] = $script:curId - $status['power_plan'] = $power; $status['power_mode'] = PowerMode; $status['session_need_tokens'] = $sessNeed - $status | ConvertTo-Json | Set-Content "$dir\public\status.json.tmp"; try { Move-Item "$dir\public\status.json.tmp" "$dir\public\status.json" -Force } catch {} - } catch { Log "loop error: $($_.Exception.Message)" } - Start-Sleep -Seconds ([int]$A.sample_sec) + $status['power_plan'] = $power; $status['power_mode'] = PowerMode; $status['power_reason'] = $script:powWhy; $status['session_need_tokens'] = $sessNeed + $status['pressure_count'] = $script:pressureCount; $status['pressure_sec'] = $script:pressureCount * $sampleSec + $status['agent_active'] = $agent.active; $status['agent_procs'] = @($agent.procs); $status['decision'] = $d.action; $status['decision_reason'] = $d.reason + $status['since_refit_min'] = [math]::Round(($now - $script:lastRefit).TotalMinutes, 1); $status['slots_on'] = [bool]$script:slots + $status['baseline'] = $script:baseline; $status['refit_blocked'] = $script:refitBlocked + $status['sense_warnings'] = @($script:senseWarn) + $script:statusDraft = $status + } catch { $sampleOk = $false; NoteLoopError $_ } + # --- status.json is written on every sample, degraded or not --- + try { + $st = $script:statusDraft + if ($null -eq $st) { $st = [ordered]@{ time = $now.ToString('s'); mode = (Mode); profile = $committed; loaded = $null; state = 'unknown' } } + else { $st['time'] = $now.ToString('s') } + $degraded = (-not $sampleOk) -or ($script:errStreak -gt 0) -or ($script:senseWarn.Count -gt 0) + $st['degraded'] = $degraded + $st['last_error'] = $script:lastError + $st['last_error_time'] = $(if ($script:lastErrorAt) { $script:lastErrorAt.ToString('s') } else { $null }) + $st['loop_errors'] = $script:errTotal; $st['loop_error_streak'] = $script:errStreak; $st['self_heals'] = $script:heals + $st['sample_ok'] = $sampleOk + $tmp = "$dir\public\status.json.tmp" + WriteText $tmp ($st | ConvertTo-Json -Depth 5) + Move-Item -LiteralPath $tmp -Destination "$dir\public\status.json" -Force + } catch { Log "status write error: $($_.Exception.Message)" } + if ($sampleOk -and $script:errStreak -gt 0) { Log "loop recovered after $($script:errStreak) error sample(s)"; $script:errStreak = 0 } + $sl = 15; try { $sl = [int](CfgNum $A 'sample_sec' 15); if ($sl -lt 5) { $sl = 5 } } catch {} + if ($env:GOV_MAX_LOOPS) { $script:loops++; if ($script:loops -ge [int]$env:GOV_MAX_LOOPS) { break } } # test harness only + Start-Sleep -Seconds $sl } - - diff --git a/governor/govpolicy.py b/governor/govpolicy.py new file mode 100644 index 0000000..1e791c4 --- /dev/null +++ b/governor/govpolicy.py @@ -0,0 +1,298 @@ +"""Pure decision logic of the Qwen governor (no I/O). Mirrored one to one by the Gov* functions +in governor.ps1 (and the others/ctx formulas in launch.ps1). Change a rule in both places. + +Units: GiB for VRAM, GB for RAM, seconds/minutes as named. All inputs may be None (= "the read +failed"); every function has a defined answer for that, because one failed PDH sample must never +kill the loop or poison the state. +""" + +# A loaded 27B Q4_K_M (17.15 GiB base) can never show less than this on the adapter or on its own process. +LOADED_MIN_ADAPTER_GIB = 8.0 +LOADED_MIN_LLAMA_GIB = 4.0 +# 'others' may not jump by more than this between two samples (15 s) without being confirmed first. +OTHERS_JUMP_GIB = 4.0 +OTHERS_CONFIRM_SAMPLES = 4 +# Everything that is not llama-server: desktop (dwm ~2.7 GiB on this PC), Chrome, Open WebUI, MCP processes. +OTHERS_PLAUSIBLE_MAX_GIB = 8.0 +PROFILES = ("MAX", "BALANCED", "LEAN") + + +def _num(v): + return isinstance(v, (int, float)) and not isinstance(v, bool) + + +def clamp(v, lo, hi): + return lo if v < lo else hi if v > hi else v + + +def validate_vram(adapter_gib, llama_gib, total_gib, loaded, llama_alive, last_good, suspect_count, starting=False): + """Turn the two PDH readings into trusted numbers. + + adapter_gib : max over '\\GPU Adapter Memory(*)\\Dedicated Usage' instances (None = read failed) + llama_gib : sum of '\\GPU Process Memory(pid_*)\\Dedicated Usage' (None = failed / no process) + total_gib : profiles.json vram.total_gib + loaded : llama-swap says the governed model is 'ready' + llama_alive : a llama-server process exists + starting : llama-swap says the model is 'starting' (its counters lag: never learn 'others' now) + last_good : previous trusted dict or None + suspect_count: consecutive samples in which 'others' jumped (confirmation counter) + + Returns (metrics, suspect_count). metrics = {used, free, llama, others, ok, warn}. + ok=False means "do not act on these numbers this sample" (they are last-good or absent). + """ + warn = [] + lg = last_good or {} + adapter_ok = _num(adapter_gib) and 0.0 <= adapter_gib <= total_gib * 1.05 + if not adapter_ok: + warn.append("adapter counter invalid (%r)" % (adapter_gib,)) + elif loaded and adapter_gib < LOADED_MIN_ADAPTER_GIB: + adapter_ok = False + warn.append("adapter counter reads %.2f GiB while the model is loaded (impossible)" % adapter_gib) + + if not adapter_ok: + # keep the last good picture, flag it, do not act + if lg: + m = dict(lg) + m["ok"] = False + m["warn"] = warn + return m, suspect_count + return {"used": None, "free": None, "llama": None, "others": None, "ok": False, "warn": warn}, suspect_count + + used = adapter_gib + free = clamp(total_gib - used, 0.0, total_gib) + + llama_ok = _num(llama_gib) and 0.0 <= llama_gib <= used + 0.5 + if llama_ok and loaded and llama_gib < LOADED_MIN_LLAMA_GIB: + llama_ok = False + warn.append("process counter reads %.2f GiB for a loaded model (lagging)" % llama_gib) + if not llama_ok and llama_gib is not None and _num(llama_gib) and not loaded: + # not loaded: a small/zero per-process value is fine (starting or exiting server) + llama_ok = True + + if llama_ok: + llama = clamp(llama_gib, 0.0, used) + elif loaded and _num(lg.get("others")): + # trust the last good 'others' and attribute the rest to the model + llama = clamp(used - lg["others"], 0.0, used) + elif loaded: + llama = used # first sample ever and the process counter is wrong: assume nothing else is there + else: + llama = 0.0 + if not llama_alive and not loaded: + llama = 0.0 + + others = clamp(used - llama, 0.0, total_gib) + ok = True + if starting: + warn.append("model starting: keeping last good others") + others = lg["others"] if _num(lg.get("others")) else None + if others is not None: + llama = clamp(used - others, 0.0, used) + return {"used": round(used, 2), "free": round(free, 2), "llama": round(llama, 2), + "others": None if others is None else round(others, 2), "ok": False, "warn": warn}, suspect_count + # jump guard: a sudden change in others while a model is (un)loading is almost always a counter lag + if _num(lg.get("others")) and abs(others - lg["others"]) > OTHERS_JUMP_GIB: + suspect_count += 1 + if suspect_count < OTHERS_CONFIRM_SAMPLES: + warn.append("others jumped %.2f -> %.2f GiB; keeping last good until confirmed (%d/%d)" + % (lg["others"], others, suspect_count, OTHERS_CONFIRM_SAMPLES)) + others = lg["others"] + llama = clamp(used - others, 0.0, used) + ok = False + else: + warn.append("others change confirmed after %d samples" % suspect_count) + suspect_count = 0 + else: + suspect_count = 0 + if others > OTHERS_PLAUSIBLE_MAX_GIB and not loaded and llama_alive: + # a dying/starting llama-server still holds VRAM: that is not 'others' + warn.append("others %.2f GiB with a llama-server alive but not ready: ignoring" % others) + others = lg["others"] if _num(lg.get("others")) else None + ok = False + return {"used": round(used, 2), "free": round(free, 2), "llama": round(llama, 2), + "others": None if others is None else round(others, 2), "ok": ok, "warn": warn}, suspect_count + + +def validate_ram(ram_gb, last_good_gb): + """Available RAM in GB. 0 or an absurd value is a failed PDH sample, not an empty machine.""" + if _num(ram_gb) and 0.05 <= ram_gb <= 2048.0: + return ram_gb, True + return last_good_gb, False + + +def pressure_step(count, free_gib, ram_gb, vram_ok, ram_ok, free_threshold, ram_critical, + others_gib=None, baseline_others=None, growth_min=0.5, hard_floor=0.25): + """Consecutive-sample counter of REAL pressure. Invalid samples never add to it (they reset it: + a reading we cannot trust is no evidence of pressure). + + A re-fit must mean OTHER apps grew: low free VRAM alone is the model's own steady state after a tight fit + (2026-10-16: ctx 40960 left 0.65 GiB free and v4.0 re-fitted onto the same footprint). So free < threshold + counts only when others has grown >= growth_min since the post-launch baseline; without a baseline it does + not count at all. free < hard_floor (0.25) always counts, as does RAM < ram_critical.""" + now = False + if vram_ok and _num(free_gib): + if free_gib < hard_floor: + now = True + elif free_gib < free_threshold and _num(others_gib) and _num(baseline_others) \ + and (others_gib - baseline_others) >= growth_min: + now = True + if ram_ok and _num(ram_gb) and ram_gb < ram_critical: + now = True + return count + 1 if now else 0 + + +def pressure_reason(free_gib, ram_gb, free_threshold, ram_critical, others_gib=None, baseline_others=None, hard_floor=0.25): + parts = [] + if _num(free_gib) and free_gib < hard_floor: + parts.append("free VRAM %.2f GiB < hard floor %.2f" % (free_gib, hard_floor)) + elif _num(free_gib) and free_gib < free_threshold: + if _num(others_gib) and _num(baseline_others): + parts.append("free VRAM %.2f GiB < %.2f with others %+.2f GiB since baseline %.2f" + % (free_gib, free_threshold, others_gib - baseline_others, baseline_others)) + else: + parts.append("free VRAM %.2f GiB < %.2f" % (free_gib, free_threshold)) + if _num(ram_gb) and ram_gb < ram_critical: + parts.append("RAM %.2f GB < %.2f" % (ram_gb, ram_critical)) + return ", ".join(parts) or "no pressure" + + +def baseline_ready(loaded, vram_ok, llama_measured, n_ctx, stable_count, need=2): + """After a launch the counters settle for a few samples. Take the baseline on the `need`-th consecutive + sample that is loaded, has valid VRAM numbers, a directly measured llama share and a known n_ctx. + Returns (new_stable_count, take_now).""" + if loaded and vram_ok and llama_measured and _num(n_ctx) and n_ctx > 0: + stable_count += 1 + return stable_count, stable_count >= need + return 0, False + + +def predicted_llama_gib(base_gib, ctx, kv_kib_per_token, overhead_gib=0.0): + return base_gib + overhead_gib + ctx * kv_kib_per_token / 1048576.0 + + +def calibrate(prev_overhead, llama_actual_gib, base_gib, ctx, kv_kib_per_token, alpha=0.5, max_overhead=1.5, min_overhead=-0.5): + """Learn the footprint launch.ps1's model misses (drafter KV, mmproj, compute buffers). Returns + (overhead_gib, predicted_gib, delta_gib). overhead is an EMA of the measured delta, clamped.""" + predicted = base_gib + ctx * kv_kib_per_token / 1048576.0 + delta = clamp(llama_actual_gib - predicted, min_overhead, max_overhead) + if _num(prev_overhead): + new = prev_overhead + alpha * (delta - prev_overhead) + else: + new = delta + return round(new, 2), round(predicted, 2), round(llama_actual_gib - predicted, 2) + + +def launch_overhead(calib_entry, enabled=True, max_overhead=1.5): + """What launch.ps1 adds to base_gib: the learned overhead, never negative (an under-estimate shrinks ctx, + an over-estimate would spill into shared memory).""" + if not enabled or not isinstance(calib_entry, dict): + return 0.0 + v = calib_entry.get("overhead_gib") + if not _num(v): + return 0.0 + return round(clamp(v, 0.0, max_overhead), 2) + + +def refit_repeat_blocked(prev_ctx, new_ctx, others_now, others_at_refit, growth_min=0.5, step=4096): + """After a re-fit that landed on the same ctx (+- one step) as before, block further re-fits until + others has changed by >= growth_min since that re-fit.""" + if not (_num(prev_ctx) and _num(new_ctx)) or abs(new_ctx - prev_ctx) > step: + return False + if _num(others_now) and _num(others_at_refit) and abs(others_now - others_at_refit) >= growth_min: + return False + return True + + +def profile_choice(mode, idle_sec, ram_gb, ram_ok, others_gib, others_ok, cpu_high_count, a): + """Which profile AUTO wants this sample. a = profiles.json 'auto'. Invalid readings never push LEAN.""" + if mode not in ("AUTO", "OFF"): + return mode + pressure = (ram_ok and _num(ram_gb) and ram_gb < a["ram_floor_gb"]) or \ + (others_ok and _num(others_gib) and others_gib > a["others_vram_lean_gib"]) or \ + (cpu_high_count >= 8) + if pressure: + return "LEAN" + if idle_sec >= a["idle_for_max_sec"] and ram_ok and _num(ram_gb) and ram_gb >= a["ram_for_max_gb"] \ + and others_ok and _num(others_gib) and others_gib < a["others_vram_max_gib"]: + return "MAX" + return "BALANCED" + + +def decide(s): + """One sample's action. s is a dict with: + mode, loaded, state ('ready'|'starting'|'stopped'|'stopping'|'swap-down'|'api-error'), + in_flight (True|False|None=unknown), quiet_sec, pressure_count, sample_sec, persist_sec, + committed, loaded_profile, idle_unload_min, since_refit_min, refit_interval_min, + since_prewarm_min, prewarm_cooldown_min, cur_id, emergency, agent_active, other_running, + free_gib, ram_gb, free_threshold, ram_critical, quiet_before_reload_sec, max_upgrade_quiet_min + Returns (action, reason). action in: none, unload, refit, upgrade, idle-unload, prewarm. + """ + if s["mode"] == "OFF": + if s["loaded"] and s["in_flight"] is False and s["quiet_sec"] >= 30: + return "unload", "mode OFF" + return "none", "mode OFF" + if s["loaded"]: + if s["in_flight"] is not False: + return "none", "request in flight" if s["in_flight"] else "slot state unknown" + persistent = s["pressure_count"] * s["sample_sec"] >= s["persist_sec"] and s["pressure_count"] > 0 + if persistent and s["quiet_sec"] >= 30: + why = pressure_reason(s["free_gib"], s["ram_gb"], s["free_threshold"], s["ram_critical"], + s.get("others_gib"), s.get("baseline_others"), s.get("hard_floor", 0.25)) + if s["committed"] == "LEAN": + return "unload", "pressure, LEAN (%s)" % why + if s["cur_id"] == "qwen3.8-27b-long" or s["emergency"]: + return "none", "pressure but protected (%s)" % why + if s.get("refit_blocked"): + return "none", "pressure but a re-fit would repeat the same ctx; waiting for others to change (%s)" % why + if s["since_refit_min"] >= s["refit_interval_min"]: + return "refit", "%s for %ds -> re-fit context (%s)" % (why, s["pressure_count"] * s["sample_sec"], s["committed"]) + return "none", "pressure persists but re-fit rate-limited (%.0f/%d min)" % (s["since_refit_min"], s["refit_interval_min"]) + if s["idle_unload_min"] > 0 and s["quiet_sec"] >= s["idle_unload_min"] * 60: + if s["agent_active"]: + return "none", "idle but an agent client is active: stay warm" + return "idle-unload", "idle %d min in %s" % (round(s["quiet_sec"] / 60), s["committed"]) + if s["loaded_profile"] == "LEAN" and s["committed"] != "LEAN" \ + and s["quiet_sec"] >= s["quiet_before_reload_sec"] and s["since_refit_min"] >= s["refit_interval_min"]: + return "upgrade", "upgrade LEAN -> %s" % s["committed"] + if s["loaded_profile"] == "BALANCED" and s["committed"] == "MAX" \ + and s["quiet_sec"] >= s["max_upgrade_quiet_min"] * 60 and s["since_refit_min"] >= s["refit_interval_min"]: + return "upgrade", "upgrade BALANCED -> MAX" + return "none", "steady" + # not loaded + if s["state"] == "stopped" and not s["other_running"] and s["since_prewarm_min"] >= s["prewarm_cooldown_min"]: + if s["committed"] == "MAX": + return "prewarm", "PC idle - keep model warm in MAX" + if s["agent_active"] and s["committed"] != "LEAN": + return "prewarm", "agent client active - keep model warm" + return "none", "not loaded (%s)" % s["state"] + + +# ---------------- launch.ps1 formulas ---------------- +def fit_ctx(total_gib, margin_gib, others_gib, base_gib, kv_kib_per_token, ctx_min, ctx_max, overhead_gib=0.0): + """Context that fits: (total - margin - others - base - learned overhead) GiB of KV, rounded down to 4096, clamped.""" + kib = (total_gib - margin_gib - others_gib - base_gib - overhead_gib) * 1048576.0 + ctx = int(kib / kv_kib_per_token / 4096) * 4096 if kib > 0 else 0 + return max(int(ctx_min), min(int(ctx_max), ctx)) + + +def launch_others(samples, llama_alive, status_others, status_age_sec, default_gib=2.2): + """What launch.ps1 should book as 'others' before sizing the context. + samples: adapter 'Dedicated Usage' readings in GiB taken ~1 s apart after the old server exited. + Returns (others_gib, note).""" + vals = [v for v in (samples or []) if _num(v) and 0.0 <= v <= 64.0] + fresh = _num(status_others) and _num(status_age_sec) and status_age_sec <= 120 and 0.0 <= status_others <= OTHERS_PLAUSIBLE_MAX_GIB + if not vals: + if fresh: + return round(status_others, 2), "adapter counter failed; using governor's others" + return default_gib, "adapter counter failed; default" + meas = min(vals) # VRAM is still being released; the smallest sample is the closest to the truth + if llama_alive: + # the previous server did not exit in time: its VRAM is in the measurement + if fresh: + return round(status_others, 2), "old llama-server still alive (measured %.2f); using governor's others" % meas + return default_gib, "old llama-server still alive (measured %.2f); default" % meas + if meas > OTHERS_PLAUSIBLE_MAX_GIB: + if fresh: + return round(status_others, 2), "measured %.2f GiB implausible; using governor's others" % meas + return round(meas, 2), "measured %.2f GiB implausible but no better source" % meas + return round(meas, 2), "measured" diff --git a/governor/launch.ps1 b/governor/launch.ps1 index ff777d4..3b33b8a 100644 --- a/governor/launch.ps1 +++ b/governor/launch.ps1 @@ -2,7 +2,11 @@ # Context is sized at load time from the VRAM actually free right now, keeping the profile's # "free VRAM" margin for Windows/apps, and never spilling into shared memory (measured limits). # llama-swap stops it with "taskkill /f /t", which also kills the llama-server child. -param([string]$Variant = 'default') +# v4 (2026-10-15): 'others' is measured only after the previous llama-server is really gone (up to 45 s), as the +# minimum of three samples, and cross-checked against the governor's last good value (status.json). The old code +# measured once after a 15 s wait and once booked a dying server's 21.24 GiB as "others" (ctx 32768 at 08:04 on 10-11). +# The others/ctx formulas mirror govpolicy.launch_others / fit_ctx (test_govpolicy.py). +param([string]$Variant = 'default', [switch]$DryRun) # -DryRun: print the decision and the command line, start nothing $ErrorActionPreference = 'Stop' $dir = 'C:\AI\governor' $cfg = Get-Content "$dir\profiles.json" -Raw | ConvertFrom-Json @@ -10,15 +14,56 @@ $v = $cfg.variants.$Variant; if (-not $v) { $Variant = 'default'; $v = $cfg.vari $name = 'BALANCED' try { $d = (Get-Content "$dir\desired.txt" -ErrorAction Stop).Trim().ToUpper(); if ($cfg.profiles.PSObject.Properties.Name -contains $d) { $name = $d } } catch {} $p = $cfg.profiles.$name +$OTHERS_PLAUSIBLE_MAX_GIB = 8.0 +function LaunchLog($m) { try { "$(Get-Date -f s) $m" | Add-Content "$dir\governor.log" } catch {} } -# Wait (max 15 s) for any previous llama-server to release VRAM, then measure what everything else uses. -for ($i = 0; $i -lt 15 -and (Get-Process llama-server -ErrorAction SilentlyContinue | ? { $_.Path -like 'C:\AI\*' }); $i++) { Start-Sleep 1 } -$others = ((Get-Counter '\GPU Adapter Memory(*)\Dedicated Usage' -ErrorAction SilentlyContinue).CounterSamples | measure CookedValue -Sum).Sum / 1GB -if (-not $others -or $others -le 0) { $others = 2.2 } +# ---- 1) wait (max 45 s) for any previous llama-server to exit; its VRAM must not be booked as 'others' ---- +$waited = 0 +# v4.3 (2026-10-17): only OUR llama-server counts. Ollama's runner is also named llama-server.exe (C:\Apps\Ollama\lib\ollama\), +# and on 17 Oct it kept llama3.2:3b (3.07 GiB) resident for 24 h: the old code waited 45 s for it, then booked others=default. +function OurServers { @(Get-Process llama-server -ErrorAction SilentlyContinue | Where-Object { $_.Path -like 'C:\AI\llama.cpp\*' }) } +while ($waited -lt 45 -and (OurServers).Count -gt 0) { Start-Sleep 1; $waited++ } +$stillAlive = ((OurServers).Count -gt 0) +if ($waited -gt 0) { Start-Sleep 2 } # let the driver release the heap before measuring -# Context sizing +# ---- 2) measure adapter 'Dedicated Usage' three times (max over adapters per sample), keep the smallest ---- +$samples = @() +for ($i = 0; $i -lt 3; $i++) { + try { + $cs = (Get-Counter '\GPU Adapter Memory(*)\Dedicated Usage' -ErrorAction SilentlyContinue).CounterSamples + $mx = $null + foreach ($x in @($cs)) { if ($null -ne $x -and $x.Status -eq 0) { $g = [double]$x.CookedValue / 1GB; if (($null -eq $mx) -or ($g -gt $mx)) { $mx = $g } } } + if ($null -ne $mx) { $samples += $mx } + } catch {} + if ($i -lt 2) { Start-Sleep 1 } +} +# the governor's last good 'others' (status.json), if fresh +$stOthers = $null; $stAge = $null +try { + $st = Get-Content "$dir\public\status.json" -Raw -ErrorAction Stop | ConvertFrom-Json + $stAge = ((Get-Date) - [datetime]$st.time).TotalSeconds + if ($st.vram_ok -eq $true -and $null -ne $st.vram_others_gib) { $stOthers = [double]$st.vram_others_gib } +} catch {} +$fresh = ($null -ne $stOthers) -and ($null -ne $stAge) -and ($stAge -le 120) -and ($stOthers -ge 0) -and ($stOthers -le $OTHERS_PLAUSIBLE_MAX_GIB) +$others = 2.2; $othersNote = 'default' +if ($samples.Count -eq 0) { + if ($fresh) { $others = $stOthers; $othersNote = "adapter counter failed; using governor's others" } else { $othersNote = 'adapter counter failed; default' } +} else { + $meas = ($samples | Measure-Object -Minimum).Minimum + if ($stillAlive) { + if ($fresh) { $others = $stOthers; $othersNote = ('old llama-server still alive (measured {0:F2}); using governor''s others' -f $meas) } + else { $othersNote = ('old llama-server still alive (measured {0:F2}); default' -f $meas) } + } elseif ($meas -gt $OTHERS_PLAUSIBLE_MAX_GIB) { + if ($fresh) { $others = $stOthers; $othersNote = ('measured {0:F2} GiB implausible; using governor''s others' -f $meas) } + else { $others = $meas; $othersNote = ('measured {0:F2} GiB implausible but no better source' -f $meas) } + } else { $others = $meas; $othersNote = 'measured' } +} +$others = [math]::Round([double]$others, 2) + +# ---- 3) context sizing ---- $ctk = $v.ctk; $ctv = $v.ctv $extra = @($v.extra_args) +$draftNote = ''; $overhead = 0.0 if ($v.fixed_ctx) { $ctx = [int]$v.fixed_ctx # Optional drafter (e.g. MTP for the 262k LONG model) only if enough VRAM stays free after it loads @@ -29,27 +74,42 @@ if ($v.fixed_ctx) { } else { $kvKiB = $v.kv_kib_per_token + # learned footprint the base_gib/kv model misses (governor writes calib.json at each post-launch baseline); never negative + $overhead = 0.0; $calEnabled = $true; try { if ($cfg.calibration.enabled -is [bool]) { $calEnabled = $cfg.calibration.enabled } } catch {} + $maxOver = 1.5; try { if ($cfg.calibration.max_overhead_gib) { $maxOver = [double]$cfg.calibration.max_overhead_gib } } catch {} + if ($calEnabled) { try { $cal = Get-Content "$dir\calib.json" -Raw -ErrorAction Stop | ConvertFrom-Json; $ce = $cal.PSObject.Properties[$v.id] + if ($ce -and ($null -ne $ce.Value.overhead_gib)) { $overhead = [math]::Round([math]::Max(0.0, [math]::Min($maxOver, [double]$ce.Value.overhead_gib)), 2) } } catch {} } $targetGiB = $cfg.vram.total_gib - $p.free_margin_gib - $others - $ctx = [int]([math]::Floor((($targetGiB - $v.base_gib) * 1MB) / $kvKiB / 4096) * 4096) # GiB->KiB = *1MB + $kib = ($targetGiB - $v.base_gib - $overhead) * 1MB # GiB->KiB = *1MB + $ctx = 0; if ($kib -gt 0) { $ctx = [int]([math]::Floor($kib / $kvKiB / 4096) * 4096) } $ctx = [math]::Max([int]$p.ctx_min, [math]::Min([int]$v.ctx_max, $ctx)) # Session protection: never come back smaller than the largest live agent session (written by the governor). try { $need = [int](Get-Content "$dir\session-need.txt" -ErrorAction Stop) } catch { $need = 0 } if ($need -gt 0 -and $ctx -lt ($need + 8192)) { $want = [int]([math]::Ceiling(($need + 8192) / 4096) * 4096) - $emerg = [int]([math]::Floor(((($cfg.vram.total_gib - 1.15 - $others) - $v.base_gib) * 1MB) / $kvKiB / 4096) * 4096) # 1.15 GiB = emergency floor, just above the 0.96 GiB free that slowed one run (threshold not isolated, see docs/TUNING-LOG.md) + $emerg = [int]([math]::Floor(((($cfg.vram.total_gib - 1.15 - $others) - $v.base_gib - $overhead) * 1MB) / $kvKiB / 4096) * 4096) # 1.15 GiB = just above the measured slowdown cliff $new = [math]::Min([math]::Min($want, $emerg), [int]$v.ctx_max) if ($new -gt $ctx) { $draftNote = "session-protect: raised ctx $ctx -> $new for live session of $need tokens"; $ctx = $new } if ($ctx -lt ($need + 4096)) { $draftNote += " WARNING: cannot fit live session ($need tokens) - client will get an explicit context error, never silent truncation" } } + # why the fit is below the preferred window (f16 KV: 61440 needs others <= ~1.6 GiB in MAX) - informational + $tgt = 0; try { $tgt = [int]$cfg.auto.ctx_target_min } catch {} + if ($tgt -gt 0 -and $ctx -lt $tgt -and $ctx -lt [int]$v.ctx_max) { + $maxOthers = [math]::Round($cfg.vram.total_gib - $p.free_margin_gib - $v.base_gib - $overhead - ($tgt * $kvKiB / 1MB), 2) + $draftNote += " (ctx below target $tgt`: others=$others GiB, margin=$($p.free_margin_gib); target needs others <= $maxOthers GiB)" + } } $prio = @{ Normal = '0'; BelowNormal = '-1' }[$p.priority]; if (-not $prio) { $prio = '-1' } -$args2 = @('-m', $v.model, '--mmproj', $cfg.mmproj, '-a', $v.id, '--host', '127.0.0.1', '--port', "$($v.port)", +try { if ($cfg.slots -and $cfg.slots.dir) { New-Item -ItemType Directory -Force -Path $cfg.slots.dir | Out-Null } } catch {} # llama-server does not create --slot-save-path itself +$args2 = @('-m', $v.model, '--mmproj', $(if ($v.mmproj) { $v.mmproj } else { $cfg.mmproj }), '-a', $v.id, '--host', '127.0.0.1', '--port', "$($v.port)", '-c', "$ctx", '-ctk', $ctk, '-ctv', $ctv, '-t', "$($p.threads)", '-tb', "$($p.threads)", '-cram', "$($p.cache_ram_mib)", '--prio', $prio) + @($cfg.common_args) + $extra foreach ($e in $cfg.env.PSObject.Properties) { Set-Item -Path "env:$($e.Name)" -Value $e.Value } -try { @{ emergency = [bool]($draftNote -like 'session-protect*'); profile = $name; variant = $Variant; id = $v.id; port = $v.port; ctx = $ctx; ctk = $ctk; ctv = $ctv; others_gib = [math]::Round($others, 2); started = (Get-Date).ToString('s'); launcher_pid = $PID } | ConvertTo-Json | Set-Content "$dir\running.json" } catch {} # governor may hold the file for a moment; never abort the launch for bookkeeping -try { "$(Get-Date -f s) launch: $($v.id) profile=$name ctx=$ctx kv=$ctk/$ctv others=$([math]::Round($others,2))GiB port=$($v.port) $draftNote" | Add-Content "$dir\governor.log" } catch {} +try { @{ emergency = [bool]($draftNote -like 'session-protect*'); profile = $name; variant = $Variant; id = $v.id; port = $v.port; ctx = $ctx; ctk = $ctk; ctv = $ctv; others_gib = $others; others_note = $othersNote; overhead_gib = $overhead; started = (Get-Date).ToString('s'); launcher_pid = [System.Diagnostics.Process]::GetCurrentProcess().Id } | ConvertTo-Json | Set-Content "$dir\running.json" } catch {} # governor may hold the file for a moment; never abort the launch for bookkeeping +$line = "launch: $($v.id) profile=$name ctx=$ctx kv=$ctk/$ctv others=${others}GiB ($othersNote; waited ${waited}s) overhead=${overhead}GiB port=$($v.port) $draftNote" +if ($DryRun) { Write-Output "DRYRUN $line"; Write-Output ("DRYRUN cmd: " + $cfg.exe + ' ' + ($args2 -join ' ')); exit 0 } +LaunchLog $line & $cfg.exe @args2 exit $LASTEXITCODE diff --git a/governor/profiles.json b/governor/profiles.json index a8ab8c3..613d001 100644 --- a/governor/profiles.json +++ b/governor/profiles.json @@ -1,178 +1,252 @@ -{ - "_comment": "Qwen governor v2 (measured on this B60, 10 Oct 2026). AUTO picks MAX (PC idle) / BALANCED (you are on the PC) / LEAN (heavy load). Context is sized at each load from the VRAM free at that moment minus the profile's free-VRAM margin. DFlash2 drafter (7 tokens) ~43-50 tok/s. One run with 0.96 GiB free slowed to 27 tok/s (the exact threshold was not isolated, see docs/TUNING-LOG.md), so the profile margins stay at 1.35 GiB or more. Variants: default UD-Q4_K_M (best quality), turbo Q4_0 (faster, slightly lower quality), long = native 262k context, no drafter (~15 tok/s).", - "exe": "C:/AI/llama.cpp/vulkan-intelfa/llama-server.exe", - "mmproj": "C:/AI/models/qwen3.8-27b/mmproj-F16.gguf", - "vram": { - "total_gib": 23.88, - "budget_gib": 23.13 - }, - "env": { - "GGML_VK_FORCE_MMVQ": "1" - }, - "common_args": [ - "-ngl", - "99", - "-fa", - "on", - "-lm", - "dio", - "--jinja", - "-np", - "1", - "--cache-reuse", - "256", - "--metrics", - "--reasoning-budget", - "4096", - "--reasoning-budget-message", - "Thinking budget reached. Give the final answer now.", - "--no-mmproj-offload", - "-fit", - "off", - "--chat-template-file", - "C:/AI/governor/qwen38-template.jinja", - "--no-context-shift" - ], - "variants": { - "default": { - "id": "qwen3.8-27b", - "port": 10001, - "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", - "ctk": "f16", - "ctv": "f16", - "base_gib": 17.15, - "kv_kib_per_token": 64.5, - "ctx_max": 65536, - "extra_args": [ - "-ngld", - "99", - "-md", - "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", - "--spec-type", - "draft-dflash", - "--spec-draft-n-max", - "7", - "-ub", - "256", - "-ctkd", - "q8_0", - "-ctvd", - "q8_0" - ] - }, - "turbo": { - "id": "qwen3.8-27b-turbo", - "port": 10003, - "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-Q4_0.gguf", - "ctk": "f16", - "ctv": "f16", - "base_gib": 16.77, - "kv_kib_per_token": 64.5, - "ctx_max": 65536, - "extra_args": [ - "-ngld", - "99", - "-md", - "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", - "--spec-type", - "draft-dflash", - "--spec-draft-n-max", - "7", - "-ub", - "256", - "-ctkd", - "q8_0", - "-ctvd", - "q8_0" - ] - }, - "long": { - "id": "qwen3.8-27b-long", - "port": 10004, - "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", - "ctk": "q4_0", - "ctv": "q4_0", - "fixed_ctx": 262144, - "extra_args": [], - "base_gib": 22.11, - "optional_draft": { - "cost_gib": 1.81, - "min_free_gib": 1.3, - "args": [ - "-ngld", - "99", - "-md", - "C:/AI/models/qwen3.8-27b/mtp-Qwen3.8-27B-Q4_0.gguf", - "--spec-type", - "draft-mtp", - "--spec-draft-n-max", - "3", - "-ctkd", - "q4_0", - "-ctvd", - "q4_0" - ] - } - }, - "big": { - "id": "qwen3.8-27b-big", - "port": 10005, - "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", - "ctk": "q4_0", - "ctv": "q4_0", - "base_gib": 17.46, - "kv_kib_per_token": 18.6, - "ctx_max": 262144, - "extra_args": [ - "-ngld", - "99", - "-md", - "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", - "--spec-type", - "draft-dflash", - "--spec-draft-n-max", - "7" - ] - } - }, - "profiles": { - "MAX": { - "free_margin_gib": 1.35, - "ctx_min": 32768, - "threads": 14, - "cache_ram_mib": 8192, - "priority": "Normal", - "idle_unload_min": 0 - }, - "BALANCED": { - "free_margin_gib": 1.5, - "ctx_min": 32768, - "threads": 8, - "cache_ram_mib": 4096, - "priority": "BelowNormal", - "idle_unload_min": 120 - }, - "LEAN": { - "free_margin_gib": 3.0, - "ctx_min": 32768, - "threads": 4, - "cache_ram_mib": 1024, - "priority": "BelowNormal", - "idle_unload_min": 5 - } - }, - "auto": { - "idle_for_max_sec": 600, - "ram_floor_gb": 3.5, - "ram_for_max_gb": 8.0, - "others_vram_lean_gib": 3.5, - "others_vram_max_gib": 3.0, - "vram_free_pressure_gib": 1.1, - "others_cpu_lean_pct": 85, - "confirm_samples": 3, - "model_quiet_sec_before_reload": 120, - "max_upgrade_quiet_min": 20, - "prewarm_cooldown_min": 10, - "sample_sec": 15 - } -} \ No newline at end of file +{ + "_comment": "Qwen governor v2 (measured on this B60, 10 Oct 2026). AUTO picks MAX (PC idle) / BALANCED (you are on the PC) / LEAN (heavy load). Context is sized at each load from the VRAM free at that moment minus the profile's free-VRAM margin. DFlash2 drafter (7 tokens) ~43-50 tok/s; generation collapses if free VRAM < ~1.1 GiB, so margins stay >= 1.2 GiB. Variants: default UD-Q4_K_M (best quality), turbo Q4_0 (faster, slightly lower quality), long = native 262k context, no drafter (~15 tok/s).", + "exe": "C:/AI/llama.cpp/vulkan-intelfa/llama-server.exe", + "mmproj": "C:/AI/models/qwen3.8-27b/mmproj-F16.gguf", + "vram": { + "total_gib": 23.88, + "budget_gib": 23.13 + }, + "env": { + "GGML_VK_FORCE_MMVQ": "1" + }, + "common_args": [ + "-ngl", + "99", + "-fa", + "on", + "-lm", + "dio", + "--jinja", + "-np", + "1", + "--cache-reuse", + "256", + "--metrics", + "--reasoning-budget", + "16384", + "--reasoning-budget-message", + "Thinking budget reached. Give the final answer now.", + "--no-mmproj-offload", + "-fit", + "off", + "--chat-template-file", + "C:/AI/governor/qwen38-template.jinja", + "--no-context-shift", + "--slot-save-path", + "C:/AI/cache/slots" + ], + "slots": { + "enabled": true, + "dir": "C:/AI/cache/slots", + "max_files": 3, + "max_gib": 12, + "min_tokens": 4096, + "min_free_disk_gib": 10 + }, + "calibration": { + "enabled": true, + "alpha": 0.5, + "max_overhead_gib": 1.5, + "_note": "governor learns (measured llama VRAM - base_gib - ctx*kv) per variant into calib.json at each post-launch BASELINE; launch.ps1 adds the positive part to base_gib so free VRAM lands near the profile margin instead of 0.65 GiB (2026-10-16)" + }, + "variants": { + "default": { + "id": "qwen3.8-27b", + "port": 10001, + "model": "C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf", + "ctk": "f16", + "ctv": "f16", + "base_gib": 17.15, + "kv_kib_per_token": 64.5, + "ctx_max": 65536, + "extra_args": [ + "-ngld", + "99", + "-md", + "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", + "--spec-type", + "draft-dflash", + "--spec-draft-n-max", + "7", + "-ub", + "256", + "-ctkd", + "q8_0", + "-ctvd", + "q8_0", + "--spec-draft-p-min", + "0.5" + ], + "mmproj": "C:/AI/models/thinkingcap/mmproj-ThinkingCap-Qwen3.8-27B-f16.gguf" + }, + "turbo": { + "id": "qwen3.8-27b-turbo", + "port": 10003, + "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-Q4_0.gguf", + "ctk": "f16", + "ctv": "f16", + "base_gib": 16.77, + "kv_kib_per_token": 64.5, + "ctx_max": 65536, + "extra_args": [ + "-ngld", + "99", + "-md", + "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", + "--spec-type", + "draft-dflash", + "--spec-draft-n-max", + "7", + "-ub", + "256", + "-ctkd", + "q8_0", + "-ctvd", + "q8_0", + "--spec-draft-p-min", + "0.5" + ] + }, + "long": { + "id": "qwen3.8-27b-long", + "port": 10004, + "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", + "ctk": "q4_0", + "ctv": "q4_0", + "fixed_ctx": 262144, + "extra_args": [], + "base_gib": 22.11, + "optional_draft": { + "cost_gib": 1.81, + "min_free_gib": 1.3, + "args": [ + "-ngld", + "99", + "-md", + "C:/AI/models/qwen3.8-27b/mtp-Qwen3.8-27B-Q4_0.gguf", + "--spec-type", + "draft-mtp", + "--spec-draft-n-max", + "3", + "-ctkd", + "q4_0", + "-ctvd", + "q4_0" + ] + } + }, + "big": { + "id": "qwen3.8-27b-big", + "port": 10005, + "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", + "ctk": "q4_0", + "ctv": "q4_0", + "base_gib": 17.46, + "kv_kib_per_token": 18.6, + "ctx_max": 262144, + "extra_args": [ + "-ngld", + "99", + "-md", + "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", + "--spec-type", + "draft-dflash", + "--spec-draft-n-max", + "7" + ] + }, + "base": { + "id": "qwen3.8-27b-base", + "port": 10006, + "model": "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf", + "ctk": "f16", + "ctv": "f16", + "base_gib": 17.15, + "kv_kib_per_token": 64.5, + "ctx_max": 65536, + "extra_args": [ + "-ngld", + "99", + "-md", + "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf", + "--spec-type", + "draft-dflash", + "--spec-draft-n-max", + "7", + "-ub", + "256", + "-ctkd", + "q8_0", + "-ctvd", + "q8_0", + "--spec-draft-p-min", + "0.5" + ] + } + }, + "profiles": { + "MAX": { + "free_margin_gib": 2.5, + "ctx_min": 32768, + "threads": 14, + "cache_ram_mib": 2048, + "priority": "Normal", + "idle_unload_min": 0 + }, + "BALANCED": { + "free_margin_gib": 2.5, + "ctx_min": 32768, + "threads": 8, + "cache_ram_mib": 4096, + "priority": "BelowNormal", + "idle_unload_min": 120 + }, + "LEAN": { + "free_margin_gib": 3.0, + "ctx_min": 32768, + "threads": 4, + "cache_ram_mib": 1024, + "priority": "BelowNormal", + "idle_unload_min": 5 + } + }, + "auto": { + "idle_for_max_sec": 600, + "ram_floor_gb": 3.5, + "ram_critical_gb": 1.5, + "ram_for_max_gb": 10.0, + "others_vram_lean_gib": 3.5, + "others_vram_max_gib": 2.5, + "vram_free_pressure_gib": 1.1, + "vram_free_hard_floor_gib": 0.25, + "others_growth_gib": 0.5, + "pressure_persist_sec": 60, + "refit_min_interval_min": 15, + "others_cpu_lean_pct": 85, + "confirm_samples": 4, + "model_quiet_sec_before_reload": 120, + "max_upgrade_quiet_min": 20, + "prewarm_cooldown_min": 10, + "sample_sec": 15, + "agent_processes": [ + "codex", + "claude" + ], + "agent_recent_min": 10, + "ctx_target_min": 61440 + }, + "power": { + "dwell_min": 10, + "saver_idle_min": 15, + "saver_model_quiet_min": 15, + "perf_model_recent_sec": 120, + "cpu_busy_pct": 40, + "cpu_busy_samples": 2, + "cpu_calm_pct": 25, + "_note": "v4.2 power-plan hysteresis: PERFORMANCE at once on model activity (busy, or a request within perf_model_recent_sec) or CPU >= cpu_busy_pct for cpu_busy_samples; step down ONE plan at a time only after the lower demand has lasted dwell_min AND the current plan was held dwell_min; never below BALANCED while an agent client is active (auto.agent_processes or a request within auto.agent_recent_min); SAVER only with no input for saver_idle_min AND model quiet for saver_model_quiet_min AND CPU < cpu_calm_pct. power.txt (qwen power ...) still forces a plan immediately." + }, + "_v3_note": "2026-10-11 V3: default = ThinkingCap-Qwen3.8-27B Q4_K_M (16/16, 3.9x tasks/min vs base at xhigh); DFlash2 p-min 0.5 (+4.6%); base kept as variant 'base'.", + "_v4_note": "2026-10-15 V4 governor: PDH readings validated (invalid sample = keep last good, never act); pressure must persist pressure_persist_sec and re-fits/upgrades happen at most every refit_min_interval_min; ram_critical_gb is the acute floor (ram_floor_gb only selects LEAN); agent_processes keep the model warm and block idle unloads; slots = KV slot save before governor unloads / restore after its relaunch (needs --slot-save-path in common_args). ctx_target_min is only logged by launch.ps1 when the fit falls short (f16 KV: 61440 needs others <= ~1.6 GiB in MAX). v4.1: a re-fit needs OTHER apps to have grown >= others_growth_gib since the post-launch baseline (or free < vram_free_hard_floor_gib); footprint calibration via calib.json.", + "_v43_note": "2026-10-17 v4.3 (ctxlab): (1) ProcIds/launch.ps1 count only C:\\AI\\llama.cpp\\* llama-server processes - Ollama's runner (Ollama's bundled llama-server.exe, llama3.2:3b, 3.07 GiB, OLLAMA_KEEP_ALIVE=24h) was being booked as the model, so others read 3 GiB low and free VRAM sat at 0.56 GiB. (2) BALANCED free margin 1.5 -> 1.35 (same as MAX; measured cliff is ~1.1 GiB, post-launch free was 3.06 GiB at ctx 45056 once the Ollama runner was gone). KV stays f16: q8_0 KV measured -53% prefill and -57% decode at 25K depth (Intel FA kernels require f16 K and V) and saved only 0.27 GiB of dedicated VRAM at 40960.", + "_v44_note": "2026-10-18 published defaults: MAX/BALANCED free_margin_gib 2.5 and auto.others_vram_max_gib 2.5. A fit on adapter dedicated-free VRAM is not a real fit: at margin 1.35 the governor chose ctx 57344 and llama-server spilled 2.90 GiB into WDDM shared memory (20-22 tok/s). Margin 2.5 landed ctx 36864 with 1.23 GiB shared (26.7-28.3 tok/s). Re-qualify the margin on your desktop with the shared-usage check in docs/FIELD-REPORT-20261018.md." +} diff --git a/governor/qwen.ps1 b/governor/qwen.ps1 index d3dd2f0..e6d06ab 100644 --- a/governor/qwen.ps1 +++ b/governor/qwen.ps1 @@ -1,5 +1,5 @@ # qwen - control the local Qwen server on this PC -# qwen status | qwen mode auto|max|balanced|lean|off | qwen load [fast] | qwen unload | qwen restart | qwen log +# qwen status | qwen mode auto|max|balanced|lean|off | qwen load [fast] | qwen unload | qwen restart | qwen log | qwen slots [clear] param([string]$Cmd = 'status', [string]$Arg = '') $dir = 'C:\AI\governor'; $swap = 'http://127.0.0.1:8090' $key = (Get-Content 'C:\AI\llama-swap\api-key.txt' -Raw).Trim(); $h = @{ Authorization = "Bearer $key" } @@ -9,6 +9,9 @@ switch ($Cmd.ToLower()) { $age = [math]::Round(((Get-Date) - [datetime]$s.time).TotalSeconds) Write-Host ("Mode {0} | profile {1} | model {2}{3} | ctx {4} | quiet {5} min" -f $s.mode, $s.profile, $(if ($s.loaded) { "LOADED ($($s.loaded_profile))" } else { $s.state }), $(if ($s.processing) { ' BUSY' } else { '' }), $s.n_ctx, $s.model_quiet_min) Write-Host ("PC: idle {0}s | RAM free {1} GB | VRAM used {2}/23.9 GiB (model {3}, others {4}) | CPU others {5}%" -f $s.idle_sec, $s.ram_avail_gb, $s.vram_used_gib, $s.vram_llama_gib, $s.vram_others_gib, $s.cpu_others) + if ($null -ne $s.decision_reason) { Write-Host ("Governor: {0} ({1}) | pressure {2}s | agent {3}" -f $s.decision, $s.decision_reason, $s.pressure_sec, $(if ($s.agent_active) { 'active' } else { 'none' })) } + if ($s.degraded) { Write-Host ("DEGRADED: loop errors {0} (streak {1}, heals {2}) last_error={3}" -f $s.loop_errors, $s.loop_error_streak, $s.self_heals, $s.last_error) -ForegroundColor Yellow + if ($s.sense_warnings) { Write-Host (" sense: " + ($s.sense_warnings -join '; ')) -ForegroundColor Yellow } } if ($age -gt 60) { Write-Host "WARNING: governor status is $age s old - governor may not be running" -ForegroundColor Yellow } } 'mode' { @@ -45,12 +48,35 @@ switch ($Cmd.ToLower()) { Write-Host 'Done - the next request (or the governor prewarm) loads the new engine.' } 'bench' { powershell -NoProfile -ExecutionPolicy Bypass -File C:\AI\bench\regression.ps1 } + 'slots' { + # saved KV slots (written by the governor before it unloads the model, restored after its own reloads) + $lib = "$dir\slotlib.ps1"; if (-not (Test-Path $lib)) { Write-Host "slotlib.ps1 missing in $dir"; break } + . $lib + $sd = 'C:/AI/cache/slots'; try { $c = Get-Content "$dir\profiles.json" -Raw | ConvertFrom-Json; if ($c.slots -and $c.slots.dir) { $sd = [string]$c.slots.dir } } catch {} + if (-not (SlotDirSafe $sd)) { Write-Host "Refusing to touch unsafe slots dir: $sd"; break } + $rows = @(SlotList $sd) + if ($Arg.ToLower() -eq 'clear') { + $files = @(Get-ChildItem -LiteralPath $sd -File -ErrorAction SilentlyContinue | ? { $_.Extension -in '.bin', '.json' }) + if (-not $files.Count) { Write-Host "No slot files in $sd"; break } + $gib = [math]::Round((($files | measure Length -Sum).Sum) / 1GB, 2) + $ans = Read-Host "Delete $($files.Count) slot file(s) ($gib GiB) from $sd ? [y/N]" + if ($ans -match '^(y|yes)$') { $n = SlotClear $sd; Write-Host "Deleted $n file(s). Next reload starts with an empty slot." } else { Write-Host 'Nothing deleted.' } + break + } + if ($Arg -ne '') { Write-Host 'usage: qwen slots | qwen slots clear'; break } + if (-not $rows.Count) { Write-Host "No saved slots in $sd"; break } + foreach ($r in $rows) { + Write-Host ("{0,-28} {1,6} GiB | {2,7} tokens | ctx {3,7} | saved {4} ago{5}" -f $r.file, $r.gib, $(if ($null -ne $r.tokens) { $r.tokens } else { '?' }), $(if ($null -ne $r.ctx) { $r.ctx } else { '?' }), (SlotAgeText $r.age_min), $(if ($r.sidecar) { '' } else { ' (no sidecar: will not be restored)' })) + } + Write-Host ("{0} file(s), {1} GiB in {2}" -f $rows.Count, [math]::Round((($rows | measure gib -Sum).Sum), 2), $sd) + } + 'test' { powershell -NoProfile -ExecutionPolicy Bypass -File "$dir\test_governor.ps1" } 'log' { Get-Content "$dir\governor.log" -Tail 25 } 'doctor' { powershell -NoProfile -ExecutionPolicy Bypass -File "$dir\doctor.ps1" } { $_ -in 'snapshot', 'history', 'rollback', 'diff' } { powershell -NoProfile -ExecutionPolicy Bypass -File "$dir\snapshot.ps1" $Cmd $Arg } 'window' { # Safe client context window = loaded ctx (or expected ctx if not loaded) minus 8k headroom - $w = 24576 # safe fallback if status.json is unreadable: ctx_min 32768 minus 8K headroom (never larger than any real load) + $w = 24576 # safe fallback if status.json is unreadable: ctx_min 32768 minus 8K headroom try { $s = Get-Content "$dir\public\status.json" -Raw | ConvertFrom-Json $c = if ($s.loaded -and $s.n_ctx) { [int]$s.n_ctx } elseif ($s.expected_ctx) { [int]$s.expected_ctx } else { 0 } if ($Arg -eq 'long') { $c = 262144 } @@ -58,7 +84,7 @@ switch ($Cmd.ToLower()) { if ($c -gt 0) { $w = [math]::Max(16384, $c - 8192) } } catch {} Write-Output $w } - default { Write-Host 'qwen status | mode auto|max|balanced|lean|off | load [fast] | unload | restart | log' } + default { Write-Host 'qwen status | mode auto|max|balanced|lean|off | load [fast] | unload | restart | slots [clear] | test | log' } } diff --git a/governor/slotlib.ps1 b/governor/slotlib.ps1 new file mode 100644 index 0000000..03a4e22 --- /dev/null +++ b/governor/slotlib.ps1 @@ -0,0 +1,485 @@ +# Slot persistence for the Qwen governor: save the KV slot before an unload, restore it after a governor-initiated load. +# v4 (2026-10-15): sidecar records the KV type (ctk/ctv) and a restore into a different KV type is refused; the save checks free disk first. +# Dot-sourced by governor.ps1, qwen.ps1 and the restore background job. PowerShell 5.1 compatible. No top-level side effects. +# The pure decision functions (Slot*Decision, SlotPruneSelection, SlotEmptyReplyStep ...) mirror governor/slotpolicy.py, +# which has the unit tests (python3 governor/test_slotpolicy.py). Change a rule in both places. +$script:SlotLogPath = 'C:\AI\governor\governor.log' +$script:SlotLogged = @{} + +function SlotLog($m) { + $line = "$(Get-Date -f s) $m" + try { $line | Add-Content $script:SlotLogPath -ErrorAction Stop } catch { try { Start-Sleep -Milliseconds 250; $line | Add-Content $script:SlotLogPath -ErrorAction Stop } catch {} } +} +function SlotLogOnce($key, $m) { if (-not $script:SlotLogged.ContainsKey($key)) { $script:SlotLogged[$key] = $true; SlotLog $m } } + +# ---------------- pure decision logic (mirrors slotpolicy.py) ---------------- +function SlotIsNum($v) { ($v -is [int]) -or ($v -is [long]) -or ($v -is [double]) -or ($v -is [decimal]) -or ($v -is [single]) } +function SlotResult($ok, $reason) { [pscustomobject]@{ ok = [bool]$ok; reason = [string]$reason } } +function SlotNormPath($p) { ([string]$p).Replace('\', '/').Trim().ToLowerInvariant() } + +function SlotFilename($id) { + if (($id -isnot [string]) -or ($id -notmatch '^[A-Za-z0-9._-]{1,64}$') -or $id.StartsWith('.')) { return $null } + return ($id + '.bin') +} +function SlotTokenCount($slot) { + if ($null -eq $slot) { return $null } + foreach ($k in 'n_tokens', 'n_past', 'n_cache_tokens') { + $pr = $slot.PSObject.Properties[$k] + if ($pr -and (SlotIsNum $pr.Value) -and ($pr.Value -ge 0)) { return [int]$pr.Value } + } + return $null +} +function SlotSaveDecision($slot, $minTokens) { + if ($null -eq $slot) { return (SlotResult $false 'no slot info') } + if ($slot.is_processing -eq $true) { return (SlotResult $false 'slot busy') } + $n = SlotTokenCount $slot + if ($null -eq $n) { return (SlotResult $true 'n_tokens not reported') } # save anyway; SlotPostSaveOk re-checks n_saved + if ($n -lt $minTokens) { return (SlotResult $false "n_tokens $n < min_tokens $minTokens") } + return (SlotResult $true "n_tokens $n") +} +function SlotPostSaveOk($nSaved, $minTokens) { + if (-not (SlotIsNum $nSaved)) { return (SlotResult $false 'save reply has no n_saved') } + $n = [int]$nSaved + if ($n -lt $minTokens) { return (SlotResult $false "n_saved $n < min_tokens $minTokens") } + return (SlotResult $true "n_saved $n") +} +function SlotRestoreDecision($sidecar, $binExists, $modelPath, $ctx, $modelStat, $headroom = 4096, $kvNow = $null) { + if (-not $binExists) { return (SlotResult $false 'no slot file') } + if (($null -eq $sidecar) -or ($sidecar -is [string]) -or ($sidecar -is [ValueType]) -or ($sidecar -is [array])) { return (SlotResult $false 'no sidecar') } + $n = $sidecar.n_tokens + if (-not (SlotIsNum $n) -or $n -le 0) { return (SlotResult $false 'sidecar has no n_tokens') } + $n = [int]$n + $sm = $sidecar.model_path + if (-not $sm -or -not $modelPath -or ((SlotNormPath $sm) -ne (SlotNormPath $modelPath))) { return (SlotResult $false 'model_path mismatch') } + if (-not $modelStat) { return (SlotResult $false 'model file stat unavailable') } + if (-not (SlotIsNum $sidecar.model_size) -or -not (SlotIsNum $sidecar.model_mtime)) { return (SlotResult $false 'sidecar has no model size/mtime') } + if (([long]$sidecar.model_size -ne [long]$modelStat.size) -or ([long]$sidecar.model_mtime -ne [long]$modelStat.mtime)) { return (SlotResult $false 'model file changed (size/mtime differ)') } + # a slot saved with one KV type (f16) cannot be restored into another (q8_0): refuse when both sides are known and differ + $skv = $null; $kp = $sidecar.PSObject.Properties['kv']; if ($kp -and ($kp.Value -is [string])) { $skv = $kp.Value } + if ($skv -and $kvNow -and ($skv.ToLowerInvariant() -ne ([string]$kvNow).ToLowerInvariant())) { return (SlotResult $false "kv type changed ($skv -> $kvNow)") } + if (-not (SlotIsNum $ctx) -or $ctx -le 0) { return (SlotResult $false 'new ctx unknown') } + $ctx = [int]$ctx + if ($ctx -lt ($n + $headroom)) { return (SlotResult $false "ctx $ctx < n_tokens $n + $headroom") } + return (SlotResult $true "n_tokens $n") +} +# May the governor unload now? Only a definitely-processing slot says no (checked before AND after the save). +function SlotUnloadGate($slot) { + if (($null -ne $slot) -and ($slot.is_processing -eq $true)) { return (SlotResult $false 'slot busy') } + if ($null -eq $slot) { return (SlotResult $true 'slot state unknown') } + return (SlotResult $true 'slot idle') +} +function SlotRestoreTargetOk($slot) { + if ($null -eq $slot) { return (SlotResult $true 'slot state unknown') } + if ($slot.is_processing -eq $true) { return (SlotResult $false 'slot busy (a request is already running)') } + $n = SlotTokenCount $slot + if (($null -ne $n) -and ($n -gt 0)) { return (SlotResult $false "slot not empty ($n tokens)") } + return (SlotResult $true 'slot empty') +} +# entries: objects with .name .size (bytes) .mtime (epoch seconds). Returns leaf names to delete. Never returns anything but *.bin / *.json leaf names. +function SlotPruneSelection($entries, $maxFiles, $maxGib, $managedIds = $null) { + $maxBytes = [double]$maxGib * 1GB + $del = New-Object System.Collections.ArrayList + $units = @{} + foreach ($e in @($entries)) { + $name = [string]$e.name + if (-not $name -or $name.Contains('/') -or $name.Contains('\')) { continue } + if ($name.EndsWith('.tmp.bin')) { $stem = $name.Substring(0, $name.Length - 8); $kind = 'tmp' } + elseif ($name.EndsWith('.bin')) { $stem = $name.Substring(0, $name.Length - 4); $kind = 'bin' } + elseif ($name.EndsWith('.json')) { $stem = $name.Substring(0, $name.Length - 5); $kind = 'json' } + else { continue } + if (($null -ne $managedIds) -and (@($managedIds) -notcontains $stem)) { continue } + if ($kind -eq 'tmp') { [void]$del.Add($name); continue } + if (-not $units.ContainsKey($stem)) { $units[$stem] = @{} } + $units[$stem][$kind] = $e + } + $complete = @() + foreach ($stem in @($units.Keys)) { + $u = $units[$stem] + if ($u.ContainsKey('bin') -and $u.ContainsKey('json')) { + $complete += [pscustomobject]@{ stem = $stem; size = ([double]$u['bin'].size + [double]$u['json'].size); mtime = [math]::Max([double]$u['bin'].mtime, [double]$u['json'].mtime) } + } else { foreach ($k in @($u.Keys)) { [void]$del.Add([string]$u[$k].name) } } + } + $complete = @($complete | Sort-Object mtime, stem) # oldest first + $count = $complete.Count; $total = 0.0; foreach ($c in $complete) { $total += $c.size } + $i = 0 + while (($i -lt $complete.Count) -and (($count -gt $maxFiles) -or ($total -gt $maxBytes))) { + $c = $complete[$i]; [void]$del.Add($c.stem + '.bin'); [void]$del.Add($c.stem + '.json') + $count--; $total -= $c.size; $i++ + } + return @($del) +} +function SlotHygieneDecision($loadedMin, $quietMin, $processing, $intervalHours, $sinceLastMin, $minQuietMin = 10, $cooldownMin = 30) { + if (-not $intervalHours -or $intervalHours -le 0) { return (SlotResult $false 'disabled') } + if ($processing) { return (SlotResult $false 'busy') } + if ($null -eq $loadedMin) { return (SlotResult $false 'load time unknown') } + if ($loadedMin -lt ($intervalHours * 60)) { return (SlotResult $false ('loaded {0:F0} min < {1:F0} min' -f $loadedMin, ($intervalHours * 60))) } + if ($quietMin -le $minQuietMin) { return (SlotResult $false ('quiet {0:F1} min <= {1} min' -f $quietMin, $minQuietMin)) } + if (($null -ne $sinceLastMin) -and ($sinceLastMin -lt $cooldownMin)) { return (SlotResult $false 'cooldown') } + return (SlotResult $true ('loaded {0:F1} h, quiet {1:F1} min' -f ($loadedMin / 60.0), $quietMin)) +} +# Heuristic over /metrics counters (there is no per-request counter). Caller advances prev* only when nothing is processing. +function SlotEmptyReplyStep($prevP, $prevT, $p, $t, $processing, $count) { + if (($null -eq $prevP) -or ($null -eq $prevT) -or ($null -eq $p) -or ($null -eq $t)) { return 0 } + if (($p -lt $prevP) -or ($t -lt $prevT)) { return 0 } # counters went backwards: server restarted + if ($processing) { return $count } + if (($t - $prevT) -gt 0) { return 0 } + if (($p - $prevP) -gt 0) { return ($count + 1) } + return $count +} + +# ---------------- Control Centre levers: request.json, phases, VRAM bands (mirror slotpolicy.py) ---------------- +function SlotReqResult($ok, $action, $arg, $reason) { [pscustomobject]@{ ok = [bool]$ok; action = $action; arg = $arg; reason = [string]$reason } } +function SlotPlan($plan, $reason) { [pscustomobject]@{ plan = [string]$plan; reason = [string]$reason } } +# Epoch seconds of a request's t (number = seconds, >= 1e11 = milliseconds; ISO 8601 string, naive = UTC), else $null. +function SlotRequestTime($t) { + if (($null -eq $t) -or ($t -is [bool])) { return $null } + if (SlotIsNum $t) { + $n = [double]$t + if ([double]::IsNaN($n) -or ($n -le 0)) { return $null } + if ($n -ge 1e11) { return ($n / 1000.0) } + return $n + } + if ($t -is [datetime]) { + $u = $t; if ($u.Kind -eq [DateTimeKind]::Local) { $u = $u.ToUniversalTime() } else { $u = [datetime]::SpecifyKind($u, [DateTimeKind]::Utc) } + return ($u - [datetime]::new(1970, 1, 1, 0, 0, 0, [DateTimeKind]::Utc)).TotalSeconds + } + if ($t -is [string]) { + $str = $t.Trim() + if ($str -notmatch '^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}') { return $null } + $dto = [DateTimeOffset]::MinValue + if ([DateTimeOffset]::TryParse($str, [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal, [ref]$dto)) { return ([double]$dto.ToUnixTimeMilliseconds() / 1000.0) } + } + return $null +} +# Validate a request.json that ConvertFrom-Json produced. $now = epoch seconds. Result: ok, action (load|unload|restore|mode), arg (mode name), reason. +# Nothing in the file is ever executed; anything outside the four actions, or older than 60 s, is refused. +function SlotRequestDecision($req, $now, $maxAge = 60) { + if (($null -eq $req) -or ($req -isnot [pscustomobject])) { return (SlotReqResult $false $null $null 'not a JSON object') } + $ap = $req.PSObject.Properties['action'] + if ((-not $ap) -or ($ap.Value -isnot [string])) { return (SlotReqResult $false $null $null 'no action') } + $act = $ap.Value.Trim().ToLowerInvariant() + if ($act -eq 'reload') { $act = 'restore' } # the GUI says reload, the governor says restore + if (@('load', 'unload', 'restore', 'mode') -notcontains $act) { return (SlotReqResult $false $null $null 'action not allowed') } + $tp = $req.PSObject.Properties['t']; $raw = $null; if ($tp) { $raw = $tp.Value } + $tt = SlotRequestTime $raw + if ($null -eq $tt) { return (SlotReqResult $false $null $null 'no usable timestamp') } + $age = [double]$now - $tt + if ($age -gt $maxAge) { return (SlotReqResult $false $null $null ('stale request ({0:F0} s old, limit {1} s)' -f $age, $maxAge)) } + if ($age -lt -5) { return (SlotReqResult $false $null $null 'request dated in the future') } + $arg = $null + if ($act -eq 'mode') { + $mp = $req.PSObject.Properties['mode']; $mv = $null + if ($mp -and ($mp.Value -is [string])) { $mv = $mp.Value.Trim().ToUpperInvariant() } + if (@('AUTO', 'MAX', 'BALANCED', 'LEAN', 'OFF') -notcontains $mv) { return (SlotReqResult $false $null $null 'mode not allowed') } + $arg = $mv + } + return (SlotReqResult $true $act $arg 'ok') +} +# What to do with a valid request: plan = set-mode | prewarm | unload | unload-then-prewarm | postpone | noop. 'postpone' = a request is running ("never while busy"). +function SlotRequestPlan($action, $loaded, $state, $processing, $curMode, $otherRunning = $false) { + if ($action -eq 'mode') { return (SlotPlan 'set-mode' 'ok') } + if (($state -eq 'swap-down') -or ($state -eq 'api-error')) { return (SlotPlan 'noop' 'llama-swap not answering') } + if ($state -eq 'starting') { return (SlotPlan 'noop' 'model is already loading') } + if ($action -eq 'load') { + if ($loaded) { return (SlotPlan 'noop' 'already loaded') } + if ($curMode -eq 'OFF') { return (SlotPlan 'noop' 'mode OFF') } + if ($otherRunning) { return (SlotPlan 'noop' 'another model is running') } + return (SlotPlan 'prewarm' 'load') + } + if ($action -eq 'restore') { + if ($curMode -eq 'OFF') { return (SlotPlan 'noop' 'mode OFF') } + if (-not $loaded) { if ($otherRunning) { return (SlotPlan 'noop' 'another model is running') }; return (SlotPlan 'prewarm' 'load with restore') } + if ($processing) { return (SlotPlan 'postpone' 'a request is running') } + return (SlotPlan 'unload-then-prewarm' 'save, unload, reload with restore') + } + if ($action -eq 'unload') { + if (-not $loaded) { return (SlotPlan 'noop' 'not loaded') } + if ($processing) { return (SlotPlan 'postpone' 'a request is running') } + return (SlotPlan 'unload' 'unload') + } + return (SlotPlan 'noop' 'action not allowed') +} +# The `phase` string for status.json. Ages are seconds since the event or $null. NOTE: in PowerShell $null -lt 30 is TRUE, so every age is null-checked. +function SlotPhaseDecide($state, $loaded, $processing, $jobPhase = $null, $jobAge = $null, $unloadAge = $null, $postponedAge = $null, $prewarmAge = $null) { + if ($loaded -and ($null -ne $postponedAge) -and ($postponedAge -lt 30)) { return 'postponed-busy' } + if ((@('loading', 'restoring', 'warming') -contains $jobPhase) -and ($null -ne $jobAge) -and ($jobAge -lt 180)) { return $jobPhase } + if ($state -eq 'starting') { return 'loading' } + if ($state -eq 'stopping') { return 'unloading' } + if (($null -ne $prewarmAge) -and ($prewarmAge -lt 30) -and (($null -eq $unloadAge) -or ($prewarmAge -le $unloadAge))) { + if (($null -ne $unloadAge) -and ($unloadAge -lt 10)) { return 'loading' } # unload then reload in one sample: $loaded is still the pre-unload value + if ((-not $loaded) -and ($state -eq 'stopped')) { return 'loading' } + if ($loaded -and $processing) { return 'warming' } + } + if ($loaded -and ($null -ne $unloadAge) -and ($unloadAge -lt 10)) { return 'unloading' } + if ($loaded) { return 'ready' } + return 'stopped' +} +# VRAM bands in GiB that sum to the heap total: model + kv (estimated) + desktop (dwm) + other + free. +function SlotVramBands($total, $used, $llama, $desktop, $nCtx = $null, $kvKib = $null) { + $tot = [math]::Max(0.0, [double]$total); $usd = [math]::Max(0.0, [double]$used) + $lla = [math]::Min([math]::Max(0.0, [double]$llama), $usd) + $dsk = [math]::Min([math]::Max(0.0, [double]$desktop), ($usd - $lla)) + $oth = [math]::Max(0.0, ($usd - $lla - $dsk)) + $kv = 0.0 + if (($lla -gt 0) -and $nCtx -and $kvKib) { $kv = [math]::Min($lla, ([double]$nCtx * [double]$kvKib / 1048576.0)) } + $mdl = $lla - $kv + $free = [math]::Max(0.0, ($tot - $usd)) + $sum = $mdl + $kv + $dsk + $oth + if (($tot -gt 0) -and ($sum -gt $tot)) { $f = $tot / $sum; $mdl *= $f; $kv *= $f; $dsk *= $f; $oth *= $f; $free = 0.0 } + return [ordered]@{ total_gib = [math]::Round($tot, 2); model_gib = [math]::Round($mdl, 2); kv_gib = [math]::Round($kv, 2); desktop_gib = [math]::Round($dsk, 2); other_gib = [math]::Round($oth, 2); free_gib = [math]::Round($free, 2); kv_estimated = $true } +} +# Itemised cost of the next load: base (weights + drafter + compute buffers, from profiles.json base_gib) + KV at ctx. others = VRAM not ours (desktop included). +function SlotPreload($total, $others, $base, $kvKib, $ctx, $margin) { + $kv = [double]$ctx * [double]$kvKib / 1048576.0 + $need = [double]$base + $kv + $after = [double]$total - [double]$others - $need + return [ordered]@{ base_gib = [math]::Round([double]$base, 2); kv_gib = [math]::Round($kv, 2); ctx = [int]$ctx; need_gib = [math]::Round($need, 2); others_gib = [math]::Round([double]$others, 2); free_after_gib = [math]::Round($after, 2); margin_gib = [math]::Round([double]$margin, 2); fits = ($after -ge ([double]$margin - 0.05)) } +} +# phase.json: the restore warm-up job (a separate process) reports its step here; the governor merges it into status.json. +function SlotSetPhase($p, $phase) { + try { + $f = [string]$p.phase_file; if (-not $f) { return } + $o = [ordered]@{ phase = $phase; t = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds(); id = [string]$p.id } + $tmp = $f + '.tmp' + [IO.File]::WriteAllText($tmp, ($o | ConvertTo-Json -Compress), (New-Object System.Text.UTF8Encoding($false))) + Move-Item -LiteralPath $tmp -Destination $f -Force + } catch {} +} +function SlotClearPhase($file) { try { if ($file -and (Test-Path -LiteralPath $file)) { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue } } catch {} } +function SlotReadPhase($file) { + try { + if ($file -and (Test-Path -LiteralPath $file)) { + $o = [IO.File]::ReadAllText($file) | ConvertFrom-Json + if (($o.phase -is [string]) -and (SlotIsNum $o.t)) { return [pscustomobject]@{ phase = $o.phase; age = ([DateTimeOffset]::UtcNow.ToUnixTimeSeconds() - [double]$o.t) } } + } + } catch {} + return [pscustomobject]@{ phase = $null; age = $null } +} + +# ---------------- paths and config ---------------- +function SlotDirSafe($d) { + try { + if (-not $d) { return $false } + $full = [IO.Path]::GetFullPath([string]$d).TrimEnd([char[]]'\/') + if ($full.Length -le 3) { return $false } # a drive root + if (@($full.Split([char[]]'\/') | ? { $_ }).Count -lt 3) { return $false } # C:\AI is too shallow, C:\AI\cache\slots is fine + return $true + } catch { return $false } +} +# Full path of a leaf name inside $dir, or $null if it could land anywhere else. +function SlotSafePath($dir, $name) { + try { + if (-not $name -or ($name -ne [IO.Path]::GetFileName($name)) -or $name.StartsWith('.')) { return $null } + $root = [IO.Path]::GetFullPath([string]$dir).TrimEnd([char[]]'\/') + $full = [IO.Path]::GetFullPath((Join-Path $dir $name)) + if ($full -ne ($root + '\' + $name)) { return $null } + return $full + } catch { return $null } +} +function SlotDirReady($d) { if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } } +function SlotModelPath($cfg, $id) { + foreach ($p in $cfg.variants.PSObject.Properties) { if ($p.Value.id -eq $id) { return [string]$p.Value.model } } + return $null +} +# Returns a hashtable (dir, max_files, max_gib, min_tokens, headroom) or $null when slots are off / unsafe / not wired into the server args. +function SlotCfg($cfg) { + try { + $s = $cfg.slots + if (-not $s -or ($s.enabled -ne $true)) { return $null } + $d = [string]$s.dir + if (-not (SlotDirSafe $d)) { SlotLogOnce 'dir' "slots disabled: unsafe slots.dir '$d'"; return $null } + $ca = @($cfg.common_args); $i = [array]::IndexOf($ca, '--slot-save-path') + if (($i -lt 0) -or (($i + 1) -ge $ca.Count) -or ((SlotNormPath $ca[$i + 1]).TrimEnd('/') -ne (SlotNormPath $d).TrimEnd('/'))) { + SlotLogOnce 'args' 'slots disabled: common_args has no --slot-save-path equal to slots.dir (server could not save/restore)'; return $null } + $mf = [int]$s.max_files; if ($mf -lt 1) { $mf = 3 } + $mg = [double]$s.max_gib; if ($mg -le 0) { $mg = 12 } + $mt = [int]$s.min_tokens; if ($mt -lt 1) { $mt = 4096 } + $md = 10.0; try { if (SlotIsNum $s.min_free_disk_gib) { $md = [double]$s.min_free_disk_gib } } catch {} + return @{ dir = $d; max_files = $mf; max_gib = $mg; min_tokens = $mt; headroom = 4096; min_free_disk_gib = $md } + } catch { return $null } +} +# (size, mtime) of the model file as the sidecar records it: mtime is whole UTC epoch seconds. $null when unreadable. +function SlotModelStat($path) { + try { $fi = Get-Item -LiteralPath $path -ErrorAction Stop + return [pscustomobject]@{ size = [long]$fi.Length; mtime = [long][math]::Floor(($fi.LastWriteTimeUtc - [datetime]'1970-01-01').TotalSeconds) } } catch { return $null } +} +# First slot from GET /slots, or $null. PS 5.1 hands a JSON array back as ONE object, so take [0] from the variable, never from @(Invoke-RestMethod ...). +function SlotGetSlot($base) { + try { $r = Invoke-RestMethod -Uri "${base}/slots" -TimeoutSec 5; return @($r)[0] } catch { return $null } +} +function SlotReadSidecar($dir, $id) { + try { $f = SlotSafePath $dir ($id + '.json'); if ($f -and (Test-Path -LiteralPath $f)) { return (Get-Content -LiteralPath $f -Raw -Encoding UTF8 | ConvertFrom-Json) } } catch {} + return $null +} + +# ---------------- save (before a governor-initiated unload). Never throws; a failure only logs. ---------------- +# Returns $true when the unload may go ahead, $false only when a request was running before or after the save (unloading would kill it). +# Free GiB on the drive that holds $dir, or $null. +function SlotDiskFreeGib($dir) { try { $root = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath([string]$dir)); return ((New-Object System.IO.DriveInfo $root).AvailableFreeSpace / 1GB) } catch { return $null } } +# $variant (optional): the profiles.json variant object of $id (ctk, ctv, kv_kib_per_token) - recorded in the sidecar and used for the disk-space estimate. +function SlotSave($s, $id, $port, $modelPath, $ctx, $variant = $null) { + $tmp = $null + try { + $fn = SlotFilename $id + if (-not $fn) { SlotLog 'SAVE skipped (bad variant id)'; return $true } + SlotDirReady $s.dir + $base = "http://127.0.0.1:${port}" + $slot = SlotGetSlot $base + $g = SlotUnloadGate $slot + if (-not $g.ok) { SlotLog "SAVE skipped, unload postponed ($($g.reason))"; return $false } + $d = SlotSaveDecision $slot $s.min_tokens + if (-not $d.ok) { SlotLog "SAVE skipped ($($d.reason))"; return $true } + $slotId = 0; if ($slot -and ($null -ne $slot.id)) { $slotId = [int]$slot.id } + # never fill the disk: estimated file size = tokens * KV bytes/token (+ headroom), checked against the free space + $kvKib = 64.5; $kvType = $null + if ($variant) { try { if (SlotIsNum $variant.kv_kib_per_token) { $kvKib = [double]$variant.kv_kib_per_token }; if ($variant.ctk) { $kvType = "$($variant.ctk)/$($variant.ctv)" } } catch {} } + $nEst = SlotTokenCount $slot; if ($null -eq $nEst) { $nEst = 65536 } + $estGib = ($nEst * $kvKib / 1048576.0) * 1.1 + $freeDisk = SlotDiskFreeGib $s.dir + $minFree = 10.0; try { if ($null -ne $s.min_free_disk_gib) { $minFree = [double]$s.min_free_disk_gib } } catch {} + if (($null -ne $freeDisk) -and (($freeDisk - $estGib) -lt $minFree)) { SlotLog ('SAVE skipped (disk: {0:F1} GiB free, slot needs ~{1:F1} GiB, keep {2:F0} GiB free)' -f $freeDisk, $estGib, $minFree); return $true } + if (-not $ctx) { try { $ctx = [int](Invoke-RestMethod -Uri "${base}/props" -TimeoutSec 5).default_generation_settings.n_ctx } catch {} } + $tmpName = $id + '.tmp.bin' + $tmp = SlotSafePath $s.dir $tmpName; $final = SlotSafePath $s.dir $fn; $side = SlotSafePath $s.dir ($id + '.json') + if (-not $tmp -or -not $final -or -not $side) { SlotLog 'SAVE skipped (path outside slots dir)'; return $true } + # Save under a temp name and rename on success: a timeout or crash mid-write can never leave a half file under the real name. + $sw = [Diagnostics.Stopwatch]::StartNew() + $r = Invoke-RestMethod -Method Post -Uri "${base}/slots/${slotId}?action=save" -Body (@{ filename = $tmpName } | ConvertTo-Json -Compress) -ContentType 'application/json' -TimeoutSec 30 + $ms = $sw.ElapsedMilliseconds + $ok = SlotPostSaveOk $r.n_saved $s.min_tokens + if (-not $ok.ok) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue; SlotLog "SAVE discarded ($($ok.reason))" } + else { + Remove-Item -LiteralPath $side -Force -ErrorAction SilentlyContinue # sidecar present == file valid; drop the old one first + Move-Item -LiteralPath $tmp -Destination $final -Force + $st = SlotModelStat $modelPath + $meta = [ordered]@{ n_tokens = [int]$r.n_saved; ctx = $ctx; saved_at = (Get-Date).ToString('s'); model_path = $modelPath; model_size = $(if ($st) { $st.size } else { $null }); model_mtime = $(if ($st) { $st.mtime } else { $null }); variant = $id; kv = $kvType } + [IO.File]::WriteAllText($side, ($meta | ConvertTo-Json -Compress), (New-Object System.Text.UTF8Encoding($false))) + $gib = [math]::Round((Get-Item -LiteralPath $final).Length / 1GB, 2) + SlotLog "SAVE $($meta.n_tokens) tokens, $gib GiB in $ms ms ($id)" + } + # a request may have arrived during the (multi-second) save: re-read the slot before letting the caller unload + $g2 = SlotUnloadGate (SlotGetSlot $base) + if (-not $g2.ok) { SlotLog "unload postponed: a request started during the slot save ($($g2.reason))"; return $false } + return $true + } catch { + SlotLog "SAVE failed ($($_.Exception.Message)); unloading anyway" + if ($tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue } + return $true + } +} + +# ---------------- pruning: only *.bin / *.json leaf names inside the slots dir, only governed variant ids ---------------- +function SlotPrune($s, $managedIds) { + try { + if (-not (Test-Path -LiteralPath $s.dir)) { return } + $epoch = [datetime]'1970-01-01' + $ents = @(Get-ChildItem -LiteralPath $s.dir -File -ErrorAction Stop | ? { $_.Extension -in '.bin', '.json' } | + % { [pscustomobject]@{ name = $_.Name; size = [double]$_.Length; mtime = ($_.LastWriteTimeUtc - $epoch).TotalSeconds } }) + $del = @(SlotPruneSelection $ents $s.max_files $s.max_gib $managedIds) + $gone = @() + foreach ($n in $del) { $f = SlotSafePath $s.dir $n; if ($f -and (Test-Path -LiteralPath $f)) { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue; $gone += $n } } + if ($gone.Count) { SlotLog "PRUNE removed $($gone -join ', ')" } + } catch { SlotLog "prune failed: $($_.Exception.Message)" } +} +function SlotDropVariant($s, $id) { + try { foreach ($n in @(($id + '.bin'), ($id + '.json'), ($id + '.tmp.bin'))) { $f = SlotSafePath $s.dir $n; if ($f -and (Test-Path -LiteralPath $f)) { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue } } + SlotLog "slot files for $id dropped" } catch { SlotLog "slot drop failed: $($_.Exception.Message)" } +} + +# ---------------- restore (after a governor-initiated load) ---------------- +# Cheap check on the governor thread: is a restore even possible? Returns the sidecar or $null (and logs why not). +function SlotRestorePlan($s, $id, $modelPath, $kvNow = $null) { + if (-not $s) { return $null } + $fn = SlotFilename $id; if (-not $fn) { return $null } + $bin = SlotSafePath $s.dir $fn + $exists = [bool]($bin -and (Test-Path -LiteralPath $bin)) + $sc = SlotReadSidecar $s.dir $id + $d = SlotRestoreDecision $sc $exists $modelPath ([int]::MaxValue) (SlotModelStat $modelPath) $s.headroom $kvNow # ctx is unknown until the new server is up + if (-not $d.ok) { SlotLog "RESTORE skipped ($($d.reason))"; return $null } + return $sc +} +# Runs in a background job (Start-Job) so the governor loop never blocks. Guaranteed order: load -> /health ok -> restore -> (1-token 'hi' only if no restore). +# $p: swap, key, id, port, model_path, dir, headroom, log +function SlotWarmFlow($p) { + $script:SlotLogPath = $p.log + $hdr = @{ Authorization = "Bearer $($p.key)" } + $base = "http://127.0.0.1:$($p.port)" + $deadline = (Get-Date).AddSeconds(120) + $healthy = $false; $restored = $false; $skipHi = $false; $trigOk = $false + SlotSetPhase $p 'loading' # phase.json -> status.json `phase` for the Control Centre (only when $p.phase_file is set) + # 1) load the model WITHOUT running inference: llama-swap starts the upstream and proxies /health once it answers + try { Invoke-WebRequest -Uri "$($p.swap)/upstream/$($p.id)/health" -Headers $hdr -UseBasicParsing -TimeoutSec 120 | Out-Null; $trigOk = $true } + catch { SlotLog "RESTORE: load trigger failed ($($_.Exception.Message))" } + # 2) wait for the server's own /health ok (up to 120 s from the start); if the trigger failed, one look only + do { + try { $h = Invoke-RestMethod -Uri "${base}/health" -TimeoutSec 3; if ($h.status -eq 'ok') { $healthy = $true; break } } catch {} + if (-not $trigOk) { break } + Start-Sleep -Seconds 2 + } while ((Get-Date) -lt $deadline) + if (-not $healthy) { SlotLog 'RESTORE skipped (server not healthy within 120 s); sending the normal warm-up' } + else { + # 3) restore, unless a user request already got into the slot while the model was loading + $ctx = $null; try { $ctx = [int](Invoke-RestMethod -Uri "${base}/props" -TimeoutSec 5).default_generation_settings.n_ctx } catch {} + $slot = SlotGetSlot $base + $gate = SlotRestoreTargetOk $slot + if (-not $gate.ok) { SlotLog "RESTORE skipped ($($gate.reason))"; $skipHi = $true } # slot is in use: no restore and no 'hi' either + else { + $fn = SlotFilename $p.id; $bin = SlotSafePath $p.dir $fn + $sc = SlotReadSidecar $p.dir $p.id + $kvNow = $null; try { $rj = Get-Content -LiteralPath (Join-Path (Split-Path -Parent $p.log) 'running.json') -Raw | ConvertFrom-Json; if ($rj.ctk) { $kvNow = "$($rj.ctk)/$($rj.ctv)" } } catch {} + $d = SlotRestoreDecision $sc ([bool]($bin -and (Test-Path -LiteralPath $bin))) $p.model_path $ctx (SlotModelStat $p.model_path) $p.headroom $kvNow + if (-not $d.ok) { SlotLog "RESTORE skipped ($($d.reason))" } + else { + SlotSetPhase $p 'restoring' + try { + $sw = [Diagnostics.Stopwatch]::StartNew() + $r = Invoke-RestMethod -Method Post -Uri "${base}/slots/0?action=restore" -Body (@{ filename = $fn } | ConvertTo-Json -Compress) -ContentType 'application/json' -TimeoutSec 60 + $n = [int]$sc.n_tokens; if ($r -and (SlotIsNum $r.n_restored)) { $n = [int]$r.n_restored } + SlotLog "RESTORE $n tokens in $($sw.ElapsedMilliseconds) ms ($($p.id))" + $restored = $true + } catch { SlotLog "RESTORE failed ($($_.Exception.Message)); sending the normal warm-up" } + } + } + } + # 4) the 1-token prompt would overwrite the slot, so it is only for the no-restore case + if (-not $restored -and -not $skipHi) { + SlotSetPhase $p 'warming' + try { + $body = @{ model = $p.id; max_tokens = 1; messages = @(@{ role = 'user'; content = 'hi' }); chat_template_kwargs = @{ enable_thinking = $false } } | ConvertTo-Json -Depth 5 -Compress + Invoke-RestMethod -Method Post -Uri "$($p.swap)/v1/chat/completions" -Headers $hdr -Body $body -ContentType 'application/json' -TimeoutSec 300 | Out-Null + } catch { SlotLog "warm-up request failed ($($_.Exception.Message))" } + } + SlotSetPhase $p 'ready' +} + +# ---------------- for qwen.ps1 ---------------- +function SlotAgeText($min) { + if ($min -lt 90) { return ('{0:F0} min' -f $min) } + if ($min -lt 2880) { return ('{0:F1} h' -f ($min / 60)) } + return ('{0:F1} d' -f ($min / 1440)) +} +function SlotList($d) { + $rows = @() + if (-not (Test-Path -LiteralPath $d)) { return $rows } + foreach ($f in @(Get-ChildItem -LiteralPath $d -File -Filter '*.bin' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending)) { + $id = $f.Name.Substring(0, $f.Name.Length - 4) + $sc = SlotReadSidecar $d $id + $tok = $null; $ctx = $null; $at = $f.LastWriteTime + if ($sc) { + if (SlotIsNum $sc.n_tokens) { $tok = [int]$sc.n_tokens } + if (SlotIsNum $sc.ctx) { $ctx = [int]$sc.ctx } + try { $at = [datetime]$sc.saved_at } catch {} + } + $rows += [pscustomobject]@{ file = $f.Name; gib = [math]::Round($f.Length / 1GB, 2); tokens = $tok; ctx = $ctx; age_min = [math]::Max(0, ((Get-Date) - $at).TotalMinutes); sidecar = [bool]$sc } + } + return $rows +} +# Deletes every *.bin / *.json leaf in $d (nothing else, nothing outside). Returns the number of files removed. +function SlotClear($d) { + $n = 0 + foreach ($f in @(Get-ChildItem -LiteralPath $d -File -ErrorAction SilentlyContinue | ? { $_.Extension -in '.bin', '.json' })) { + $p = SlotSafePath $d $f.Name + if ($p) { try { Remove-Item -LiteralPath $p -Force -ErrorAction Stop; $n++ } catch {} } + } + return $n +} diff --git a/governor/slotpolicy.py b/governor/slotpolicy.py new file mode 100644 index 0000000..59e2179 --- /dev/null +++ b/governor/slotpolicy.py @@ -0,0 +1,433 @@ +"""Slot persistence policy for the Qwen governor (pure functions, no I/O). + +governor/slotlib.ps1 mirrors every function here one to one (CamelCase names with a +Slot prefix, same argument order, same rules and near-identical reason wording). The +unit tests in test_slotpolicy.py pin the behaviour; if you change a rule, change both. +""" + +import re + +GIB = 1024 ** 3 +_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$") + +# Keys llama-server may use for "tokens currently held in the slot", first hit wins. +TOKEN_KEYS = ("n_tokens", "n_past", "n_cache_tokens") + + +def slot_filename(variant_id): + """'.bin', or None when the id could escape the slots dir.""" + if not isinstance(variant_id, str) or not _ID_RE.match(variant_id) or variant_id.startswith("."): + return None + return variant_id + ".bin" + + +def slot_token_count(slot): + """Tokens held by a /slots entry, or None when the build does not report it.""" + if not isinstance(slot, dict): + return None + for k in TOKEN_KEYS: + v = slot.get(k) + if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0: + return int(v) + return None + + +def save_decision(slot, min_tokens): + """Decide whether to save before an unload. Returns (save: bool, reason: str). + + Unknown token count -> save anyway; the caller re-checks n_saved afterwards + (post_save_ok) and discards a too-small result. + """ + if not isinstance(slot, dict): + return False, "no slot info" + if slot.get("is_processing") is True: + return False, "slot busy" + n = slot_token_count(slot) + if n is None: + return True, "n_tokens not reported" + if n < min_tokens: + return False, "n_tokens %d < min_tokens %d" % (n, min_tokens) + return True, "n_tokens %d" % n + + +def post_save_ok(n_saved, min_tokens): + """After the save call: keep the file only when it really holds enough tokens.""" + if not isinstance(n_saved, (int, float)) or isinstance(n_saved, bool): + return False, "save reply has no n_saved" + n = int(n_saved) + if n < min_tokens: + return False, "n_saved %d < min_tokens %d" % (n, min_tokens) + return True, "n_saved %d" % n + + +def _norm_path(p): + return str(p).replace("\\", "/").strip().lower() + + +def unload_gate(slot): + """May the governor unload now? False only when the slot is definitely processing. + + Used before the save (cheap pre-check) and again after it: a request can arrive while + a multi-second save runs, and unloading then would kill it. Returns (ok, reason). + """ + if isinstance(slot, dict) and slot.get("is_processing") is True: + return False, "slot busy" + return True, "slot idle" if isinstance(slot, dict) else "slot state unknown" + + +def _int_or_none(v): + if isinstance(v, bool) or not isinstance(v, (int, float)): + return None + return int(v) + + +def restore_decision(sidecar, bin_exists, model_path, ctx, model_stat, headroom=4096, kv_now=None): + """Decide whether to restore after a governor-initiated load. + + sidecar: dict read from .json or None; ctx: the new server's n_ctx (int or None). + model_stat: (size_bytes, mtime_epoch_seconds) of the model file NOW, or None when it + cannot be read. Same path but a replaced file (re-download, re-quantise) must not be + restored into: size and mtime must both equal what the sidecar recorded. + Returns (restore: bool, reason: str). On True the reason is the token count. + """ + if not bin_exists: + return False, "no slot file" + if not isinstance(sidecar, dict): + return False, "no sidecar" + n = sidecar.get("n_tokens") + if not isinstance(n, (int, float)) or isinstance(n, bool) or n <= 0: + return False, "sidecar has no n_tokens" + n = int(n) + saved_model = sidecar.get("model_path") + if not saved_model or not model_path or _norm_path(saved_model) != _norm_path(model_path): + return False, "model_path mismatch" + if not model_stat: + return False, "model file stat unavailable" + s_size, s_mtime = _int_or_none(sidecar.get("model_size")), _int_or_none(sidecar.get("model_mtime")) + if s_size is None or s_mtime is None: + return False, "sidecar has no model size/mtime" + if s_size != _int_or_none(model_stat[0]) or s_mtime != _int_or_none(model_stat[1]): + return False, "model file changed (size/mtime differ)" + # a slot saved with one KV type (f16) cannot be restored into another (q8_0): refuse when both sides are known and differ + skv = sidecar.get("kv") + if isinstance(skv, str) and isinstance(kv_now, str) and skv.lower() != kv_now.lower(): + return False, "kv type changed (%s -> %s)" % (skv, kv_now) + if not isinstance(ctx, (int, float)) or isinstance(ctx, bool) or ctx <= 0: + return False, "new ctx unknown" + ctx = int(ctx) + if ctx < n + headroom: + return False, "ctx %d < n_tokens %d + %d" % (ctx, n, headroom) + return True, "n_tokens %d" % n + + +def restore_target_ok(slot): + """Right after the load: is the fresh slot still ours to restore into? + + A user request that queued behind the load may already hold the slot or have filled it; + restoring (or sending the 1-token warm-up) would clobber it. Returns (ok, reason). + Unknown slot state -> ok (a server that just became healthy is empty in practice). + """ + if not isinstance(slot, dict): + return True, "slot state unknown" + if slot.get("is_processing") is True: + return False, "slot busy (a request is already running)" + n = slot_token_count(slot) + if n is not None and n > 0: + return False, "slot not empty (%d tokens)" % n + return True, "slot empty" + + +def prune_selection(entries, max_files, max_gib, managed_ids=None): + """Names to delete so the slots dir holds at most max_files and max_gib. + + entries: iterable of dicts {name, size (bytes), mtime (epoch seconds)}. + A 'unit' is .bin plus .json (the sidecar); max_files counts units. + Deleted, in this order of certainty: + 1. *.tmp.bin (an interrupted save) and orphans (bin without sidecar, sidecar without bin) + 2. oldest complete units until count <= max_files and total size <= max_gib + Only *.bin / *.json files whose stem is in managed_ids (when given) are ever + considered; everything else is ignored, so the caller can never delete a stranger. + """ + max_bytes = float(max_gib) * GIB + delete = [] + units = {} + for e in entries: + name = e.get("name", "") + if "/" in name or "\\" in name or not name: + continue # leaf names only + if name.endswith(".tmp.bin"): + stem, kind = name[: -len(".tmp.bin")], "tmp" + elif name.endswith(".bin"): + stem, kind = name[: -len(".bin")], "bin" + elif name.endswith(".json"): + stem, kind = name[: -len(".json")], "json" + else: + continue + if managed_ids is not None and stem not in managed_ids: + continue + if kind == "tmp": + delete.append(name) + continue + u = units.setdefault(stem, {}) + u[kind] = e + + complete = [] + for stem, u in units.items(): + if "bin" in u and "json" in u: + size = float(u["bin"].get("size", 0)) + float(u["json"].get("size", 0)) + mtime = max(float(u["bin"].get("mtime", 0)), float(u["json"].get("mtime", 0))) + complete.append((mtime, stem, size)) + else: + for e in u.values(): + delete.append(e["name"]) + + complete.sort(key=lambda t: (t[0], t[1])) # oldest first + count = len(complete) + total = sum(t[2] for t in complete) + i = 0 + while i < len(complete) and (count > max_files or total > max_bytes): + mtime, stem, size = complete[i] + delete.extend([stem + ".bin", stem + ".json"]) + count -= 1 + total -= size + i += 1 + return delete + + +def hygiene_decision(loaded_min, quiet_min, processing, interval_hours, since_last_min, + min_quiet_min=10, cooldown_min=30): + """Scheduled restart: loaded longer than interval_hours AND quiet longer than min_quiet_min. + + interval_hours <= 0 disables. Returns (due: bool, reason: str). + cooldown_min stops a failed unload from retriggering every sample. + """ + if not interval_hours or interval_hours <= 0: + return False, "disabled" + if processing: + return False, "busy" + if loaded_min is None: + return False, "load time unknown" + if loaded_min < interval_hours * 60: + return False, "loaded %.0f min < %.0f min" % (loaded_min, interval_hours * 60) + if quiet_min <= min_quiet_min: + return False, "quiet %.1f min <= %d min" % (quiet_min, min_quiet_min) + if since_last_min is not None and since_last_min < cooldown_min: + return False, "cooldown" + return True, "loaded %.1f h, quiet %.1f min" % (loaded_min / 60.0, quiet_min) + + +def empty_reply_step(prev_prompt, prev_pred, prompt, pred, processing, count): + """Cheap empty-reply detector over llama-server /metrics counters. + + /metrics has no per-request completion counter, so this is a heuristic over one + sampling interval: prompt_tokens_total grew while tokens_predicted_total did not and + nothing is processing now -> a request finished (or was aborted) with zero predicted + tokens. Any interval that predicted tokens resets the run. Returns the new count. + A counter that went backwards means the server restarted: reset. + The caller advances its baseline (prev_*) only on samples where nothing is processing, + so a request spanning several samples is judged once, when it has finished. + """ + if None in (prev_prompt, prev_pred, prompt, pred): + return 0 + if prompt < prev_prompt or pred < prev_pred: + return 0 + if processing: + return count + d_pred = pred - prev_pred + d_prompt = prompt - prev_prompt + if d_pred > 0: + return 0 + if d_prompt > 0: + return count + 1 + return count + + +# --------------------------------------------------------------------------------------------- +# Control Centre levers (docs/REMOTE-GUI-SPEC.md section 6.4): request.json, phases, VRAM bands. +# slotlib.ps1 mirrors these as SlotRequestTime / SlotRequestDecision / SlotRequestPlan / +# SlotPhaseDecide / SlotVramBands. Change a rule in both places. +# --------------------------------------------------------------------------------------------- +import datetime as _dt + +REQUEST_ACTIONS = ("load", "unload", "restore", "mode") +REQUEST_ALIASES = {"reload": "restore"} # 6.4 names the GUI button "reload"; the governor's word is "restore" +REQUEST_MODES = ("AUTO", "MAX", "BALANCED", "LEAN", "OFF") +REQUEST_MAX_AGE_SEC = 60 +REQUEST_FUTURE_SKEW_SEC = 5 +REQUEST_MAX_BYTES = 4096 + +ACTIVE_PHASES = ("loading", "restoring", "warming") +ALL_PHASES = ("loading", "restoring", "warming", "ready", "unloading", "postponed-busy", "stopped") +POSTPONE_HOLD_SEC = 30 # how long 'postponed-busy' stays visible after a refused unload +JOB_PHASE_MAX_SEC = 180 # a warm-up job phase older than this is a dead job's leftover +UNLOAD_SHOW_SEC = 10 # 'unloading' is shown for the sample in which the unload happened +PREWARM_SHOW_SEC = 30 # curl-style warm-up (no restore job): 'warming' while its request runs + + +def request_time(t): + """Epoch seconds (float) of a request's `t`, or None. Accepts epoch seconds (or ms), or an ISO 8601 + string (naive strings count as UTC). Bools and everything else are rejected.""" + if isinstance(t, bool): + return None + if isinstance(t, (int, float)): + if t != t or t <= 0: + return None + return float(t) / 1000.0 if t >= 1e11 else float(t) + if isinstance(t, str): + s = t.strip() + if not re.match(r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}", s): + return None + try: + d = _dt.datetime.fromisoformat(s.replace("Z", "+00:00")) + except ValueError: + return None + if d.tzinfo is None: + d = d.replace(tzinfo=_dt.timezone.utc) + return d.timestamp() + return None + + +def request_decision(req, now, max_age=REQUEST_MAX_AGE_SEC): + """Validate a parsed request.json. Returns (ok, action, arg, reason). + + action is one of REQUEST_ACTIONS ('reload' is mapped to 'restore'); arg is the mode name for + action 'mode', else None. Anything else is refused: the file is never a way to run code. + A request older than max_age seconds (or dated in the future beyond a small skew) is stale. + """ + if not isinstance(req, dict): + return False, None, None, "not a JSON object" + a = req.get("action") + if not isinstance(a, str): + return False, None, None, "no action" + a = REQUEST_ALIASES.get(a.strip().lower(), a.strip().lower()) + if a not in REQUEST_ACTIONS: + return False, None, None, "action not allowed" + t = request_time(req.get("t")) + if t is None: + return False, None, None, "no usable timestamp" + age = now - t + if age > max_age: + return False, None, None, "stale request (%d s old, limit %d s)" % (age, max_age) + if age < -REQUEST_FUTURE_SKEW_SEC: + return False, None, None, "request dated in the future" + arg = None + if a == "mode": + m = req.get("mode") + m = m.strip().upper() if isinstance(m, str) else None + if m not in REQUEST_MODES: + return False, None, None, "mode not allowed" + arg = m + return True, a, arg, "ok" + + +def request_plan(action, loaded, state, processing, mode, other_running=False): + """What the governor does with a valid request. Returns (plan, reason); plan is one of + 'set-mode' | 'prewarm' | 'unload' | 'unload-then-prewarm' | 'postpone' | 'noop'. + + 'postpone' = refused because a request is running ("never while busy"): phase 'postponed-busy'. + A load or restore never runs while mode is OFF (the loop would unload it again), nor over a + different model, nor while llama-swap is down or already starting the model. + """ + if action == "mode": + return "set-mode", "ok" + if state in ("swap-down", "api-error"): + return "noop", "llama-swap not answering" + if state == "starting": + return "noop", "model is already loading" + if action == "load": + if loaded: + return "noop", "already loaded" + if mode == "OFF": + return "noop", "mode OFF" + if other_running: + return "noop", "another model is running" + return "prewarm", "load" + if action == "restore": + if mode == "OFF": + return "noop", "mode OFF" + if not loaded: + return ("noop", "another model is running") if other_running else ("prewarm", "load with restore") + if processing: + return "postpone", "a request is running" + return "unload-then-prewarm", "save, unload, reload with restore" + if action == "unload": + if not loaded: + return "noop", "not loaded" + if processing: + return "postpone", "a request is running" + return "unload", "unload" + return "noop", "action not allowed" + + +def phase_decide(state, loaded, processing, job_phase=None, job_age=None, unload_age=None, + postponed_age=None, prewarm_age=None): + """The `phase` string for status.json. Ages are seconds since the event, or None if it never happened. + + job_phase/job_age: what the restore warm-up job last wrote to phase.json (loading|restoring|warming|ready). + unload_age: since the governor's last successful unload call; postponed_age: since it refused one because + a request was running; prewarm_age: since it last started a (re)load. + """ + if loaded and postponed_age is not None and postponed_age < POSTPONE_HOLD_SEC: + return "postponed-busy" + if job_phase in ACTIVE_PHASES and job_age is not None and job_age < JOB_PHASE_MAX_SEC: + return job_phase + if state == "starting": + return "loading" + if state == "stopping": + return "unloading" + if (prewarm_age is not None and prewarm_age < PREWARM_SHOW_SEC and + (unload_age is None or prewarm_age <= unload_age)): + if unload_age is not None and unload_age < UNLOAD_SHOW_SEC: + return "loading" # unload then reload in one sample: `loaded` is still the pre-unload value + if not loaded and state == "stopped": + return "loading" # the load was asked for; llama-swap has not reported 'starting' yet + if loaded and processing: + return "warming" # the 1-token warm-up request + if loaded and unload_age is not None and unload_age < UNLOAD_SHOW_SEC: + return "unloading" # the sample in which we unloaded still carries the pre-unload state + return "ready" if loaded else "stopped" + + +def vram_bands(total_gib, used_gib, llama_gib, desktop_gib, n_ctx=None, kv_kib_per_token=None): + """Split the adapter's dedicated VRAM into bands that always sum to total_gib (within rounding). + + total/used: adapter totals; llama: the llama-server processes; desktop: dwm.exe (2.7 GB on the B60 box). + KV is an estimate (n_ctx * kv_kib_per_token) carved out of llama's share; model gets the rest. + Everything else on the adapter is 'other'. If counters overshoot the heap the bands are scaled down. + Returns a dict of GiB values rounded to 2 places plus kv_estimated. + """ + total = max(0.0, float(total_gib)) + used = max(0.0, float(used_gib)) + llama = min(max(0.0, float(llama_gib)), used) + desktop = min(max(0.0, float(desktop_gib)), used - llama) + other = max(0.0, used - llama - desktop) + kv = 0.0 + if llama > 0 and n_ctx and kv_kib_per_token: + kv = min(llama, float(n_ctx) * float(kv_kib_per_token) / 1048576.0) + model = llama - kv + free = max(0.0, total - used) + parts = {"model_gib": model, "kv_gib": kv, "desktop_gib": desktop, "other_gib": other} + s = sum(parts.values()) + if total and s > total: + f = total / s + parts = {k: v * f for k, v in parts.items()} + free = 0.0 + out = {k: round(v, 2) for k, v in parts.items()} + out["free_gib"] = round(free, 2) + out["total_gib"] = round(total, 2) + out["kv_estimated"] = True + return out + + +def preload_items(total_gib, others_gib, base_gib, kv_kib_per_token, ctx, margin_gib): + """Itemised cost of the next load (SlotPreload in slotlib.ps1): base + KV at ctx, and what is left afterwards. + + base_gib is profiles.json `base_gib` (weights, drafter and compute buffers together: the config does not split them). + fits is True when the free VRAM after loading still honours the profile's margin (0.05 GiB tolerance). + """ + kv = float(ctx) * float(kv_kib_per_token) / 1048576.0 + need = float(base_gib) + kv + after = float(total_gib) - float(others_gib) - need + return {"base_gib": round(base_gib, 2), "kv_gib": round(kv, 2), "ctx": int(ctx), "need_gib": round(need, 2), + "others_gib": round(others_gib, 2), "free_after_gib": round(after, 2), "margin_gib": round(margin_gib, 2), + "fits": after >= float(margin_gib) - 0.05} diff --git a/governor/test_ctx.ps1 b/governor/test_ctx.ps1 new file mode 100644 index 0000000..0d2deeb --- /dev/null +++ b/governor/test_ctx.ps1 @@ -0,0 +1,21 @@ +# ctxlab v4.3 checks (run on the PC): the patched files only count OUR llama-server, and the profile edit is in place. +param([string]$Dir = (Split-Path -Parent $MyInvocation.MyCommand.Path)) +$fail = 0 +function Check($name, $ok) { if ($ok) { "PASS $name" } else { "FAIL $name"; $script:fail++ } } +$g = Get-Content "$Dir\governor.ps1" -Raw; $l = Get-Content "$Dir\launch.ps1" -Raw; $p = Get-Content "$Dir\profiles.json" -Raw | ConvertFrom-Json +Check 'governor ProcIds filters llama-server by C:\AI\llama.cpp path' ($g -match "notlike 'C:\\AI\\llama\.cpp\\\*'") +Check 'launch.ps1 waits only for OurServers' (($l -match 'function OurServers') -and ($l -notmatch 'while \(\$waited -lt 45 -and @\(Get-Process llama-server')) +Check 'BALANCED margin 2.5 (18 Oct shared-memory finding)' ($p.profiles.BALANCED.free_margin_gib -eq 2.5) +Check 'default variant keeps f16 KV' ($p.variants.default.ctk -eq 'f16' -and $p.variants.default.ctv -eq 'f16') +Check 'default keeps drafter + -ub 256' ((($p.variants.default.extra_args) -join ' ') -match 'draft-dflash.*-ub 256') +# behavioural: ProcIds must drop a llama-server.exe outside C:\AI\llama.cpp (simulate with a fake Get-Process) +$ast = [System.Management.Automation.Language.Parser]::ParseInput($g, [ref]$null, [ref]$null) +$fn = $ast.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'ProcIds' }, $true) +$sb = [scriptblock]::Create($fn.Extent.Text) # whole function via the AST (a fixed line count broke when comments were added) +function Attempt([scriptblock]$b) { try { @{ ok = $true; value = (& $b) } } catch { @{ ok = $false } } } +function Get-Process { param($Name, $ErrorAction) @([pscustomobject]@{ Id = 1; Path = 'C:\Apps\Ollama\lib\ollama\llama-server.exe' }, [pscustomobject]@{ Id = 2; Path = 'C:\AI\llama.cpp\vulkan-intelfa\llama-server.exe' }) } +. $sb +$ids = ProcIds 'llama-server' +Check 'ProcIds returns only the C:\AI\llama.cpp pid' (($ids.Count -eq 1) -and ($ids[0] -eq 2)) +Check 'ProcIds still returns every pid for other names' ((ProcIds 'codex').Count -eq 2) +if ($fail) { "FAILED: $fail"; exit 1 } else { "ALL PASS"; exit 0 } diff --git a/governor/test_governor.ps1 b/governor/test_governor.ps1 new file mode 100644 index 0000000..268f397 --- /dev/null +++ b/governor/test_governor.ps1 @@ -0,0 +1,257 @@ +# Plain-assert tests for the governor's pure decision functions (no Pester needed; Windows PowerShell 5.1 or pwsh 7). +# powershell -NoProfile -ExecutionPolicy Bypass -File C:\AI\governor\test_governor.ps1 +# 1) parse-checks every .ps1 next to this file, 2) loads governor.ps1 -FunctionsOnly, 3) replays the same +# scenarios as test_govpolicy.py (taken from real governor.log lines) and 4) proves the needLog fix. +$ErrorActionPreference = 'Stop' +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +$fails = 0; $passes = 0 +function Check($name, $cond) { if ($cond) { $script:passes++; "ok $name" } else { $script:fails++; "FAIL $name" } } + +# ---- 1) parse check ---- +foreach ($f in Get-ChildItem -LiteralPath $here -Filter '*.ps1') { + $tokens = $null; $errors = $null + [System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$tokens, [ref]$errors) | Out-Null + Check "parse $($f.Name)" ($errors.Count -eq 0) + foreach ($e in $errors) { " line $($e.Extent.StartLineNumber): $($e.Message)" } + $src = Get-Content -LiteralPath $f.FullName -Raw + Check "no PS7-only operators in $($f.Name)" (([regex]::Matches($src, '\?\?|\?\.')).Count -eq 0) +} + +# ---- 2) load the pure functions ---- +. (Join-Path $here 'governor.ps1') -FunctionsOnly +$ErrorActionPreference = 'Stop' +# Everything the functions under test log goes to a temp dir, never to C:\AI\governor\governor.log +$tmpRoot = $env:TEMP; if (-not $tmpRoot) { $tmpRoot = [IO.Path]::GetTempPath() } +$dir = Join-Path $tmpRoot ('qwen-governor-tests-' + [System.Diagnostics.Process]::GetCurrentProcess().Id) +New-Item -ItemType Directory -Force -Path $dir | Out-Null +$testLog = Join-Path $dir 'governor.log' +Check "tests log to temp dir ($dir), not production" ($dir -notlike 'C:\AI\governor*') +$TOTAL = 23.88 +$AUTO = [pscustomobject]@{ idle_for_max_sec = 600; ram_floor_gb = 3.5; ram_for_max_gb = 8.0; others_vram_lean_gib = 3.5; others_vram_max_gib = 3.0 } +function BaseState { param([hashtable]$o = @{}) + $s = @{ mode = 'AUTO'; loaded = $true; state = 'ready'; in_flight = $false; quiet_sec = 200; pressure_count = 0; sample_sec = 15; persist_sec = 60 + committed = 'MAX'; loaded_profile = 'MAX'; idle_unload_min = 0; since_refit_min = 60; refit_interval_min = 15; since_prewarm_min = 60; prewarm_cooldown_min = 10 + cur_id = 'qwen3.8-27b'; emergency = $false; agent_active = $false; other_running = $null; free_gib = 1.35; ram_gb = 12.0; free_threshold = 1.1; ram_critical = 1.5 + quiet_before_reload_sec = 120; max_upgrade_quiet_min = 20 } + foreach ($k in $o.Keys) { $s[$k] = $o[$k] }; return $s } + +# ---- 3a) the needLog bug (governor.ps1:147 in v3): piping $null runs the filter once with $_ = $null ---- +$threw = $false +try { $null | ForEach-Object { $_[0] } | Out-Null } catch { $threw = $true } +Check 'v3 line 147 reproduces: $null[0] inside a pipeline throws "Cannot index into a null array"' $threw +$ok = $true +try { $needLog = @(); $now = Get-Date; $keep = @(); foreach ($e in @($needLog)) { if (($null -ne $e) -and (($now - $e.t).TotalMinutes -le 60)) { $keep += $e } }; $needLog = $keep } catch { $ok = $false } +Check 'v4 needLog filter is safe on an empty list' ($ok -and $needLog.Count -eq 0) + +# ---- 3b) VRAM validation against real log lines ---- +$last = [ordered]@{ used = 22.5; free = 1.38; llama = 21.0; others = 1.5; ok = $true } +$r = GovValidateVram 0.0 21.0 $TOTAL $true $true $last 0 +Check '2026-10-10T22:38:26 adapter 0 while loaded -> rejected, last good kept' (($r.m.ok -eq $false) -and ($r.m.free -eq 1.38)) +Check ' and it is no pressure' ((GovPressureStep 0 $r.m.free 12.0 $r.m.ok $true 1.1 1.5 1.5 1.5) -eq 0) +$ram = GovValidateRam 0.0 16.9 +Check 'RAM 0 is an invalid sample, not an empty machine' (($ram.ok -eq $false) -and ($ram.gb -eq 16.9)) +Check 'invalid RAM never counts as pressure' ((GovPressureStep 3 23.88 $ram.gb $false $ram.ok 1.1 1.5 1.5 1.5) -eq 0) +$last = [ordered]@{ used = 21.6; free = 2.28; llama = 21.2; others = 0.44; ok = $true } +$r = GovValidateVram 21.33 0.0 $TOTAL $false $true $last 0 $true +Check '2026-10-11T08:34:33 others 21.33 while starting -> last good 0.44' (($r.m.others -eq 0.44) -and ($r.m.ok -eq $false)) +Check ' profile choice is not LEAN' ((GovProfileChoice 'AUTO' 37527 18.69 $true $r.m.others $r.m.ok 0 $AUTO) -ne 'LEAN') +$last = [ordered]@{ used = 21.5; free = 2.38; llama = 21.2; others = 0.3; ok = $true } +$r = GovValidateVram 21.5 6.5 $TOTAL $true $true $last 0 +Check '2026-10-11T08:58:55 process counter lag -> others kept at 0.3, suspect=1' (($r.m.ok -eq $false) -and ($r.m.others -eq 0.3) -and ($r.suspect -eq 1)) +$sc = $r.suspect +for ($i = 1; $i -lt 4; $i++) { $r = GovValidateVram 21.5 16.0 $TOTAL $true $true $last $sc; $sc = $r.suspect } +Check ' a real change is accepted after 4 samples' (($r.m.ok -eq $true) -and ($r.m.others -eq 5.5) -and ($sc -eq 0)) +$r = GovValidateVram 20.0 21.16 $TOTAL $true $true $null 0 +Check '2026-10-11T09:17:48 negative others clamped' (($r.m.others -ge 0) -and ($r.m.llama -le $r.m.used)) +$r = GovValidateVram 2.87 $null $TOTAL $false $false $null 0 +Check '2026-10-15T23:17:21 desktop alone = others 2.87' (($r.m.others -eq 2.87) -and ($r.m.llama -eq 0) -and $r.m.ok) +$r = GovValidateVram $null $null $TOTAL $false $false $null 0 +Check 'adapter None without history -> degraded, free is $null (not 23.88)' (($r.m.ok -eq $false) -and ($null -eq $r.m.free)) +Check ' $null free never counts as pressure (PS: $null -lt 1.1 is TRUE, so this matters)' ((GovPressureStep 2 $r.m.free $null $r.m.ok $false 1.1 1.5 $null $null) -eq 0) + +# ---- 3c) hysteresis, baseline rule (2026-10-16) and rate limit ---- +function P($c, $free, $others, $base) { GovPressureStep $c $free 9.0 $true $true 1.1 1.5 $others $base 0.5 0.25 } +# 2026-10-16 live v4.0: v3-launched ctx 40960 f16, others 2.62 -> adapter 23.23/23.88, free 0.65 -> re-fit onto its own footprint every 15 min +$c = 0; for ($i = 0; $i -lt 10; $i++) { $c = P $c 0.65 2.62 2.62 } +Check '2026-10-16 own footprint (free 0.65, others unchanged) is never pressure' ($c -eq 0) +Check ' no baseline yet -> low free alone never counts' ((P 3 0.65 2.62 $null) -eq 0) +Check ' growth 0.3 < 0.5 is not pressure' ((P 0 0.65 2.92 2.62) -eq 0) +$c = 0; for ($i = 0; $i -lt 4; $i++) { $c = P $c 0.65 3.22 2.62 } +$d = GovDecide (BaseState @{ free_gib = 0.65; pressure_count = $c; others_gib = 3.22; baseline_others = 2.62 }) +Check ' others +0.60 since baseline for 60 s -> refit, reason says so' (($c -eq 4) -and ($d.action -eq 'refit') -and ($d.reason -like '*+0.60 GiB since baseline 2.62*')) +Check ' hard floor 0.25 always counts' ((P 0 0.20 2.62 2.62) -eq 1) +Check ' hard floor named in the reason' ((GovPressureReason 0.20 9.0 1.1 1.5 2.62 2.62) -like '*hard floor*') +$c = P 0 0.63 3.3 2.5 +$d = GovDecide (BaseState @{ free_gib = 0.63; pressure_count = $c }) +Check '2026-10-12T15:01:40 one low sample does not re-fit' (($c -eq 1) -and ($d.action -eq 'none')) +$c = 0; for ($i = 0; $i -lt 4; $i++) { $c = P $c 0.63 3.3 2.5 } +$d = GovDecide (BaseState @{ free_gib = 0.63; pressure_count = $c; since_refit_min = 60; others_gib = 3.3; baseline_others = 2.5 }) +Check 'pressure for 60 s -> refit, reason names the real trigger' (($d.action -eq 'refit') -and ($d.reason -like 'free VRAM 0.63*60s*')) +$d = GovDecide (BaseState @{ free_gib = 0.63; pressure_count = $c; since_refit_min = 3 }) +Check 'second re-fit within 15 min is rate-limited' (($d.action -eq 'none') -and ($d.reason -like '*rate-limited*')) +$d = GovDecide (BaseState @{ free_gib = 0.63; pressure_count = $c; since_refit_min = 15; refit_blocked = $true }) +Check 'a re-fit that would repeat the same ctx is blocked' (($d.action -eq 'none') -and ($d.reason -like '*repeat the same ctx*')) +Check 'repeat guard: same ctx, others unchanged -> blocked' (GovRefitRepeatBlocked 40960 40960 2.62 2.62) +Check 'repeat guard: one step counts as the same' (GovRefitRepeatBlocked 40960 36864 2.62 2.62) +Check 'repeat guard: a real ctx change is not blocked' (-not (GovRefitRepeatBlocked 40960 24576 2.62 2.62)) +Check 'repeat guard: others changed -> allowed again' (-not (GovRefitRepeatBlocked 40960 40960 3.3 2.62)) +$b = GovBaselineReady $true $true $true 40960 0 +$b2 = GovBaselineReady $true $true $true 40960 $b.count +Check 'baseline taken on the 2nd stable sample' ((-not $b.take) -and $b2.take -and ($b2.count -eq 2)) +Check 'baseline resets on an invalid or inferred sample' (((GovBaselineReady $true $false $true 40960 5).count -eq 0) -and ((GovBaselineReady $true $true $false 40960 5).count -eq 0)) +# calibration with today's numbers: predicted 17.15 + 40960*64.5/1MiB = 19.67, measured 23.23 - 2.62 = 20.61 +$cal = GovCalibrate $null (23.23 - 2.62) 17.15 40960 64.5 +Check 'calibration: delta +0.94 learned' (($cal.predicted -eq 19.67) -and ($cal.delta -eq 0.94) -and ($cal.overhead -eq 0.94)) +Check 'calibration: EMA' ((GovCalibrate $cal.overhead 20.21 17.15 40960 64.5).overhead -eq 0.74) +Check 'calibration: clamps' (((GovCalibrate $null 30.0 17.15 40960 64.5).overhead -eq 1.5) -and ((GovCalibrate $null 10.0 17.15 40960 64.5).overhead -eq -0.5)) +$oh = GovLaunchOverhead ([pscustomobject]@{ overhead_gib = $cal.overhead }) +Check 'launch overhead: positive part only, off switch honoured' (($oh -eq 0.94) -and ((GovLaunchOverhead ([pscustomobject]@{ overhead_gib = -0.3 })) -eq 0.0) -and ((GovLaunchOverhead ([pscustomobject]@{ overhead_gib = 0.94 }) $false) -eq 0.0) -and ((GovLaunchOverhead $null) -eq 0.0)) +$ctxCal = GovFitCtx $TOTAL 1.5 2.62 17.15 64.5 32768 65536 $oh +$freeAfter = [math]::Round($TOTAL - 2.62 - (GovPredictedLlamaGib 17.15 $ctxCal 64.5 $oh), 2) +Check "calibrated fit for today's launch: ctx $ctxCal (ctx_min), free lands at $freeAfter GiB" (($ctxCal -eq 32768) -and ($freeAfter -ge 1.1) -and ($freeAfter -le 1.3)) +Check 'uncalibrated fit reproduces the 40960 that left 0.65 free' ((GovFitCtx $TOTAL 1.5 2.62 17.15 64.5 32768 65536) -eq 40960) +Check 'idle PC still gets 65536 with the overhead' ((GovFitCtx $TOTAL 1.35 0.14 17.15 64.5 32768 65536 $oh) -eq 65536) +Check 'a good sample resets the counter' ((GovPressureStep 3 1.4 9.0 $true $true 1.1 1.5 3.3 2.5) -eq 0) +Check 'reason: RAM trigger is named, not blamed on VRAM' ((GovPressureReason 23.88 1.2 1.1 1.5) -eq 'RAM 1.20 GB < 1.50') +$d = GovDecide (BaseState @{ free_gib = 0.3; pressure_count = 8; in_flight = $true }) +Check 'never unload in flight' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ free_gib = 0.3; pressure_count = 8; in_flight = $null }) +Check 'unknown slot state -> no optional reload' (($d.action -eq 'none') -and ($d.reason -eq 'slot state unknown')) +$d = GovDecide (BaseState @{ mode = 'OFF'; in_flight = $true }) +Check 'mode OFF still waits for the request' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ free_gib = 0.5; pressure_count = 8; cur_id = 'qwen3.8-27b-long' }) +Check 'LONG variant never re-fit' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ free_gib = 0.5; pressure_count = 8; committed = 'LEAN'; loaded_profile = 'LEAN' }) +Check 'LEAN + persistent pressure -> unload' ($d.action -eq 'unload') + +# ---- 3d) agent clients ---- +$d = GovDecide (BaseState @{ committed = 'LEAN'; loaded_profile = 'LEAN'; idle_unload_min = 5; quiet_sec = 400; agent_active = $true }) +Check 'agent active blocks idle unload' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ committed = 'LEAN'; loaded_profile = 'LEAN'; idle_unload_min = 5; quiet_sec = 400; agent_active = $false }) +Check 'no agent -> idle unload as before' ($d.action -eq 'idle-unload') +$d = GovDecide (BaseState @{ loaded = $false; state = 'stopped'; committed = 'BALANCED'; agent_active = $true }) +Check 'agent active + model stopped -> prewarm' ($d.action -eq 'prewarm') +$d = GovDecide (BaseState @{ loaded = $false; state = 'stopped'; committed = 'LEAN'; agent_active = $true }) +Check 'but not under LEAN' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ loaded = $false; state = 'stopped'; committed = 'MAX'; since_prewarm_min = 2 }) +Check 'prewarm cooldown respected' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ loaded_profile = 'BALANCED'; committed = 'MAX'; quiet_sec = 1300; since_refit_min = 10 }) +Check 'upgrade is rate-limited' ($d.action -eq 'none') +$d = GovDecide (BaseState @{ loaded_profile = 'BALANCED'; committed = 'MAX'; quiet_sec = 1300; since_refit_min = 15 }) +Check 'upgrade after 15 min' ($d.action -eq 'upgrade') + +# ---- 3e) ctx formula against real launch lines ---- +Check 'launch 2026-10-11T21:22:19 BALANCED others=1.53 -> 57344' ((GovFitCtx $TOTAL 1.5 1.53 17.15 64.5 32768 65536) -eq 57344) +Check 'launch 2026-10-15T23:17:21 BALANCED others=2.87 -> 36864' ((GovFitCtx $TOTAL 1.5 2.87 17.15 64.5 32768 65536) -eq 36864) +Check 'launch 2026-10-15T10:31:53 MAX others=3.32 -> 32768' ((GovFitCtx $TOTAL 1.35 3.32 17.15 64.5 32768 65536) -eq 32768) +Check 'launch 2026-10-11T12:56:33 MAX others=0.14 -> 65536' ((GovFitCtx $TOTAL 1.35 0.14 17.15 64.5 32768 65536) -eq 65536) +Check 'MAX 61440 needs others <= 1.6 GiB' ((GovFitCtx $TOTAL 1.35 1.6 17.15 64.5 32768 65536) -eq 61440) + +# ---- 3f) profile choice with invalid readings ---- +Check 'invalid ram+others never push LEAN' ((GovProfileChoice 'AUTO' 40000 0.0 $false 21.3 $false 0 $AUTO) -eq 'BALANCED') +Check 'idle PC, good readings -> MAX' ((GovProfileChoice 'AUTO' 40000 20.0 $true 0.4 $true 0 $AUTO) -eq 'MAX') +Check '2026-10-10T08:14:02 ram=2.43 -> LEAN' ((GovProfileChoice 'AUTO' 40000 2.43 $true 1.1 $true 0 $AUTO) -eq 'LEAN') + +# ---- 3g) loop error accounting: first error logged, then counted; state re-initialised after 4 in a row ---- +$script:errStreak = 0; $script:errTotal = 0; $script:heals = 0; $script:pressureCount = 7; $script:lastGoodVram = @{ used = 1 } +$fake = $null; try { throw 'Cannot index into a null array.' } catch { $fake = $_ } +for ($i = 0; $i -lt 4; $i++) { NoteLoopError $fake } +Check '4 consecutive loop errors -> one self-heal, state reset' (($script:heals -eq 1) -and ($script:errStreak -eq 4) -and ($script:pressureCount -eq 0) -and ($null -eq $script:lastGoodVram)) +Check 'last_error carries the message and the line' ($script:lastError -like 'Cannot index into a null array.*line*') +for ($i = 0; $i -lt 36; $i++) { NoteLoopError $fake } +Check 'second self-heal only at 40' ($script:heals -eq 2) +$lg = ''; try { $lg = Get-Content -LiteralPath $testLog -Raw } catch {} +Check 'self-heal lines went to the temp log' (($lg -like '*loop error at line*') -and ($lg -like '*self-heal: state re-initialised after 40*')) + +# ---- 3i) power plan hysteresis (v4.2) ---- +# Replay of governor.log 2026-10-16 08:09-08:40 (v4.1: 104 power changes in 400 lines, e.g. 08:09:31 SAVER -> BALANCED cpu=32.9, +# 08:10:12 -> PERFORMANCE cpu=72.1, 08:11:33 -> SAVER cpu=3.2, 08:11:54 -> BALANCED, 08:12:14 -> PERFORMANCE ... 08:37:20 -> SAVER cpu=1, +# 08:38:22 -> BALANCED). Agent bursts: 2-3 samples >= 70 % CPU every ~2 min, ~3 % between; codex/claude processes alive; model quiet. +$PCFG = [pscustomobject]@{ dwell_min = 10; saver_idle_min = 15; saver_model_quiet_min = 15; perf_model_recent_sec = 120; cpu_busy_pct = 40; cpu_busy_samples = 2; cpu_calm_pct = 25 } +function PowStep($st, $t, $cpu, $idle, $quiet, $busy, $agent, $mode = 'AUTO') { GovPowerDecide $st @{ t = $t; mode = $mode; cpu = $cpu; idle_sec = $idle; quiet_sec = $quiet; model_busy = $busy; agent_active = $agent; cfg = $PCFG } } +$t0 = [datetime]'2026-10-16T08:09:16' +$st = @{ now = 'SAVER'; entered = $t0.AddMinutes(-9); down_since = $null; cpu_busy = 0 } # as v4.1 left it before 08:09:31 +$logged = @{ 15 = 32.9; 60 = 72.1; 135 = 3.2; 1680 = 1.0 } # 08:09:31, 08:10:12, 08:11:33, 08:37:20 from the log, snapped to the 15 s grid +$trans = New-Object System.Collections.ArrayList +$plans = @{} +for ($sec = 15; $sec -le 1860; $sec += 15) { # 08:09:31 .. 08:40:16, 15 s cadence + $cpu = 3.0; if ((($sec % 120) -ge 45) -and (($sec % 120) -lt 90)) { $cpu = 72.0 } # a burst of three samples every two minutes (first one 08:10:01-08:10:31) + if ($logged.ContainsKey($sec)) { $cpu = $logged[$sec] } + $t = $t0.AddSeconds($sec) + $before = $st.now + $r = PowStep $st $t $cpu 30 (1800 + $sec) $false $true + $st = $r.st + if ($r.apply -and $r.apply -ne $before) { [void]$trans.Add(('{0} {1} -> {2} ({3})' -f $t.ToString('HH:mm:ss'), $before, $r.apply, $r.reason)) } + $plans[$sec] = $st.now +} +Check ("replay 08:09-08:40 with agent bursts: at most 2 power transitions (got {0}: {1})" -f $trans.Count, ($trans -join '; ')) ($trans.Count -le 2) +Check ' first step SAVER -> BALANCED at once (agent floor), then -> PERFORMANCE at 08:10:16 on the first sustained burst' (($trans.Count -eq 2) -and ($trans[0] -like '08:09:31 SAVER -> BALANCED (up: agent client active*') -and ($trans[1] -like '08:10:16 BALANCED -> PERFORMANCE (up: cpu 72*')) +Check ' final state after 31 min of bursts is PERFORMANCE (never dropped between bursts: 08:11:33 cpu=3.2 and 08:37:20 cpu=1 stay PERFORMANCE)' ($st.now -eq 'PERFORMANCE' -and $plans[135] -eq 'PERFORMANCE' -and $plans[1680] -eq 'PERFORMANCE') +Check ' transitions carry a reason' (@($trans | Where-Object { $_ -notmatch '\(.+\)$' }).Count -eq 0) +# bursts stop, agent still active: ONE step down to BALANCED after the 10 min dwell, never SAVER while the agent lives +$trans2 = New-Object System.Collections.ArrayList; $tb = $t0.AddSeconds(1860); $downAt = $null +for ($sec = 15; $sec -le 1800; $sec += 15) { + $t = $tb.AddSeconds($sec); $before = $st.now + $r = PowStep $st $t 2.0 (600 + $sec) (3600 + $sec) $false $true + $st = $r.st + if ($r.apply -and $r.apply -ne $before) { [void]$trans2.Add($r.apply); if ($null -eq $downAt) { $downAt = $sec } } +} +Check ("calm 30 min with an agent client: exactly one step down to BALANCED (got {0})" -f ($trans2 -join ',')) ($trans2.Count -eq 1 -and $trans2[0] -eq 'BALANCED' -and $st.now -eq 'BALANCED') +Check (" the step down waited the full 10 min dwell from the first calm sample (at {0} s into the calm window, expected 615 = 15 + 600)" -f $downAt) ($downAt -eq 615) +Check ' the agent floor keeps it off SAVER even though the PC is idle 40 min and the model quiet 90 min' ($st.now -eq 'BALANCED') +# agent gone, PC idle, model quiet: one more step to SAVER after another dwell +$trans3 = New-Object System.Collections.ArrayList; $tc = $tb.AddSeconds(1800); $saverAt = $null +for ($sec = 15; $sec -le 1200; $sec += 15) { + $t = $tc.AddSeconds($sec); $before = $st.now + $r = PowStep $st $t 2.0 (2400 + $sec) (5400 + $sec) $false $false + $st = $r.st + if ($r.apply -and $r.apply -ne $before) { [void]$trans3.Add($r.apply); if ($null -eq $saverAt) { $saverAt = $sec } } +} +Check ("no agent, idle, quiet: one step BALANCED -> SAVER a full dwell after the agent left (got {0} at {1} s, expected 615 = first agent-free sample + 600)" -f ($trans3 -join ','), $saverAt) ($trans3.Count -eq 1 -and $st.now -eq 'SAVER' -and $saverAt -eq 615) +# upgrades are immediate: a request arrives +$r = PowStep $st $tc.AddSeconds(1215) 5.0 3000 0 $true $true +Check 'model busy -> SAVER -> PERFORMANCE on the very next sample' ($r.apply -eq 'PERFORMANCE' -and $r.reason -like 'up: model busy*') +$st = $r.st +# a one-sample CPU spike does not count; the second does +$st2 = @{ now = 'BALANCED'; entered = $t0; down_since = $null; cpu_busy = 0 } +$r = PowStep $st2 $t0.AddSeconds(15) 72.0 30 3000 $false $true +Check 'one 72 % sample: no change (cpu_busy_samples 2)' ($null -eq $r.apply -and $r.st.cpu_busy -eq 1) +$r = PowStep $r.st $t0.AddSeconds(30) 72.0 30 3000 $false $true +Check 'second 72 % sample: PERFORMANCE' ($r.apply -eq 'PERFORMANCE') +# SAVER needs BOTH idle and model-quiet thresholds (15 min), not the old 10/5 +function LowFor30 { return @{ now = 'BALANCED'; entered = $t0.AddMinutes(-30); down_since = $t0.AddMinutes(-30); cpu_busy = 0 } } # fresh state each time: GovPowerDecide mutates it +Check 'idle 20 min but model quiet only 10 min -> no SAVER' ((PowStep (LowFor30) $t0 2.0 1200 600 $false $false).want -eq 'BALANCED') +Check 'model quiet 20 min but idle only 10 min -> no SAVER' ((PowStep (LowFor30) $t0 2.0 600 1200 $false $false).want -eq 'BALANCED') +Check 'idle 16 min + quiet 16 min + calm -> SAVER wanted (and applied: dwell long satisfied)' ((PowStep (LowFor30) $t0 2.0 960 960 $false $false).apply -eq 'SAVER') +Check 'idle 16 min + quiet 16 min but CPU 30 % -> no SAVER' ((PowStep (LowFor30) $t0 30.0 960 960 $false $false).want -eq 'BALANCED') +Check 'same but agent active -> BALANCED floor' ((PowStep (@{ now = 'BALANCED'; entered = $t0.AddMinutes(-30); down_since = $null; cpu_busy = 0 }) $t0 2.0 960 960 $false $true).want -eq 'BALANCED') +# a plan held for less than the dwell is never left downward, even if the demand has been low for the dwell +$st4 = @{ now = 'PERFORMANCE'; entered = $t0.AddMinutes(-5); down_since = $t0.AddMinutes(-11); cpu_busy = 0 } +Check 'held 5 min < dwell: no step down yet' ($null -eq (PowStep $st4 $t0 2.0 30 3000 $false $true).apply) +# PERFORMANCE steps to BALANCED first, never straight to SAVER +$st5 = @{ now = 'PERFORMANCE'; entered = $t0.AddMinutes(-20); down_since = $t0.AddMinutes(-12); cpu_busy = 0 } +$r = PowStep $st5 $t0 2.0 2000 2000 $false $false +Check 'PERFORMANCE with SAVER wanted steps to BALANCED first' ($r.want -eq 'SAVER' -and $r.apply -eq 'BALANCED' -and $r.reason -like 'down after 12 min*') +# forced mode (power.txt) still applies immediately, both ways +Check 'power mode SAVER forced while the model is busy -> SAVER now' ((PowStep (@{ now = 'PERFORMANCE'; entered = $t0; down_since = $null; cpu_busy = 0 }) $t0.AddSeconds(15) 90.0 0 0 $true $true 'SAVER').apply -eq 'SAVER') +$ru = PowStep (@{ now = 'BALANCED'; entered = $t0; down_since = $null; cpu_busy = 1 }) $t0 $null 30 3000 $false $true +Check 'unknown CPU is neutral: busy streak neither grows nor resets, no spurious PERFORMANCE' (($null -eq $ru.apply) -and ($ru.st.cpu_busy -eq 1)) +Check 'first sample ever applies the wanted plan (startup)' ((PowStep $null $t0 3.0 30 3000 $false $true).reason -like 'startup:*') +$pj = ReadJsonFile (Join-Path $here 'profiles.json') +Check 'profiles.json carries the power section with dwell 10 / saver 15+15' ($pj.power.dwell_min -eq 10 -and $pj.power.saver_idle_min -eq 15 -and $pj.power.saver_model_quiet_min -eq 15) + +# ---- 3h) slotlib: KV type guard on restore ---- +. (Join-Path $here 'slotlib.ps1') +$script:SlotLogPath = $testLog +$sc = [pscustomobject]@{ n_tokens = 43000; model_path = 'C:/m/x.gguf'; model_size = 1000; model_mtime = 2000; kv = 'f16/f16' } +$stat = [pscustomobject]@{ size = 1000; mtime = 2000 } +Check 'restore allowed: same KV' ((SlotRestoreDecision $sc $true 'C:/m/x.gguf' 65536 $stat 4096 'f16/f16').ok) +Check 'restore refused: KV type changed' (-not (SlotRestoreDecision $sc $true 'C:/m/x.gguf' 65536 $stat 4096 'q8_0/q8_0').ok) +Check 'restore allowed: KV unknown on one side (old sidecar)' ((SlotRestoreDecision $sc $true 'C:/m/x.gguf' 65536 $stat 4096 $null).ok) +Check 'restore refused: ctx too small for the slot' (-not (SlotRestoreDecision $sc $true 'C:/m/x.gguf' 45056 $stat 4096 'f16/f16').ok) +Check 'SlotCfg reads min_free_disk_gib' ((SlotCfg ([pscustomobject]@{ slots = [pscustomobject]@{ enabled = $true; dir = 'C:/AI/cache/slots'; max_files = 3; max_gib = 12; min_tokens = 4096; min_free_disk_gib = 25 }; common_args = @('--slot-save-path', 'C:/AI/cache/slots') })).min_free_disk_gib -eq 25) + +try { Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue } catch {} +"" +"$passes passed, $fails failed" +if ($fails) { exit 1 } diff --git a/governor/test_govpolicy.py b/governor/test_govpolicy.py new file mode 100644 index 0000000..f6972af --- /dev/null +++ b/governor/test_govpolicy.py @@ -0,0 +1,292 @@ +"""pytest tests for govpolicy.py. Every scenario is taken from a real line of C:\\AI\\governor\\governor.log +(2026-10-10 .. 2026-10-15). Run: python3 -m pytest test_govpolicy.py -q +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import govpolicy as g + +TOTAL = 23.88 +AUTO = {"idle_for_max_sec": 600, "ram_floor_gb": 3.5, "ram_for_max_gb": 8.0, + "others_vram_lean_gib": 3.5, "others_vram_max_gib": 3.0} + + +def base_state(**kw): + s = dict(mode="AUTO", loaded=True, state="ready", in_flight=False, quiet_sec=200, pressure_count=0, + sample_sec=15, persist_sec=60, committed="MAX", loaded_profile="MAX", idle_unload_min=0, + since_refit_min=60, refit_interval_min=15, since_prewarm_min=60, prewarm_cooldown_min=10, + cur_id="qwen3.8-27b", emergency=False, agent_active=False, other_running=None, + free_gib=1.35, ram_gb=12.0, free_threshold=1.1, ram_critical=1.5, + quiet_before_reload_sec=120, max_upgrade_quiet_min=20) + s.update(kw) + return s + + +# ---------------- VRAM validation (root cause 2 and 3) ---------------- +def test_log_2026_10_10T22_38_26_adapter_zero_while_loaded_is_rejected(): + # "UNLOAD (free VRAM 23.88 GiB < 1.1 -> re-fit context (MAX))": adapter read 0 B with a 21 GiB model loaded + last = {"used": 22.5, "free": 1.38, "llama": 21.0, "others": 1.5, "ok": True} + m, sc = g.validate_vram(0.0, 21.0, TOTAL, loaded=True, llama_alive=True, last_good=last, suspect_count=0) + assert m["ok"] is False + assert m["free"] == 1.38 # last good kept, not 23.88 + assert any("impossible" in w for w in m["warn"]) + # and it must not count as pressure + assert g.pressure_step(0, m["free"], 12.0, m["ok"], True, 1.1, 1.5) == 0 + + +def test_log_2026_10_10T22_38_26_all_counters_zero_no_pressure(): + # the same sample set also zeroed 'Available MBytes' (ram 0 < floor 3.5 is what really fired $acute) + ram, ok = g.validate_ram(0.0, 16.9) + assert ok is False and ram == 16.9 + assert g.pressure_step(3, 23.88, ram, False, ok, 1.1, 1.5) == 0 + + +def test_log_2026_10_11T08_34_33_others_21_33_while_starting(): + # "profile MAX -> LEAN (othersVRAM=21.33GiB)" two seconds before "launch:" - the old server's VRAM was booked as others + last = {"used": 21.6, "free": 2.28, "llama": 21.2, "others": 0.44, "ok": True} + m, sc = g.validate_vram(21.33, 0.0, TOTAL, loaded=False, llama_alive=True, last_good=last, suspect_count=0, starting=True) + assert m["others"] == 0.44 and m["ok"] is False + assert g.profile_choice("AUTO", 37527, 18.69, True, m["others"], m["ok"], 0, AUTO) != "LEAN" + + +def test_log_2026_10_11T08_58_55_process_counter_lag_on_loaded_model(): + # "profile MAX -> LEAN (ram=11.51GB othersVRAM=14.99GiB)": adapter 21.5, llama process counter 6.5 (lagging) + last = {"used": 21.5, "free": 2.38, "llama": 21.2, "others": 0.3, "ok": True} + m, sc = g.validate_vram(21.5, 6.5, TOTAL, loaded=True, llama_alive=True, last_good=last, suspect_count=0) + assert m["ok"] is False and m["others"] == 0.3 and sc == 1 + # a REAL change (someone opened a 5 GiB app) is accepted after 4 consecutive samples + for i in range(1, 4): + m, sc = g.validate_vram(21.5, 16.0, TOTAL, True, True, last, sc) + assert m["ok"] is True and m["others"] == 5.5 and sc == 0 + + +def test_log_2026_10_11T09_17_48_negative_others_clamped(): + # "profile LEAN -> MAX (othersVRAM=-1.16GiB)" + m, sc = g.validate_vram(20.0, 21.16, TOTAL, loaded=True, llama_alive=True, last_good=None, suspect_count=0) + assert m["others"] >= 0.0 and m["llama"] <= m["used"] + + +def test_process_counter_zero_first_sample_loaded_assumes_model(): + m, sc = g.validate_vram(21.2, 0.0, TOTAL, loaded=True, llama_alive=True, last_good=None, suspect_count=0) + assert m["llama"] == 21.2 and m["others"] == 0.0 and m["ok"] is True + + +def test_not_loaded_no_process_all_is_others(): + # 2026-10-15T23:17:21 launch others=2.87GiB: the desktop alone + m, sc = g.validate_vram(2.87, None, TOTAL, loaded=False, llama_alive=False, last_good=None, suspect_count=0) + assert m["others"] == 2.87 and m["llama"] == 0.0 and m["ok"] is True + + +def test_adapter_none_no_last_good_is_degraded_not_zero(): + m, sc = g.validate_vram(None, None, TOTAL, loaded=False, llama_alive=False, last_good=None, suspect_count=0) + assert m["ok"] is False and m["free"] is None + assert g.pressure_step(2, m["free"], None, m["ok"], False, 1.1, 1.5) == 0 + + +# ---------------- hysteresis and rate limit ---------------- +def P(count, free, others=None, base=None, ram=9.0): + return g.pressure_step(count, free, ram, True, True, 1.1, 1.5, others, base, 0.5, 0.25) + + +def test_log_2026_10_16_own_footprint_is_not_pressure(): + # v4.0 live: v3-launched ctx 40960 f16, others 2.62 -> adapter 23.23/23.88, free 0.65 for ever -> re-fit every 15 min + c = 0 + for _ in range(10): + c = P(c, 0.65, others=2.62, base=2.62) + assert c == 0 + assert g.decide(base_state(free_gib=0.65, pressure_count=c, others_gib=2.62, baseline_others=2.62)) == ("none", "steady") + # no baseline yet (just launched): low free alone never counts + assert P(3, 0.65, others=2.62, base=None) == 0 + # other apps grew by 0.6 GiB: that IS pressure, confirmed after 60 s + c = 0 + for _ in range(4): + c = P(c, 0.65, others=3.22, base=2.62) + assert c == 4 + act, why = g.decide(base_state(free_gib=0.65, pressure_count=c, others_gib=3.22, baseline_others=2.62)) + assert act == "refit" and "+0.60 GiB since baseline 2.62" in why + # hard floor always counts + assert P(0, 0.20, others=2.62, base=2.62) == 1 + assert "hard floor" in g.pressure_reason(0.20, 9.0, 1.1, 1.5, 2.62, 2.62) + # growth of 0.3 is below growth_min + assert P(0, 0.65, others=2.92, base=2.62) == 0 + + +def test_log_2026_10_12T15_01_40_single_low_sample_does_not_refit(): + # "UNLOAD (free VRAM 0.63 GiB < 1.1 ...)" fired on ONE sample in the live code + c = P(0, 0.63, others=3.3, base=2.5) + assert c == 1 + assert g.decide(base_state(free_gib=0.63, pressure_count=c)) == ("none", "steady") + + +def test_pressure_for_60s_then_refit_once_per_15min(): + c = 0 + for _ in range(4): + c = P(c, 0.63, others=3.3, base=2.5) + assert c == 4 + act, why = g.decide(base_state(free_gib=0.63, pressure_count=c, since_refit_min=60, others_gib=3.3, baseline_others=2.5)) + assert act == "refit" and "free VRAM 0.63" in why and "60s" in why + # 2026-10-12T15:04:41 / 15:07:43 / 15:10:45: the live code re-fit every 3 min. Now: rate-limited. + act, why = g.decide(base_state(free_gib=0.63, pressure_count=c, since_refit_min=3)) + assert act == "none" and "rate-limited" in why + act, _ = g.decide(base_state(free_gib=0.63, pressure_count=c, since_refit_min=15)) + assert act == "refit" + # a re-fit that would repeat the same ctx is blocked + act, why = g.decide(base_state(free_gib=0.63, pressure_count=c, since_refit_min=15, refit_blocked=True)) + assert act == "none" and "repeat the same ctx" in why + + +def test_refit_repeat_guard(): + assert g.refit_repeat_blocked(40960, 40960, 2.62, 2.62) is True + assert g.refit_repeat_blocked(40960, 36864, 2.62, 2.62) is True # one step counts as the same + assert g.refit_repeat_blocked(40960, 24576, 2.62, 2.62) is False + assert g.refit_repeat_blocked(40960, 40960, 3.3, 2.62) is False # others changed: allowed again + assert g.refit_repeat_blocked(None, 40960, 2.62, 2.62) is False + + +def test_baseline_ready_needs_two_stable_samples(): + n, take = g.baseline_ready(True, True, True, 40960, 0) + assert (n, take) == (1, False) + n, take = g.baseline_ready(True, True, True, 40960, n) + assert (n, take) == (2, True) + assert g.baseline_ready(True, False, True, 40960, 5) == (0, False) # invalid sample resets + assert g.baseline_ready(True, True, False, 40960, 5) == (0, False) # llama share inferred, not measured + assert g.baseline_ready(False, True, True, 40960, 5) == (0, False) + + +def test_calibration_with_today_numbers(): + # 2026-10-16: launch ctx 40960 f16 others 2.62 -> predicted llama 17.15 + 2.52 = 19.67; adapter 23.23 -> llama 20.61 + over, pred, delta = g.calibrate(None, 23.23 - 2.62, 17.15, 40960, 64.5) + assert pred == 19.67 and delta == 0.94 and over == 0.94 + # EMA on a second, smaller measurement + over2, _, _ = g.calibrate(over, 20.21, 17.15, 40960, 64.5) + assert over2 == 0.74 + # clamps + assert g.calibrate(None, 30.0, 17.15, 40960, 64.5)[0] == 1.5 + assert g.calibrate(None, 10.0, 17.15, 40960, 64.5)[0] == -0.5 + # launch.ps1 applies the learned overhead (never negative) and the next fit lands with free >= margin + oh = g.launch_overhead({"overhead_gib": over}) + assert oh == 0.94 + assert g.launch_overhead({"overhead_gib": -0.3}) == 0.0 + assert g.launch_overhead({"overhead_gib": 0.94}, enabled=False) == 0.0 + assert g.launch_overhead(None) == 0.0 + ctx = g.fit_ctx(TOTAL, 1.5, 2.62, 17.15, 64.5, 32768, 65536, overhead_gib=oh) + assert ctx == 32768 # 1.67 GiB of KV = 24576, lifted to ctx_min + free_after = TOTAL - 2.62 - g.predicted_llama_gib(17.15, ctx, 64.5, oh) + assert 1.1 <= round(free_after, 2) <= 1.3, free_after # 1.15: where the margin wanted it + # without calibration the same inputs reproduce the 40960 that left 0.65 GiB free + assert g.fit_ctx(TOTAL, 1.5, 2.62, 17.15, 64.5, 32768, 65536) == 40960 + # idle PC (others 0.14): still the full 65536 + assert g.fit_ctx(TOTAL, 1.35, 0.14, 17.15, 64.5, 32768, 65536, overhead_gib=oh) == 65536 + assert g.fit_ctx(TOTAL, 1.35, 1.0, 17.15, 64.5, 32768, 65536, overhead_gib=oh) == 53248 + + +def test_pressure_resets_on_a_good_sample(): + c = 3 + c = g.pressure_step(c, 1.4, 9.0, True, True, 1.1, 1.5) + assert c == 0 + + +def test_never_unload_in_flight(): + s = base_state(free_gib=0.3, pressure_count=8, in_flight=True) + assert g.decide(s)[0] == "none" + s = base_state(mode="OFF", in_flight=True) + assert g.decide(s)[0] == "none" + s = base_state(free_gib=0.3, pressure_count=8, in_flight=None) + assert g.decide(s) == ("none", "slot state unknown") + + +def test_pressure_reason_names_the_real_trigger(): + # the live log always said "free VRAM X < 1.1" even when RAM was the trigger + assert g.pressure_reason(23.88, 1.2, 1.1, 1.5) == "RAM 1.20 GB < 1.50" + assert g.pressure_reason(0.7, 12.0, 1.1, 1.5) == "free VRAM 0.70 GiB < 1.10" + + +def test_protected_variants_never_refit(): + s = base_state(free_gib=0.5, pressure_count=8, cur_id="qwen3.8-27b-long") + assert g.decide(s)[0] == "none" + s = base_state(free_gib=0.5, pressure_count=8, emergency=True) + assert g.decide(s)[0] == "none" + s = base_state(free_gib=0.5, pressure_count=8, committed="LEAN", loaded_profile="LEAN") + assert g.decide(s)[0] == "unload" + + +# ---------------- agent clients ---------------- +def test_agent_active_blocks_idle_unload_and_prewarms(): + s = base_state(committed="LEAN", loaded_profile="LEAN", idle_unload_min=5, quiet_sec=400, agent_active=True) + assert g.decide(s)[0] == "none" + s["agent_active"] = False + assert g.decide(s)[0] == "idle-unload" + s = base_state(loaded=False, state="stopped", committed="BALANCED", agent_active=True) + assert g.decide(s) == ("prewarm", "agent client active - keep model warm") + s["agent_active"] = False + assert g.decide(s)[0] == "none" + s = base_state(loaded=False, state="stopped", committed="LEAN", agent_active=True) + assert g.decide(s)[0] == "none" # never pull 21 GiB back in under LEAN pressure + s = base_state(loaded=False, state="stopped", committed="MAX") + assert g.decide(s)[0] == "prewarm" + s["since_prewarm_min"] = 2 + assert g.decide(s)[0] == "none" + s = base_state(loaded=False, state="stopped", committed="MAX", other_running="qwen3.6-35b-a3b") + assert g.decide(s)[0] == "none" + + +def test_upgrades_are_rate_limited_too(): + s = base_state(loaded_profile="BALANCED", committed="MAX", quiet_sec=1300, since_refit_min=10) + assert g.decide(s)[0] == "none" + s["since_refit_min"] = 15 + assert g.decide(s) == ("upgrade", "upgrade BALANCED -> MAX") + s = base_state(loaded_profile="LEAN", committed="BALANCED", quiet_sec=130, since_refit_min=20) + assert g.decide(s) == ("upgrade", "upgrade LEAN -> BALANCED") + + +def test_mode_off(): + assert g.decide(base_state(mode="OFF", quiet_sec=31)) == ("unload", "mode OFF") + assert g.decide(base_state(mode="OFF", quiet_sec=10))[0] == "none" + + +# ---------------- profile choice never acts on invalid readings ---------------- +def test_profile_choice_invalid_readings(): + assert g.profile_choice("AUTO", 40000, 0.0, False, 21.3, False, 0, AUTO) == "BALANCED" + assert g.profile_choice("AUTO", 40000, 20.0, True, 0.4, True, 0, AUTO) == "MAX" + assert g.profile_choice("AUTO", 5, 20.0, True, 0.4, True, 0, AUTO) == "BALANCED" + assert g.profile_choice("AUTO", 40000, 2.4, True, 1.1, True, 0, AUTO) == "LEAN" # 2026-10-10T08:14:02 ram=2.43GB + assert g.profile_choice("LEAN", 0, 20.0, True, 0.4, True, 0, AUTO) == "LEAN" + + +# ---------------- launch.ps1 formulas, checked against real "launch:" lines ---------------- +def test_fit_ctx_matches_logged_launches(): + base, kv = 17.15, 64.5 + # 2026-10-11T21:22:19 launch: profile=BALANCED ctx=57344 others=1.53GiB + assert g.fit_ctx(TOTAL, 1.5, 1.53, base, kv, 32768, 65536) == 57344 + # 2026-10-15T23:17:21 launch: profile=BALANCED ctx=36864 others=2.87GiB + assert g.fit_ctx(TOTAL, 1.5, 2.87, base, kv, 32768, 65536) == 36864 + # 2026-10-15T10:31:53 launch: profile=MAX ctx=32768 others=3.32GiB + assert g.fit_ctx(TOTAL, 1.35, 3.32, base, kv, 32768, 65536) == 32768 + # 2026-10-11T12:56:33 launch: profile=MAX ctx=65536 others=0.14GiB + assert g.fit_ctx(TOTAL, 1.35, 0.14, base, kv, 32768, 65536) == 65536 + # 2026-10-12T14:09:09 launch: profile=BALANCED ctx=49152 others=2.07GiB + assert g.fit_ctx(TOTAL, 1.5, 2.07, base, kv, 32768, 65536) == 49152 + # the f16 ceiling: 61440 needs others <= ~1.6 GiB in MAX + assert g.fit_ctx(TOTAL, 1.35, 1.6, base, kv, 32768, 65536) == 61440 + assert g.fit_ctx(TOTAL, 1.35, 1.9, base, kv, 32768, 65536) == 53248 + + +def test_log_2026_10_11T08_04_36_launch_others_21_24_rejected(): + # "launch: ... ctx=32768 others=21.24GiB": the previous server was still alive after the 15 s wait + o, note = g.launch_others([21.24, 21.2, 21.1], llama_alive=True, status_others=0.43, status_age_sec=20) + assert o == 0.43 and "still alive" in note + o, note = g.launch_others([21.24], llama_alive=True, status_others=None, status_age_sec=None) + assert o == 2.2 + # old server gone, VRAM still draining: the smallest sample wins + o, note = g.launch_others([5.0, 2.9, 2.87], llama_alive=False, status_others=2.69, status_age_sec=30) + assert o == 2.87 and note == "measured" + # implausible without a live server, fresh governor value available + o, note = g.launch_others([12.0, 11.9, 11.9], llama_alive=False, status_others=2.69, status_age_sec=30) + assert o == 2.69 + # stale status (> 120 s) is not used + o, note = g.launch_others([12.0], llama_alive=False, status_others=2.69, status_age_sec=900) + assert o == 12.0 + # counter failed entirely + assert g.launch_others([], False, 2.69, 10)[0] == 2.69 + assert g.launch_others(None, False, None, None)[0] == 2.2 diff --git a/governor/test_slotpolicy.py b/governor/test_slotpolicy.py new file mode 100644 index 0000000..b0b25c8 --- /dev/null +++ b/governor/test_slotpolicy.py @@ -0,0 +1,426 @@ +"""Plain-assert tests for slotpolicy.py. Run: python3 governor/test_slotpolicy.py""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import slotpolicy as sp + +GIB = 1024 ** 3 +MP = "C:/AI/models/qwen3.8-27b/Qwen3.8-27B-UD-Q4_K_M.gguf" + + +def test_filename(): + assert sp.slot_filename("qwen3.8-27b") == "qwen3.8-27b.bin" + assert sp.slot_filename("qwen3.8-27b-long") == "qwen3.8-27b-long.bin" + for bad in ("", "..", "../x", "a/b", "a\\b", ".hidden", None, "x" * 80, "a b"): + assert sp.slot_filename(bad) is None, bad + + +def test_save_decision(): + assert sp.save_decision({"is_processing": False, "n_tokens": 43000}, 4096) == (True, "n_tokens 43000") + assert sp.save_decision({"is_processing": False, "n_tokens": 4096}, 4096)[0] is True # boundary + ok, why = sp.save_decision({"is_processing": False, "n_tokens": 4095}, 4096) + assert not ok and "min_tokens" in why + assert sp.save_decision({"is_processing": True, "n_tokens": 43000}, 4096) == (False, "slot busy") + assert sp.save_decision({"is_processing": False, "n_past": 9000}, 4096)[0] is True # fallback key + assert sp.save_decision({"is_processing": False, "n_tokens": 0}, 4096)[0] is False + # unknown count: save, validate afterwards with n_saved + assert sp.save_decision({"is_processing": False}, 4096) == (True, "n_tokens not reported") + assert sp.save_decision(None, 4096)[0] is False + assert sp.save_decision({"is_processing": False, "n_tokens": True}, 4096)[1] == "n_tokens not reported" + + +def test_post_save_ok(): + assert sp.post_save_ok(43000, 4096)[0] is True + assert sp.post_save_ok(10, 4096)[0] is False + assert sp.post_save_ok(None, 4096)[0] is False + assert sp.post_save_ok(True, 4096)[0] is False + + +MS = (16_900_000_000, 1760000000) # (size, mtime) of the model file now + + +def test_restore_decision_kv_type(): + stat = (1000, 2000) + sc = {"n_tokens": 43000, "model_path": MP, "model_size": 1000, "model_mtime": 2000, "kv": "f16/f16"} + assert sp.restore_decision(sc, True, MP, 65536, stat, kv_now="f16/f16")[0] is True + assert sp.restore_decision(sc, True, MP, 65536, stat, kv_now="F16/F16")[0] is True + ok, why = sp.restore_decision(sc, True, MP, 65536, stat, kv_now="q8_0/q8_0") + assert not ok and "kv type changed" in why + # unknown on either side: no veto (older sidecars have no kv field) + assert sp.restore_decision(sc, True, MP, 65536, stat, kv_now=None)[0] is True + sc2 = dict(sc); del sc2["kv"] + assert sp.restore_decision(sc2, True, MP, 65536, stat, kv_now="q8_0/q8_0")[0] is True + + +def test_restore_decision(): + sc = {"n_tokens": 43000, "ctx": 65536, "saved_at": "2026-10-11T09:00:00", "model_path": MP, + "model_size": MS[0], "model_mtime": MS[1]} + assert sp.restore_decision(sc, True, MP, 65536, MS) == (True, "n_tokens 43000") + assert sp.restore_decision(sc, True, MP, 43000 + 4096, MS)[0] is True # exact boundary + ok, why = sp.restore_decision(sc, True, MP, 43000 + 4095, MS) + assert not ok and why.startswith("ctx ") + assert sp.restore_decision(sc, False, MP, 65536, MS) == (False, "no slot file") + assert sp.restore_decision(None, True, MP, 65536, MS) == (False, "no sidecar") + assert sp.restore_decision("junk", True, MP, 65536, MS) == (False, "no sidecar") + # model swapped under the same variant id (different gguf) + assert sp.restore_decision(sc, True, "C:/AI/models/x/other.gguf", 65536, MS) == (False, "model_path mismatch") + # Windows spelling and case differences are not a mismatch + assert sp.restore_decision(sc, True, MP.replace("/", "\\").upper(), 65536, MS)[0] is True + assert sp.restore_decision(dict(sc, model_path=None), True, MP, 65536, MS)[1] == "model_path mismatch" + assert sp.restore_decision(dict(sc, n_tokens=0), True, MP, 65536, MS)[1] == "sidecar has no n_tokens" + assert sp.restore_decision(dict(sc, n_tokens="43000"), True, MP, 65536, MS)[1] == "sidecar has no n_tokens" + assert sp.restore_decision(sc, True, MP, None, MS) == (False, "new ctx unknown") + # smaller re-fit context than the saved prompt: skip, never truncate + assert sp.restore_decision(sc, True, MP, 32768, MS)[0] is False + # model file replaced under the same path + assert sp.restore_decision(sc, True, MP, 65536, (MS[0] + 1, MS[1])) == (False, "model file changed (size/mtime differ)") + assert sp.restore_decision(sc, True, MP, 65536, (MS[0], MS[1] + 1))[1].startswith("model file changed") + assert sp.restore_decision(sc, True, MP, 65536, None) == (False, "model file stat unavailable") + # old sidecar without size/mtime is not trusted + old = {k: v for k, v in sc.items() if k not in ("model_size", "model_mtime")} + assert sp.restore_decision(old, True, MP, 65536, MS) == (False, "sidecar has no model size/mtime") + assert sp.restore_decision(dict(sc, model_size=None), True, MP, 65536, MS)[0] is False + assert sp.restore_decision(dict(sc, model_mtime="1760000000"), True, MP, 65536, MS)[0] is False + + +def test_unload_gate(): + assert sp.unload_gate({"is_processing": True}) == (False, "slot busy") + assert sp.unload_gate({"is_processing": False})[0] is True + assert sp.unload_gate({})[0] is True + assert sp.unload_gate(None) == (True, "slot state unknown") + + +def test_restore_target_ok(): + f = sp.restore_target_ok + assert f({"is_processing": False, "n_tokens": 0}) == (True, "slot empty") + assert f({"is_processing": False}) == (True, "slot empty") + assert f(None)[0] is True + assert f({"is_processing": True, "n_tokens": 0})[0] is False + ok, why = f({"is_processing": False, "n_tokens": 12}) + assert not ok and "not empty" in why + + +def _e(name, gib, mtime): + return {"name": name, "size": int(gib * GIB), "mtime": mtime} + + +def _unit(stem, gib, mtime): + return [_e(stem + ".bin", gib, mtime), _e(stem + ".json", 0, mtime)] + + +def test_prune_by_count(): + ents = _unit("a", 1, 100) + _unit("b", 1, 200) + _unit("c", 1, 300) + _unit("d", 1, 400) + out = sp.prune_selection(ents, 3, 12) + assert sorted(out) == ["a.bin", "a.json"], out + assert sp.prune_selection(ents, 4, 12) == [] + out = sp.prune_selection(ents, 1, 12) + assert sorted(out) == ["a.bin", "a.json", "b.bin", "b.json", "c.bin", "c.json"] + + +def test_prune_by_size(): + ents = _unit("a", 5, 100) + _unit("b", 5, 200) + _unit("c", 5, 300) + out = sp.prune_selection(ents, 3, 12) # 15 GiB > 12 -> drop oldest (10 GiB left) + assert sorted(out) == ["a.bin", "a.json"], out + out = sp.prune_selection(ents, 3, 4) # even the newest alone is too big: all go + assert sorted(out) == sorted(["a.bin", "a.json", "b.bin", "b.json", "c.bin", "c.json"]) + assert sp.prune_selection(ents, 3, 15) == [] # exactly at the limit is fine + + +def test_prune_tmp_and_orphans(): + ents = _unit("a", 3.4, 100) + [_e("b.tmp.bin", 1.2, 500), _e("c.bin", 2, 50), _e("d.json", 0, 60)] + out = sp.prune_selection(ents, 3, 12) + assert sorted(out) == ["b.tmp.bin", "c.bin", "d.json"], out + + +def test_prune_never_touches_strangers(): + ents = _unit("a", 1, 100) + [_e("notes.txt", 1, 1), _e("sub/evil.bin", 1, 1), _e("..\\x.bin", 1, 1), + _e("mine.bin", 1, 5), _e("mine.json", 0, 5), _e("x.tmp.bin", 1, 1)] + out = sp.prune_selection(ents, 3, 12, managed_ids={"a"}) + assert out == [], out # mine.* and x.tmp.bin are not managed ids + out = sp.prune_selection(ents, 3, 12) # unmanaged mode still ignores .txt and path-like names + assert "notes.txt" not in out and "sub/evil.bin" not in out and "..\\x.bin" not in out + assert "x.tmp.bin" in out + for n in sp.prune_selection(ents, 0, 12): + assert "/" not in n and "\\" not in n and n.endswith((".bin", ".json")) + + +def test_prune_tie_break_is_stable(): + ents = _unit("b", 1, 100) + _unit("a", 1, 100) + assert sorted(sp.prune_selection(ents, 1, 12)) == ["a.bin", "a.json"] + + +def test_hygiene(): + f = sp.hygiene_decision + assert f(400, 15, False, 6, None)[0] is True + assert f(360, 10.5, False, 6, None)[0] is True # boundary: loaded == 6 h + assert f(359, 15, False, 6, None) == (False, "loaded 359 min < 360 min") + assert f(400, 10, False, 6, None)[0] is False # quiet must be MORE than 10 + assert f(400, 9, False, 6, None)[0] is False + assert f(400, 15, True, 6, None) == (False, "busy") + assert f(400, 15, False, 0, None) == (False, "disabled") # 0 disables + assert f(400, 15, False, None, None) == (False, "disabled") + assert f(None, 15, False, 6, None) == (False, "load time unknown") + assert f(400, 15, False, 6, 5) == (False, "cooldown") + assert f(400, 15, False, 6, 31)[0] is True + assert f(100, 15, False, 1.5, None)[0] is True # fractional hours + assert f(100, 15, False, 1.5, None, min_quiet_min=20)[0] is False + + +def test_empty_reply(): + f = sp.empty_reply_step + # request finished with zero predicted tokens + assert f(100, 50, 600, 50, False, 0) == 1 + assert f(600, 50, 1100, 50, False, 1) == 2 + assert f(1100, 50, 1600, 50, False, 2) == 3 + # a healthy reply resets the run + assert f(1600, 50, 1700, 80, False, 2) == 0 + # nothing happened: unchanged + assert f(100, 50, 100, 50, False, 2) == 2 + # still processing: cannot judge, unchanged + assert f(100, 50, 600, 50, True, 2) == 2 + # server restarted (counters went backwards) or first sample: reset + assert f(5000, 900, 10, 0, False, 2) == 0 + assert f(None, None, 10, 0, False, 2) == 0 + assert f(10, None, 10, 0, False, 2) == 0 + + +# ------------------------------- Control Centre levers (request.json, phases, bands) ------------------------------- +NOW = 1760180000 + + +def _req(action="unload", age=5, **kw): + d = {"action": action, "t": NOW - age, "by": "cc"} + d.update(kw) + return d + + +def test_request_time(): + f = sp.request_time + assert f(1760180000) == 1760180000.0 + assert f(1760180000.5) == 1760180000.5 + assert f(1760180000000) == 1760180000.0 # milliseconds + assert f("2025-10-11T10:13:20Z") == 1760177600.0 + assert f("2025-10-11T20:13:20+10:00") == 1760177600.0 + assert f("2025-10-11T10:13:20") == 1760177600.0 # naive == UTC + for bad in (None, True, False, 0, -5, "", "yesterday", "1760180000", [], {}, float("nan"), "2025-13-45T99:99"): + assert f(bad) is None, bad + + +def test_request_decision_accepts_only_the_four_actions(): + f = sp.request_decision + assert f(_req("load"), NOW) == (True, "load", None, "ok") + assert f(_req("unload"), NOW)[:2] == (True, "unload") + assert f(_req("restore"), NOW)[:2] == (True, "restore") + assert f(_req("reload"), NOW)[:2] == (True, "restore") # GUI word mapped to the governor word + assert f(_req("UNLOAD"), NOW)[:2] == (True, "unload") + for bad in ("exec", "powershell", "kill", "unload; calc", "", "../load", "load now", 7, ["load"], None): + r = {"action": bad, "t": NOW - 1, "by": "cc"} + assert f(r, NOW)[:2] == (False, None), bad + assert f({"t": NOW}, NOW)[:2] == (False, None) # no action key at all + assert f({"action": "load"}, NOW) == (False, None, None, "no usable timestamp") # t is mandatory + assert f("load", NOW)[0] is False and f(None, NOW)[0] is False and f([_req()], NOW)[0] is False + + +def test_request_decision_ignores_old_and_future_requests(): + f = sp.request_decision + assert f(_req(age=59), NOW)[0] is True + assert f(_req(age=60), NOW)[0] is True # the limit itself is still fresh + ok, a, arg, why = f(_req(age=61), NOW) + assert not ok and why.startswith("stale request") + assert f(_req(age=3600), NOW)[0] is False + assert f(_req(age=-3), NOW)[0] is True # small clock skew + assert f(_req(age=-30), NOW) == (False, None, None, "request dated in the future") + assert f({"action": "load", "t": "2025-10-11T10:13:20Z"}, 1760177600 + 30)[0] is True + assert f({"action": "load", "t": "2025-10-11T10:13:20Z"}, 1760177600 + 90)[0] is False + assert f(_req(), NOW, max_age=2)[0] is False # configurable + + +def test_request_decision_mode_needs_a_valid_mode(): + f = sp.request_decision + assert f(_req("mode", mode="max"), NOW) == (True, "mode", "MAX", "ok") + assert f(_req("mode", mode="OFF"), NOW)[2] == "OFF" + for bad in (None, "", "TURBO", "MAX; x", 3, ["MAX"]): + assert f(_req("mode", mode=bad), NOW) == (False, None, None, "mode not allowed"), bad + assert f(_req("mode"), NOW)[0] is False + # arg is only ever set for 'mode' + assert f(_req("unload", mode="MAX"), NOW)[2] is None + + +def test_request_plan(): + p = sp.request_plan + # unload: busy -> postponed, no unload (acceptance test); idle -> unload + assert p("unload", True, "ready", True, "AUTO") == ("postpone", "a request is running") + assert p("unload", True, "ready", False, "AUTO")[0] == "unload" + assert p("unload", False, "stopped", False, "AUTO") == ("noop", "not loaded") + # load + assert p("load", False, "stopped", False, "AUTO")[0] == "prewarm" + assert p("load", True, "ready", False, "AUTO") == ("noop", "already loaded") + assert p("load", False, "stopped", False, "OFF") == ("noop", "mode OFF") # the loop would unload it again + assert p("load", False, "stopped", False, "AUTO", other_running=True)[0] == "noop" + assert p("load", False, "starting", False, "AUTO") == ("noop", "model is already loading") + # restore (reload with the saved context) + assert p("restore", True, "ready", False, "AUTO")[0] == "unload-then-prewarm" + assert p("restore", True, "ready", True, "AUTO")[0] == "postpone" + assert p("restore", False, "stopped", False, "AUTO")[0] == "prewarm" + assert p("restore", True, "ready", False, "OFF")[0] == "noop" + # llama-swap down: nothing is attempted + assert p("unload", False, "swap-down", False, "AUTO") == ("noop", "llama-swap not answering") + assert p("load", False, "api-error", False, "AUTO")[0] == "noop" + # mode changes are always allowed, whatever the model is doing + assert p("mode", True, "ready", True, "OFF")[0] == "set-mode" + assert p("exec", True, "ready", False, "AUTO")[0] == "noop" + + +def _walk(samples): + """Feed phase_decide a list of kwargs dicts; return the phases.""" + return [sp.phase_decide(**k) for k in samples] + + +def test_phase_unload_busy_is_postponed_then_expires(): + busy = dict(state="ready", loaded=True, processing=True) + assert sp.phase_decide(**busy, postponed_age=0) == "postponed-busy" + assert sp.phase_decide(**busy, postponed_age=29) == "postponed-busy" + assert sp.phase_decide(**busy, postponed_age=30) == "ready" # hold over + assert sp.phase_decide(state="ready", loaded=True, processing=False, postponed_age=5) == "postponed-busy" + # postponed never sticks to a model that is gone + assert sp.phase_decide(state="stopped", loaded=False, processing=False, postponed_age=5) == "stopped" + + +def test_phase_unload_walks_unloading_then_stopped(): + seq = _walk([ + dict(state="ready", loaded=True, processing=False), # before + dict(state="ready", loaded=True, processing=False, unload_age=0.5), # the sample that unloaded + dict(state="stopped", loaded=False, processing=False, unload_age=15.5), # next sample + ]) + assert seq == ["ready", "unloading", "stopped"], seq + assert sp.phase_decide("stopping", True, False) == "unloading" + + +def test_phase_load_walks_loading_restoring_warming_ready(): + seq = _walk([ + dict(state="stopped", loaded=False, processing=False, prewarm_age=0.2), # load asked, swap not starting yet + dict(state="starting", loaded=False, processing=False, job_phase="loading", job_age=4), + dict(state="ready", loaded=True, processing=False, job_phase="restoring", job_age=9), + dict(state="ready", loaded=True, processing=True, job_phase="warming", job_age=12), # the 1-token 'hi' when no restore + dict(state="ready", loaded=True, processing=False, job_phase="ready", job_age=14), + dict(state="ready", loaded=True, processing=False), + ]) + assert seq == ["loading", "loading", "restoring", "warming", "ready", "ready"], seq + + +def test_phase_restore_in_one_sample_is_loading_not_unloading(): + # UnloadThenPrewarm: both timestamps are fresh and `loaded` still holds the pre-unload value + assert sp.phase_decide("ready", True, False, unload_age=1.0, prewarm_age=0.9) == "loading" + # a plain unload (no reload) in the same state is 'unloading' + assert sp.phase_decide("ready", True, False, unload_age=1.0) == "unloading" + + +def test_phase_dead_job_leftover_is_ignored(): + assert sp.phase_decide("ready", True, False, job_phase="restoring", job_age=600) == "ready" + assert sp.phase_decide("stopped", False, False, job_phase="loading", job_age=600) == "stopped" + assert sp.phase_decide("ready", True, False, job_phase="restoring", job_age=None) == "ready" + assert sp.phase_decide("ready", True, False, job_phase="bogus", job_age=3) == "ready" + for st, ld in (("swap-down", False), ("api-error", False), ("stopped", False), ("ready", True)): + assert sp.phase_decide(st, ld, False) in sp.ALL_PHASES + + +def _bands_sum(b): + return b["model_gib"] + b["kv_gib"] + b["desktop_gib"] + b["other_gib"] + b["free_gib"] + + +def test_vram_bands_sum_to_total_with_desktop_band(): + # loaded: 21.4 used of 23.88, llama 18.7 of which KV 65536 x 64.5 KiB = 4.03 GiB, dwm 2.7 + b = sp.vram_bands(23.88, 21.4, 18.7, 2.7, 65536, 64.5) + assert abs(_bands_sum(b) - 23.88) <= 0.1, b + assert b["desktop_gib"] == 2.7 and b["kv_estimated"] is True + assert abs(b["kv_gib"] - 4.03) < 0.01 and abs(b["model_gib"] - (18.7 - 4.03)) < 0.02 + # unloaded: the desktop band is still there, model and KV are zero + u = sp.vram_bands(23.88, 2.9, 0.0, 2.7, None, 64.5) + assert u["desktop_gib"] == 2.7 and u["model_gib"] == 0 and u["kv_gib"] == 0 + assert abs(_bands_sum(u) - 23.88) <= 0.1 and abs(u["other_gib"] - 0.2) < 0.01 + # dwm counter bigger than what is left after llama: clamped, never negative + c = sp.vram_bands(23.88, 21.0, 20.0, 2.7, 32768, 64.5) + assert c["desktop_gib"] == 1.0 and c["other_gib"] == 0 and c["free_gib"] == 2.88 + assert abs(_bands_sum(c) - 23.88) <= 0.1 + # counters overshoot the heap: scaled down, free is 0, still sums to the total + o = sp.vram_bands(23.88, 30.0, 26.0, 2.7, 32768, 64.5) + assert o["free_gib"] == 0 and abs(_bands_sum(o) - 23.88) <= 0.1 + # garbage in: no crash, no negatives + z = sp.vram_bands(23.88, -1, -2, -3, None, None) + assert _bands_sum(z) - 23.88 <= 0.1 and all(v >= 0 for k, v in z.items() if k.endswith("_gib")) + # llama so small KV would exceed it: KV is capped at llama's share + k = sp.vram_bands(23.88, 3.0, 1.0, 2.0, 262144, 64.5) + assert k["kv_gib"] == 1.0 and k["model_gib"] == 0 + + +def test_preload_items_match_the_governors_expected_ctx(): + # same arithmetic as governor.ps1 expected_ctx: default variant, BALANCED margin 1.5, others (desktop + browser) 2.9 GiB + total, margin, others, base, kv = 23.88, 1.5, 2.9, 17.15, 64.5 + ec = int(((total - margin - others - base) * 1048576) / kv / 4096) * 4096 + assert ec == 36864, ec + p = sp.preload_items(total, others, base, kv, ec, margin) + assert p["kv_gib"] == 2.27 and p["need_gib"] == 19.42 and p["free_after_gib"] == 1.56 and p["fits"] is True + assert abs(p["base_gib"] + p["kv_gib"] - p["need_gib"]) <= 0.01 + # ctx_min forces a context the heap cannot hold with that margin: fits is False and free_after is below the margin + q = sp.preload_items(total, 5.0, base, kv, 32768, margin) + assert q["fits"] is False and q["free_after_gib"] < margin - 0.05 + + +def test_ps_mirror_of_governor_wiring(): + """v4 governor: the slot is saved before every governor-initiated unload and restored after its relaunch. + (The repo's Control Centre request.json lever is NOT part of the deployed v4 governor.)""" + here = os.path.dirname(os.path.abspath(__file__)) + lib = open(os.path.join(here, "slotlib.ps1")).read() + gov = open(os.path.join(here, "governor.ps1")).read() + for name in ("SlotSave", "SlotRestorePlan", "SlotWarmFlow", "SlotCfg", "SlotPrune", "SlotDiskFreeGib"): + assert ("function %s(" % name) in lib, name + unload = gov[gov.index("function Unload("):gov.index("function WaitServerGone(")] + assert "InFlight $script:curPort" in unload # fresh in-flight check right before the unload + assert unload.index("SlotSave") < unload.index("/api/models/unload/") # save first, then unload + assert "UnloadThenPrewarm" in gov and "WaitServerGone 45" in gov # relaunch only after the old server is gone + prewarm = gov[gov.index("function Prewarm("):gov.index("function UnloadThenPrewarm(")] + assert "SlotRestorePlan" in prewarm and "SlotWarmFlow" in prewarm + # phase hooks inside SlotWarmFlow: loading at the start, restoring, warming, ready at the end + flow = lib[lib.index("function SlotWarmFlow("):lib.index("# ---------------- for qwen.ps1")] + for ph in ("loading", "restoring", "warming", "ready"): + assert ("SlotSetPhase $p '%s'" % ph) in flow, ph + assert "SlotRestoreDecision" in flow and "$kvNow" in flow # KV type is checked at restore time + assert "kv = $kvType" in lib # ... and recorded at save time + # PS 5.1 pitfalls: no $pid variable, no PS7-only operators + assert "$pid " not in gov.replace("$pids", "") and "$pid=" not in gov and "$pid)" not in gov + assert "??" not in gov and "?." not in gov + # status.json always carries the degraded flag and the last error + for key in ("degraded", "last_error", "loop_errors", "sense_warnings", "decision_reason"): + assert ("'%s'" % key) in gov, key + + +def test_ps_decision_constants_match_python(): + lib = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "slotlib.ps1")).read() + for needle in ("%d" % sp.REQUEST_MAX_AGE_SEC, "%d" % sp.POSTPONE_HOLD_SEC, "%d" % sp.JOB_PHASE_MAX_SEC, + "%d" % sp.UNLOAD_SHOW_SEC, "%d" % sp.PREWARM_SHOW_SEC): + assert needle in lib, needle + for ph in sp.ALL_PHASES: + assert ("'%s'" % ph) in lib, ph + + + +def test_ps_mirror_present(): + """Drift guard: every policy function has a PowerShell twin in slotlib.ps1 (cannot run PS here).""" + ps = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "slotlib.ps1")).read() + for name in ("SlotFilename", "SlotTokenCount", "SlotSaveDecision", "SlotPostSaveOk", "SlotRestoreDecision", + "SlotRestoreTargetOk", "SlotUnloadGate", "SlotPruneSelection", "SlotHygieneDecision", "SlotEmptyReplyStep"): + assert ("function %s(" % name) in ps, name + + +def run(): + tests = [(k, v) for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)] + for name, fn in tests: + fn() + print("ok ", name) + print("%d tests passed" % len(tests)) + + +if __name__ == "__main__": + run() From 4c93924b6bad98d71d9211eac7257b939be04937 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 02:58:14 +1100 Subject: [PATCH 03/16] Docs: field report, Codex compat, roadmap, rejected list, tuning log --- docs/CODEX-COMPAT.md | 51 ++++++++++++++++++++++ docs/FIELD-REPORT-20261018.md | 81 +++++++++++++++++++++++++++++++++++ docs/ROADMAP.md | 72 +++++++++++++++++++++++++++++++ docs/TRIED-AND-REJECTED.md | 43 +++++++++++++++++++ docs/TUNING-LOG.md | 4 ++ 5 files changed, 251 insertions(+) create mode 100644 docs/CODEX-COMPAT.md create mode 100644 docs/FIELD-REPORT-20261018.md create mode 100644 docs/ROADMAP.md create mode 100644 docs/TRIED-AND-REJECTED.md diff --git a/docs/CODEX-COMPAT.md b/docs/CODEX-COMPAT.md new file mode 100644 index 0000000..80c3853 --- /dev/null +++ b/docs/CODEX-COMPAT.md @@ -0,0 +1,51 @@ +# Codex and Claude Code against llama-server: what works + +On 15 October 2026 we ran 26 request types against the live stack. The stack was llama-swap → llama-server b11526 (Intel FA build), ThinkingCap-Qwen3.8-27B Q4_K_M with the DFlash2 drafter, the [custom chat template](../governor/qwen38-template.jinja) (qwen3-coder XML tool format), `--jinja --no-context-shift`, and a 40,960-token window. Unless noted, tests used the `qwen3.8-27b:code` preset (thinking off). Every row is a real request. + +## The short version + +| Feature | `/v1/chat/completions` | `/v1/responses` | +|---|---|---| +| `tool_choice: "auto"` | Works | Works | +| `tool_choice: "required"` when the prompt doesn't need a tool | **Not enforced** (tool call 1/4) | **Not enforced** (0/4) | +| Named `tool_choice` (force one function) | **Silently ignored**, no warning | **Silently ignored**, both shapes | +| `response_format` json_schema (strict) | Enforced, even against an adversarial prompt | — | +| `text.format` json_schema / json_object | — | **Ignored** | +| Top-level `response_format`, `json_schema` or `grammar` | Enforced | **Enforced** (the workaround for `text.format`) | +| GBNF `grammar` | Enforced | Enforced (top level) | +| `parallel_tool_calls` | Honoured | Honoured | +| Tool types `custom` (freeform apply_patch), `web_search`, `local_shell` | — | Accepted, then **dropped** | +| Output cap reached | `finish_reason: "length"` | **`"completed"`**, truncated text, no `incomplete_details` | +| Tool-argument JSON (22 calls with backslashes, nested quotes, `\n`, Unicode) | 22/22 valid | 22/22 valid | +| Reasoning, thinking on | Clean `reasoning_content`, no `` text | Separate reasoning item, no `` text | + +Two side effects: + +- With `required` and thinking off, a literal `` leaked into the content in 2 of 4 runs. +- With thinking on and a tight output cap, one run spent all 1,200 tokens reasoning and returned no message. + +## What to do about it + +- **When a tool call is required:** treat a prose answer as a retry. Don't count on the server to force the call. +- **When you need schema output on `/v1/responses`:** send a top-level `response_format`, not `text.format`. +- **When you hit the output cap on `/v1/responses`:** check the text yourself. `"completed"` doesn't mean the answer finished. +- **For agent loops:** use the `:code` preset (1.7–5.3 s turns in these tests) rather than the thinking preset (5–40 s). +- **For Codex:** use the [lean Codex home](../agents/codex-lean/README.md) to cut the start-up prompt from 12,235 to 3,010 tokens. + +## Prefix caching + +Agent-style requests with a 10,872-token system prompt and 2 tools, on the `:code` preset: + +| Request | First token | Prompt work | Generation | +|---|---:|---|---| +| Cold, unique prefix | 22.3 s | 10,872 tokens at 498 tok/s | 37.7 tok/s | +| Same request again | 0.50 s | 4 new tokens (10,868 cached) | 28.7 tok/s | +| Same system prompt, new user turn | 0.87 s | 33 new tokens | 29.0 tok/s | +| Same, via `/v1/responses` stream | 0.98 s | 10,820 cached | 111 tokens in 3.6 s | + +A verbatim 1,065-token copy ran at 53–56 tok/s, byte-exact 3 of 3 times; the drafter accepted 931 of 931 tokens. Copy-heavy output is where the drafter shines. + +## Open questions + +- Codex sometimes prints an "ignored forced-tool parameter" warning. No llama-swap or llama-server response contains one, so it probably comes from Codex itself or the tool gateway after a named `tool_choice` went unobeyed (inferred). +- Third-party guides say Codex has dropped `wire_api = "chat"`; `responses` works here (inferred, not checked against OpenAI's docs). diff --git a/docs/FIELD-REPORT-20261018.md b/docs/FIELD-REPORT-20261018.md new file mode 100644 index 0000000..2fe4108 --- /dev/null +++ b/docs/FIELD-REPORT-20261018.md @@ -0,0 +1,81 @@ +# Field report, 18 October 2026: the real VRAM budget, an open regression, and why the KV cache stays f16 + +A dated maintainer report from one Windows 11 workstation (Intel Arc Pro B60 24 GB, Ryzen 7 3700X, 32 GB RAM, two 3440×1440 displays). It runs ThinkingCap-Qwen3.8-27B Q4_K_M with the DFlash2 drafter on llama.cpp b11526, the Intel FA build. This report doesn't replace the benchmark headlines in the [README](../README.md). It records what changed in our understanding between 15 and 18 October and which settings that moved. + +**How to read the labels.** **Measured** means a number read from the machine, a log or a request capture. **Inferred** means it was derived from measured numbers. **Researched** means it comes from source reading or arithmetic, with nothing run on the card ([docs/research/](research/README.md)). Single runs unless stated. + +## Summary + +1. **Context is capped by a per-process WDDM budget, not by the adapter's free VRAM.** At a 57,344-token window, llama-server put 2.90 GiB in *shared* (system) memory and decode fell to 20–22 tok/s. That happened even though the adapter still reported about 1.2 GiB free. (Measured.) +2. **Decode on this box is slower than it was on 15–16 October, and the cause isn't known yet.** Warm decode is 28 tok/s at a 36,864-token window today, against 43–48 on 15–16 October. `llama-bench tg32` without the drafter is 19% lower on the same command. (Measured; cause open.) +3. **A q8_0 main KV cache is rejected.** At 25K tokens of context it halves prompt reading (428 → 199 tok/s) and cuts generation by 57% (25.5 → 10.9 tok/s). It saves only 0.27 GiB. (Measured.) +4. **Published governor defaults changed** to a 2.5 GiB free margin for the MAX and BALANCED profiles. The governor is now v4.3 ([governor/README.md](../governor/README.md)). + +## 1. Dedicated free VRAM is not a real fit + +The governor sizes context as weights + drafter + context × 64.5 KiB per token, against the adapter's *dedicated* free memory minus a margin. On 18 October the fit looked fine and the results did not: + +| When | Window | Margin | llama-server dedicated | llama-server **shared** | Other apps | Warm decode | +|---|---:|---:|---:|---:|---:|---:| +| 16 Oct 00:03 | 40,960 | 1.35 GiB | not recorded | not recorded | — | 48 tok/s | +| 18 Oct 00:03 | 57,344 | 1.35 GiB | 19.70 GiB | **2.90 GiB** | 1.74 GiB | 20.0–22.3 tok/s | +| 18 Oct 00:07 | 36,864 | **2.5 GiB** | 20.10 GiB | 1.23 GiB | 1.80 GiB | 26.7–28.3 tok/s | + +Data: [context-spill-20261018.csv](../data/context-spill-20261018.csv). The governor log and the counter readback for these three rows were not published. + +**What this means (inferred).** Windows gives each process a dedicated-memory budget below the adapter total. Allocations beyond that budget go to shared, system-backed memory over PCIe. Anything the model touches there runs at PCIe speed instead of the card's 456 GB/s. Adapter-wide "free VRAM" can't see that happening. The "cliff at about 1.1 GiB free" in the [tuning log](TUNING-LOG.md) was probably this same effect, seen from outside. + +**The 17 October footprint sweep supports this (inferred, not isolated).** Every variant at a 32,768-token window was measured with both counters ([footprint-variants-20261017.csv](../data/footprint-variants-20261017.csv), raw [run.log](../data/raw/ctxlab-20261017/run.log)). The fastest short-request run, 46.1 tok/s, was the one with the least shared memory (0.75 GiB). Production settings had 1.68 GiB shared and ran at 29.9 tok/s. Other things changed between those rows too, so treat this as a lead, not proof. + +**Check it on your own card** (Windows PowerShell 5.1). Run it while llama-server is loaded; a tok/s figure without both numbers isn't a result: + +```powershell +$p = Get-Process llama-server | ? { $_.Path -like 'C:\AI\llama.cpp\*' } +(Get-Counter '\GPU Process Memory(*)\Dedicated Usage','\GPU Process Memory(*)\Shared Usage').CounterSamples | + ? { $_.InstanceName -like "pid_$($p.Id)_*" } | select Path,@{n='GiB';e={[math]::Round($_.CookedValue/1GB,2)}} +``` + +**Practical ceiling on this desktop.** Until the per-process budget is mapped (step E0 in the [roadmap](ROADMAP.md)), treat **about 36–40K tokens with an f16 KV** as the safe window. The 12 October 64K result in the README was real, but shared usage wasn't being recorded then. Larger windows are being re-qualified, not withdrawn. + +## 2. An open throughput regression + +| Date | Test | Result | +|---|---|---| +| 12 Oct | `llama-bench tg32`, depth 0, no drafter | 16.0–16.1 tok/s ([TUNING-LOG](TUNING-LOG.md) row 1) | +| 15–16 Oct | warm 300-token request, window 40,960 | 43–48 tok/s | +| 17 Oct 16:08 | same `tg32` command | **13.0 tok/s** (−19%) ([kv-batch1.md](../data/raw/ctxlab-20261017/kv-batch1.md)) | +| 18 Oct 00:07 | warm 300-token request, window 36,864 | **28 tok/s** | + +The `llama-bench` drop came before any governor or profile change that week, so the governor didn't cause it. + +**Already ruled out (measured):** GPU contention (no other process above 1%), a driver change (still 32.0.101.8976), configuration changes, the power plan, the ECC registry value, and WHEA or display-driver events. + +**Not yet ruled out:** the ECC toggle in Intel Graphics Software (the 12 October slowdown had the same signature and went away with ECC off), the clock or thermal state after 2.5 days of uptime, a reboot, and whether the shared-memory spill alone explains the gap. The cheap checks are listed first in the [roadmap](ROADMAP.md#e0-real-vram-budget-and-the-regression). + +## 3. Why the main KV cache stays f16 + +The Intel Xe flash-attention shaders only take f16 K and V. With q8_0 the engine falls back to a scalar path, and the cost grows with context. Measured on 17 October, all from the same build: + +| Tool | KV | Context | Prompt tok/s | Generation tok/s | +|---|---|---:|---:|---:| +| llama-bench (no drafter) | f16 | 0 / 16K / 32K | 485 / 379 / 354 | 13.0 / 14.4 / 12.7 | +| llama-bench (no drafter) | q8_0 | 0 / 16K / 32K | 588 / 198 / 123 | 15.7 / 11.5 / 9.5 | +| llama-server + DFlash2, window 40,960 | f16 | 3.9K / 25K | 473 / **428** | 30.9 / **25.5** | +| llama-server + DFlash2, window 40,960 | q8_0 | 3.9K / 25K | 413 / **199** | 33.8 / **10.9** | + +Data: [kv-cache-depth-20261017.csv](../data/kv-cache-depth-20261017.csv); raw [server-depth-f16.log](../data/raw/ctxlab-20261017/server-depth-f16.log), [server-depth-q8_0.log](../data/raw/ctxlab-20261017/server-depth-q8_0.log). q8_0 wins on empty prompts and loses badly once a coding agent's 20–40K-token conversation is in the window. Measured at a 40,960-token window, it saved 0.27 GiB (19.65 → 19.38 GiB). + +The only honest route to a smaller KV cache is engine work, not a flag: a valid 8×16×16 path for quantised K/V, or dequantising to f16 onto the existing Xe shaders. That is researched but untested, in [research/coopmat_reconciliation.md](research/coopmat_reconciliation.md). + +## 4. What changed in this repo + +- [governor/](../governor/) is now **v4.3**. It has null-safe sensing, pressure hysteresis, no unload while a request is in flight, KV slot save/restore, power-plan hysteresis, footprint calibration, and a process-path filter so Ollama's bundled `llama-server.exe` is never counted as the model. Tests: `test_governor.ps1` 111/0, pytest 53/0, `test_ctx.ps1` 7/7. +- `governor/profiles.json`: the MAX and BALANCED `free_margin_gib` is **2.5** (was 1.35), and `auto.others_vram_max_gib` is 2.5. +- [agents/codex-lean/](../agents/codex-lean/README.md): an opt-in Codex home that cuts Codex's start-up prompt from 12,235 to 3,010 tokens (measured). The first cold turn went from 33 s to 8 s. +- [CODEX-COMPAT.md](CODEX-COMPAT.md): which OpenAI request features this llama-server honours, ignores or drops, from 22 request shapes against the live server. +- [TRIED-AND-REJECTED.md](TRIED-AND-REJECTED.md) and [ROADMAP.md](ROADMAP.md): what not to re-run, and the next experiments with pass/fail criteria. +- [research/](research/README.md): a source-level study of the engine (DFlash per-round timing, the coopmat question, the context budget), clearly marked as not run on the card. + +## Evidence boundary + +The three 16–18 October rows in section 1 and the warm-decode figures in section 2 come from the maintainer's governor log and counter readback, which are not published. Everything in section 3 and the footprint sweep has raw files in [data/raw/ctxlab-20261017/](../data/raw/ctxlab-20261017/README.md). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..fce7564 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,72 @@ +# Roadmap: next experiments + +Planned, **not yet run**. Each step has a pass/fail and a way back. The order matters: every later number depends on E0. Last updated 18 October 2026. + +Rules for every step: + +- One variable per run. +- Record the llama-server process's **dedicated and shared** memory with every tok/s figure ([how](FIELD-REPORT-20261018.md#1-dedicated-free-vram-is-not-a-real-fit)). +- Throughput claims use the fixed contract: seeds 4242–4244, temperature 0.2, 2,304 tokens, thinking off. Report tok/s, tokens per round and ms per round for each seed. +- A warm 300-token request is a smoke test, not acceptance. +- Scratch launches use another port and a scratch build directory. The production engine, weights and governor are not touched. + +## E0: Real VRAM budget and the regression + +The first step: no code changes, about 30 minutes. + +1. **ECC, clocks, reboot.** Check the ECC toggle in Intel Graphics Software; the 12 October slowdown was ECC. If ECC is already off, read the GPU clock and temperature under load. If neither explains it, reboot. + - **Pass:** warm decode ≥ 40 tok/s at a 36,864-token window with shared ≤ 0.1 GiB. +2. **Shared = 0 run.** Unload the model, close the browser, and launch the production command line at 32,768 tokens. Then step through 36,864, 40,960, 45,056 and 49,152, stopping at the first window where shared memory exceeds 0.2 GiB. + - **Deliverable:** a five-row table of window, dedicated, shared and tok/s. That table *is* the per-process budget. +3. **Make the governor honour it.** Set the margin one step below the knee. Optionally, read `Shared Usage` in the governor itself and treat > 0.25 GiB after launch as a reason to refit down. + +## E1: Where the 112 ms per round goes + +No code changes, about an hour. + +From the maintainer's trace: 2,304 tokens in 458 drafter rounds is 5.03 tokens and 133 ms per round. The draft timer accounts for 20.8 ms; one verify pass costs about 36–38 ms at the card's bandwidth. That leaves **about 74 ms per round unexplained**. Reaching 40 tok/s needs only −7 ms per round; 50 tok/s needs −32 ms (arithmetic in [research/dflash_timing_analysis.md](research/dflash_timing_analysis.md)). + +Run one seed with `GGML_VK_PERF_LOGGER=1` and read per-graph GPU time for the verify, draft-inject and draft-decode graphs. + +- **Pass:** GPU time ≤ 85 ms per round, so ≥ 25 ms is host or sync gap. Go to E2. +- **Fail:** GPU time ≥ 120 ms, so it is kernel time. Look at verify mat-vec efficiency instead. + +## E2: Remove one per-round cost + +Engine work in a scratch build; only after E1 passes. + +Candidates, in order: + +1. Skip the inject decode for positions that will be rejected (upstream `TAG_SPEC_AVOID_DRAFT_REEVAL`). +2. Drop a redundant `synchronize()`. +3. Merge inject and draft into one graph. + +**Gate:** greedy output must be token-identical to the production binary, then run the three-seed contract. **Pass:** two of three seeds ≥ 40 tok/s, at least 7 ms per round saved, and no token differences. + +An **untested** instrumentation diff is in [research/instrumentation_patch_UNTESTED.diff](research/instrumentation_patch_UNTESTED.diff). + +## E3: A valid quantised-KV path + +Engine work; only if E1 shows the draft's scalar flash attention is > 10% of draft time. + +There are two routes: + +- Dequantise q8_0 K/V to f16 onto the existing Xe shaders. +- Parametrise the cm1 flash-attention shader to the shape the driver actually enumerates. + +Either would also make q8_0 **main** KV viable without the 57% cliff. That is the only honest route to 50–60K on this card. Researched only: [research/coopmat_reconciliation.md](research/coopmat_reconciliation.md). + +## E4: Gateway, streaming and reasoning policy + +No engine work. + +1. Stream tokens from `ask_local` instead of buffering the whole answer. Today a cold 10.9K-token request shows nothing for 22 s. +2. Adopt one reasoning-parameter resolver: an omitted effort means medium, never `xhigh`, and the caller's temperature is kept. The **untested** resolver and its 22-row precedence matrix are in [research/](research/README.md). Its tests passed on the author's machine only, so it must be validated against the live server before use. +3. For Codex, use the lean home ([agents/codex-lean/](../agents/codex-lean/README.md)) and the workarounds in [CODEX-COMPAT.md](CODEX-COMPAT.md). + +## E5: Memory the governor can't see + +- Find the client that reloads a small Ollama model every 40–70 minutes, and set `OLLAMA_KEEP_ALIVE` to 5 minutes at machine scope. That returns up to 3 GiB at random times. +- The compositor holds 1.7–1.9 GiB with two 3440×1440 panels. A compositor restart and the MPO/HAGS toggles are untested. + +What not to spend time on: [TRIED-AND-REJECTED.md](TRIED-AND-REJECTED.md). diff --git a/docs/TRIED-AND-REJECTED.md b/docs/TRIED-AND-REJECTED.md new file mode 100644 index 0000000..94aaac9 --- /dev/null +++ b/docs/TRIED-AND-REJECTED.md @@ -0,0 +1,43 @@ +# Tried and rejected + +These ideas were already measured on the B60, or checked against the source, and didn't help. If you want to try one again, change something first. Each row says what you'd need to change. Last updated 18 October 2026. + +## Measured on the card and rejected + +| Idea | Result | Evidence | +|---|---|---| +| q8_0 main KV cache (`-ctk q8_0 -ctv q8_0`) | Prompt reading −53% and generation −57% at 25K tokens of context; only 0.27 GiB saved | [FIELD-REPORT-20261018](FIELD-REPORT-20261018.md#3-why-the-main-kv-cache-stays-f16) | +| q4_0 KV with the Intel FA kernel | No gain (101 vs 101 tok/s at 32K) | [TUNING-LOG](TUNING-LOG.md) row 7 | +| Larger window by lowering the free-VRAM margin (57,344 at 1.35 GiB) | Fits dedicated VRAM but spills 2.90 GiB into shared memory → 20–22 tok/s | [FIELD-REPORT-20261018](FIELD-REPORT-20261018.md#1-dedicated-free-vram-is-not-a-real-fit) | +| Removing `GGML_VK_FORCE_MMVQ=1` | 36.0 / 37.2 / 36.9 vs 38.8 / 42.7 / 43.9 tok/s (3 seeds) | maintainer battery | +| 5 draft tokens instead of 7 | 37.7 / 40.8 / 41.2 tok/s: not better | maintainer battery | +| 15 draft tokens | 27.0 tok/s; VRAM pressure | [TUNING-LOG](TUNING-LOG.md) | +| 8 CPU threads instead of 14 | 38.4 / 37.3 / 42.8 tok/s: not better (RAM cache confounds it) | maintainer battery | +| Embedded MTP drafter, n-gram stacked on DFlash2 | 32.2 tok/s, or no gain | [TUNING-LOG](TUNING-LOG.md) rows 17–19 | +| `--spec-draft-backend-sampling` | 43.95 vs 43.94 tok/s. The source shows it is a no-op for DFlash2 | battery; [research/dflash_timing_analysis.md](research/dflash_timing_analysis.md) | +| `-ub 128` / `-ub 512` to save VRAM | 18.98 / 19.50 GiB vs 19.14 GiB at 32K: not worth the speed trade | [footprint-variants-20261017.csv](../data/footprint-variants-20261017.csv) | +| Drafter on the CPU | Saves 0.15 GiB; generation 16.7 tok/s | same | +| No drafter | Saves 1.45 GiB; generation about 16 tok/s | same | +| Last two layers on the CPU (`-ot blk.(62\|63)=CPU`) | 19.53 GiB: **more** VRAM, not less | same | +| Dropping the vision projector | 0 GiB saved (it already lives CPU-side) | same | +| `--cache-reuse` | Inert on this model (multimodal) | [server-57344.log](../data/raw/server-57344.log) line 27 | +| Power-plan tuning, lower display resolution | No effect; no lower native modes on these panels | [DISPLAY-POLICY](DISPLAY-POLICY.md) | +| A strict governor gate (margin 3.0, other apps ≤ 0.75 GiB) | Pins context at 32K; MAX can never start, because the compositor alone holds 1.7–1.9 GiB | maintainer readback | + +## Proposed, checked, and not adopted + +An outside "optimisation pack" proposed the items below. Each was checked against the installed engine (Codex, read-only) and against the llama.cpp source (Gemini, reading only). **None of this was run on the card, and it isn't in this repo.** + +| Proposal | Why not | +|---|---| +| Vulkan coopmat patch for issue #30503 (admit 8×16×16 for a 16×16×16 shader) | The patch is malformed (`git apply --check` fails) and targets a predicate that doesn't exist at b11524. The claimed fallback isn't implemented. Running an unadvertised shape is outside the Vulkan contract. And the Xe FA shaders already use 8×16×16 for f16 K/V, so it isn't on the main model's hot path ([research/coopmat_reconciliation.md](research/coopmat_reconciliation.md)) | +| "The coopmat mismatch forces DP4A on decode" | Wrong for the main model, for the same reason. Single-token decode is scalar on every vendor | +| Build script for the patch | It force-resets and cleans the source tree; never point it at a working build | +| 128-token prefill benchmark as the acceptance test | Too short, with no drafter contract, so it can't show a 40 tok/s floor | +| Launcher that picks 64K/96K from the model's file size | No measured headroom, it bypasses the governor, and it stops other apps' models | +| "Reasoning effort router" | Forces maximum effort on short histories and overrides an explicit effort from the caller | +| "0-IQ repack" of the GGUF | Neither GGUF contains IQ, Q2_K or Q3_K tensors; a repack would be a model change | +| SYCL, vLLM-XPU or EXL3 containers as the fix | A different backend, Linux/oneAPI, privileged containers and different weights: not a drop-in | +| Moving the display to the integrated GPU | The Ryzen 7 3700X has no integrated GPU | +| 96K window with f16 KV | +4 GiB of KV; doesn't fit (arithmetic and measurement) | +| B70, multi-client or prefix-cached external numbers as targets | Not comparable to single-stream decode on a B60 | diff --git a/docs/TUNING-LOG.md b/docs/TUNING-LOG.md index 3032794..bda5080 100644 --- a/docs/TUNING-LOG.md +++ b/docs/TUNING-LOG.md @@ -27,6 +27,10 @@ Every change, in order, with the number it produced. Each **Data** entry names a | 21 | Qwen's template only accepts `reasoning_effort` of xhigh / medium / low | other values give HTTP 500; "high" maps to xhigh | v3 bench | | 22 | Windows audit: dwm.exe VRAM with two 3440x1440 monitors | dwm holds 2.6 GB of the 24 GB. Dropping both monitors to 1920x1080 did **not** shrink it (2.6 -> 3.3 GB right after the change, 2.8 GB a minute later). See [DISPLAY-POLICY.md](DISPLAY-POLICY.md) | observed on the PC | | 23 | Intel graphics services | Graphics Software Service 15 MB RAM, shader distributor 3 MB, PROSet monitoring small; no overlay process was running and none held VRAM. Switching them off is a tidy-up, not a speed-up | observed on the PC | +| 24 | q8_0 main KV vs f16 at depth, with the drafter (window 40,960, 17 Oct) | 25K-token prompt: prompt reading 428 -> 199 tok/s (−53%), generation 25.5 -> 10.9 (−57%); saves only 0.27 GiB. **Main KV stays f16** | ctxlab-20261017/server-depth-*.log | +| 25 | VRAM footprint sweep at 32K, nine variants, dedicated **and shared** memory recorded (17 Oct) | No-mmproj 0 GiB saved; drafter on CPU and no drafter both fall to ~16 tok/s; `-ot` two layers to CPU uses *more* VRAM; the fastest run had the least shared memory (q8_0 KV, 0.75 GiB shared, 46.1 tok/s short request) | ctxlab-20261017/run.log | +| 26 | Governor margin 1.35 -> 2.5 GiB (18 Oct) | At 1.35 the fit chose 57,344 and llama-server spilled 2.90 GiB to shared memory: 20–22 tok/s. At 2.5: 36,864, 1.23 GiB shared, 26.7–28.3 tok/s. Dedicated free VRAM is not a real fit ([field report](FIELD-REPORT-20261018.md)) | observed (governor.log not published) | +| 27 | Throughput regression (open) | `llama-bench tg32` 16.0 (12 Oct) -> 13.0 (17 Oct) on the same command; warm decode 43–48 (15–16 Oct) -> 28 (18 Oct). Cause not found yet ([roadmap E0](ROADMAP.md#e0-real-vram-budget-and-the-regression)) | ctxlab-20261017/kv-batch1.md; observed | ## Settings that matter (final) From 231c896c7501902123d623ea8f58df58b7013567 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 02:59:29 +1100 Subject: [PATCH 04/16] Research: engine study (researched, not run on the card) --- docs/research/README.md | 30 +++++++++ docs/research/REPORT.md | 55 ++++++++++++++++ docs/research/acceptance_test_spec.md | 21 +++++++ docs/research/context_budget.md | 30 +++++++++ docs/research/coopmat_reconciliation.md | 46 ++++++++++++++ docs/research/dflash_timing_analysis.md | 62 ++++++++++++++++++ .../instrumentation_patch_UNTESTED.diff | 63 +++++++++++++++++++ docs/research/pack_defects_review.md | 25 ++++++++ docs/research/reasoning_policy.md | 26 ++++++++ docs/research/sources.md | 24 +++++++ 10 files changed, 382 insertions(+) create mode 100644 docs/research/README.md create mode 100644 docs/research/REPORT.md create mode 100644 docs/research/acceptance_test_spec.md create mode 100644 docs/research/context_budget.md create mode 100644 docs/research/coopmat_reconciliation.md create mode 100644 docs/research/dflash_timing_analysis.md create mode 100644 docs/research/instrumentation_patch_UNTESTED.diff create mode 100644 docs/research/pack_defects_review.md create mode 100644 docs/research/reasoning_policy.md create mode 100644 docs/research/sources.md diff --git a/docs/research/README.md b/docs/research/README.md new file mode 100644 index 0000000..d1ad5a7 --- /dev/null +++ b/docs/research/README.md @@ -0,0 +1,30 @@ +# Research: the engine, read from source + +> **Researched, not run on the card.** Everything in this folder came from reading llama.cpp source and doing arithmetic on published numbers. It was prepared on 17 October 2026 by a separate model (Gemini) working from our logs and a reconstruction of the engine. No file here was executed on the B60. Code marked `UNTESTED` has never run against the live server. Measured results live in [../FIELD-REPORT-20261018.md](../FIELD-REPORT-20261018.md) and [../../data/](../../data/); use this folder for leads and reasoning, not for numbers. + +**The engine studied.** Our build reports `c85e6c598`, which is not a public commit. The study reconstructs it as llama.cpp b11524 plus the two commits from PR #29357 that this repo vendors. Line numbers are therefore approximate. Where these files call PR #29357 *open*, see [../INTEL-FA.md](../INTEL-FA.md): we recorded it as closed without merging on 2026-09-25. That status was not re-checked for this import. + +## What is here, and how far to trust it + +| File | What it argues | Status | +|---|---|---| +| [REPORT.md](REPORT.md) | Verdict and three ranked interventions: gateway latency first, then DFlash per-round overhead, then a valid quantised-KV FA path | Researched | +| [dflash_timing_analysis.md](dflash_timing_analysis.md) | 133 ms per drafter round, about 74 ms of it unexplained; 40 tok/s needs only −7 ms per round. Also shows `--spec-draft-backend-sampling` is a no-op for DFlash2 | Researched; the trace numbers are measured | +| [coopmat_reconciliation.md](coopmat_reconciliation.md) | Why issue #30503 (coopmat shape gate) isn't on the main model's hot path, and the two valid routes to fast q8_0 K/V | Researched | +| [context_budget.md](context_budget.md), [tools/context_budget.py](tools/context_budget.py) | VRAM arithmetic per window size and KV type | Researched. Superseded in one respect: it budgets against the adapter total, and the 18 Oct measurements show a smaller **per-process** budget ([field report](../FIELD-REPORT-20261018.md)) | +| [tools/dflash_timing.py](tools/dflash_timing.py) | The per-round arithmetic behind the timing analysis | Runs offline (no GPU) | +| [instrumentation_patch_UNTESTED.diff](instrumentation_patch_UNTESTED.diff) | Per-bucket timers for the DFlash loop (roadmap step E1/E2) | **UNTESTED**, never compiled here | +| [reasoning_policy.md](reasoning_policy.md), [tools/reasoning_resolver_UNTESTED.py](tools/reasoning_resolver_UNTESTED.py), [tests/](tests/) | One precedence order for thinking/effort/budget parameters, a 22-row matrix and unit tests | **UNTESTED** against the live server. The unit tests pass offline: 22 passed, 5 skipped (the skipped ones compare against the rejected router, which isn't shipped) | +| [acceptance_test_spec.md](acceptance_test_spec.md) | How to A/B any change on visible latency and total task time | Proposal | +| [pack_defects_review.md](pack_defects_review.md) | Line-by-line problems in the outside optimisation pack | Researched; summarised in [../TRIED-AND-REJECTED.md](../TRIED-AND-REJECTED.md) | +| [sources.md](sources.md), [src/qwen35_27b_config.json](src/qwen35_27b_config.json) | Commits, issues and specs cited; the public model config used for KV arithmetic | Reference | + +Run the offline pieces: + +```bash +python docs/research/tools/dflash_timing.py +python docs/research/tools/context_budget.py +python -m pytest docs/research/tests -q +``` + +The outside "optimisation pack" these files review is **not** included. Its patch, build script and launcher were found to be defective, and nothing from it should be run ([../TRIED-AND-REJECTED.md](../TRIED-AND-REJECTED.md)). diff --git a/docs/research/REPORT.md b/docs/research/REPORT.md new file mode 100644 index 0000000..24d67bc --- /dev/null +++ b/docs/research/REPORT.md @@ -0,0 +1,55 @@ +# B60 Qwen research report: evidence-backed next steps +*Prepared 2026-10-17 (AEDT, UTC+11). Box-only analysis; nothing was run on the user's machine. All proposed code is UNTESTED unless stated.* + +## 1. Verdict +- **Revision:** `c85e6c598f…` is **not a public commit**. According to the pack's own plan it is b11524 (`86a283532`) plus open PR #29357 (`61cc4c2`, `1a5137a`). I reconstructed that tree and all citations use it (approximate line numbers). +- **Coopmat:** on this install the main model's f16-KV attention (prefill **and** DFlash verification) already runs on PR #29357's / #24406's Intel Xe FA shaders. Those use **8x16x16, the shape the driver advertises**, with subgroup size pinned to 16. Issue #30503's gate only affects FA whose K/V is not f16. Here that means the **q8_0 DFlash draft context**, or a future q8_0 main KV. The pack's bypass is malformed. It would also run an *un-advertised* 16x16x16 shader, which is outside the Vulkan contract, and ggml has **no** fallback when pipeline creation fails: it rethrows lazily, mid-request. **Don't apply it. It isn't the decode bottleneck.** +- **Decode:** the target's weight-read floor is ~36-38 ms per forward (456 GB/s). A round takes 133 ms for 5.03 tokens, and the draft timer covers 20.8 ms of that. Up to ~74 ms per round is unexplained by "verify at bandwidth floor + draft", but it sits in uninstrumented buckets: verify inefficiency, feature readback + `synchronize`, inject decode (which includes positions that are about to be rejected, an upstream TODO), lattice readback, n==1 matmuls, and empty-draft steps. **40 t/s needs only −7 ms per round. 50 t/s needs −32 ms per round.** That is plausible only if instrumentation finds a removable sync/inject cost. I can't promise either number. +- **Already explained:** `--spec-draft-backend-sampling` is a **no-op for DFlash2** (speculative.cpp L1101), which is why "GPU sampling 43.95 ≈ 43.94". FORCE_MMVQ only changes n==1 mat-vec decisions, so its ~5 t/s effect shows that n==1 work matters inside the loop. +- **Completed coding tasks:** the largest *certain* lever is visible latency. The MCP helper buffers whole responses, and reasoning-policy errors (xhigh on omitted effort) inflate total time. Both can be fixed without touching the engine. +- **Context:** f16 KV is 64 KiB/token (verified from the public config). DFlash rollback multiplies the recurrent state ×8 (≈1.17 GiB, estimated). 48K f16 is thin but plausible. 56-64K f16 doesn't fit with a 1.5 GiB reserve. q8_0 KV fits on paper but leaves the Intel FA path. + +## 2. Ranked interventions (max three) +| Rank | Intervention | Bottleneck hypothesis | Affects | Compatibility | Risks | Smallest falsification test | Rollback | Already tested? | +|---|---|---|---|---|---|---|---|---| +| **1** | **Visible-latency + reasoning-policy fix in the gateway/MCP helper** (stream to the agent; canonical resolver, `tools/reasoning_resolver_UNTESTED.py`) | Total task time is dominated by buffered delivery and unnecessary thinking (xhigh on omitted effort; top-level effort clobbering nested), not by engine t/s | Visible latency, total task time, KV use | Gateway-only. The engine, governor and weights are untouched. Server precedence was read from source (server-common.cpp L1399-1465) | Template mis-rendering if effort names differ (verify the ThinkingCap template). Streaming partial tool calls needs a robust parser | Integration rows of the 22-shape matrix against the live server. A/B the 12+ task suite on `t_first_visible_mcp` and `t_task_total` (acceptance_test_spec §B) | Feature flag back to the current helper/router | **No.** The unit tests (27/27) pass on the box only | +| **2** | **Instrument, then attack the DFlash per-round overhead** (`instrumentation_patch_UNTESTED.diff` + `GGML_VK_PERF_LOGGER`), then the targeted fix (likely candidates: skip inject for to-be-rejected positions per TAG_SPEC_AVOID_DRAFT_REEVAL; merge inject + draft into one draft graph; remove a redundant `synchronize`) | Most of the 112 ms remainder is sync/serialisation and redundant draft work, not weight bandwidth (floor ~36-38 ms) | Decode/speculation, also prefill TTFT (feature readback of 3-5 GiB for a 32K prompt) | Scratch build of the same reconstructed source. Production engine unchanged | Spec decoding stays lossless under greedy verify. Bugs show up as token diffs, so the greedy-identical gate is required | One attributed profile run (not a throughput claim). Then a single change, A/B on the fixed sustained contract | Keep the production binary. The scratch build lives in a separate directory | **No.** Draft5 and MTP changed acceptance, not overhead. This is a new variable | +| **3** | **Valid 8x16x16 cm1 FA (or q8_0→f16 dequant onto the Xe FA path) for the q8_0 draft KV** | Draft-context attention runs FA_SCALAR (shape_ok=false) inside the 20.8 ms draft time | Speculation (draft time); later q8_0 main KV for 50-60K | Requires shader template changes (coopmat_reconciliation §4). No gate bypass | Shader correctness. Draft-quality drift (acceptance) | First: is scalar FA in the draft graph >10% of draft time in the PERF_LOGGER output? If not, drop this | Revert the build | No. Ranked 3rd because the expected gain is bounded by ≤20.8 ms/round | + +Rejected or non-ranked: the pack's #30503 patch (invalid); GGUF repack (not lossless, no IQ tensors); SYCL/containers (separate security review; production-engine replacement); clock/voltage; iGPU display move (impossible on a 3700X); `--spec-draft-backend-sampling` (no-op for DFlash2); repeating MMVQ-off / 8-worker / draft5 / MTP (no new variable). + +## 3. Single best next experiment +**Attribution profile of the existing build. No code change, no engine replacement.** +1. Launch exactly as production (MAX14, draft7, p-min 0.5, FORCE_MMVQ=1, 32K) with `GGML_VK_PERF_LOGGER=1 GGML_VK_PERF_LOGGER_FREQUENCY=50`. Run **one** seed (4242) of the fixed 2304-token prompt. +2. From the log, extract per-graph op time for (a) the target verify graph, (b) the draft inject graph, (c) the draft decode graph, plus FA pipeline names (xe_fa_decode_ph1/ph2 vs flash_attn_f32_f16 scalar) and mat-vec column counts (find the n==1 nodes). +3. Separately, run one normal (logger off) seed to confirm the baseline is intact. + +**Pass (hypothesis survives):** the sum of GPU op time per round in (a)+(b)+(c) is ≤ 85 ms. That would leave ≥ 25 ms/round of host/sync gap, which justifies intervention 2. **Fail:** GPU time ≥ 120 ms/round, meaning the remainder is kernel time. Then switch to kernel work (verify mat-vec efficiency) and drop the sync hypothesis. **Also record:** whether the draft FA is scalar and what its share is (gates intervention 3). +**Rollback:** unset the two environment variables and relaunch through the governor. No files change. **Abort criteria:** governor headroom alarm, desktop stutter, or VRAM spill. The logger serialises work and reduces t/s; that slowdown is expected and must not be reported as a benchmark. + +## 4. Precise source-level corrections worth considering (UNTESTED) +1. `ggml_vk_create_pipeline_func` (ggml-vulkan.cpp ~L777-781): on `createComputePipeline` failure, mark the pipeline failed and notify `compile_cv` before rethrowing. For FA cm1 pipelines specifically, return a "failed" state that `get_fa_tuning_params` treats as `FA_SCALAR`. Today waiters on `compiled` may block forever. +2. Shape admission: keep `shape_ok` strict. If the cm1 FA shader is parametrised (coopmat_reconciliation §4), admit by the *enumerated* M. +3. `common_speculative_impl_draft_dflash`: when `backend_sampling` is requested for DFlash2, log that it is ignored, so nobody believes it is active (L1101). +4. Server [TAG_SPEC_AVOID_DRAFT_REEVAL] (server-context.cpp L3415/L4226): inject only accepted+bonus positions into ctx_dft, after the accept step. Needs a correctness proof against the draft-KV `seq_rm` logic. +5. Gateway: use the canonical resolver (reasoning_policy.md). Never emit top-level `reasoning_effort` alongside nested kwargs. + +## 5. Missing evidence that prevents a conclusion +- The split of the 112 ms/round remainder (no per-bucket timers yet). The identity of the n==1 matmuls that FORCE_MMVQ affects. +- The actual coopmat property list of this B60 driver (a debug-build `VK_LOG_DEBUG` line). Driver version. +- Load-log buffer sizes: model (GPU vs CPU_Mapped), KV, RS, compute (main and draft). DXGI budget with the normal desktop open. +- Qwen3.8 / DFlash2 architecture (n_extract, draft layers, SWA). Only Qwen3.5/3.6 public configs were available. +- The exact local diff between `c85e6c5` and my reconstruction (`git diff 86a283532 c85e6c598 --stat` on the user's machine would settle it). +- The ThinkingCap chat template (to verify effort names and how budget tags render). + +## What the pack/Gemini research already covered (so we don't duplicate it) +- Identified issue #30503 and the 8x16x16 advertisement (correct as a lead). Benchmarks attribute 653/513/420 prefill to PR #29357. The pack lists rejected experiments: ub512 at 64K, n_max 15, MTP n=2, ngram+DFlash stacking, power plans/resolution. +- Its proposals that this report rejects or corrects: gate bypass + fallback (invalid; fallback absent), backend draft sampling (no-op for DFlash2), 0-IQ repack (no IQ tensors; not lossless), 96K from file size, the router, SYCL/containers, iGPU display, clock offsets. Detailed line-by-line review: `pack_defects_review.md`. +- **What this report adds that the pack does not have:** the IntelFA path already uses the advertised shape for f16 KV; the no-fallback/lazy-compile hazard; the DFlash2 backend-sampling no-op; the FORCE_MMVQ n==1 scope; the per-round arithmetic and bandwidth floor; recurrent-state ×(1+n_rs_seq) memory; the per-prompt feature-readback volume; the precedence matrix and tests. + +## Sections C-F (detail) +- C: `coopmat_reconciliation.md` +- D: `dflash_timing_analysis.md`, `tools/dflash_timing.py`, `tools/dflash_timing_output.json`, `instrumentation_patch_UNTESTED.diff` +- E: `reasoning_policy.md`, `tests/precedence_matrix.csv`, `tools/reasoning_resolver_UNTESTED.py`, `tests/test_reasoning_resolver.py`, `tests/test_run_output.txt` +- F: `context_budget.md`, `tools/context_budget.py`, `tools/context_budget_output.json` +- Acceptance protocol: `acceptance_test_spec.md`. Pack review: `pack_defects_review.md`. Sources: `sources.md`. diff --git a/docs/research/acceptance_test_spec.md b/docs/research/acceptance_test_spec.md new file mode 100644 index 0000000..78addb0 --- /dev/null +++ b/docs/research/acceptance_test_spec.md @@ -0,0 +1,21 @@ +# Acceptance test specification + +**Scope:** this is a *reproducible acceptance test* on one fixed contract. It is **not** a hardware-wide minimum-throughput guarantee. Throughput depends on content (DFlash acceptance), context depth, driver and desktop load. + +## A. Fixed sustained comparison (throughput contract — unchanged from current practice) +- Same binary, model, draft and flags as production. One variable changes per A/B. Governor profile MAX, with the RAM-cache setting recorded. +- Seeds 4242, 4243, 4244; temperature 0.2 (record the *effective* sampler after preset filtering); 2304 output tokens; thinking disabled; the same shallow prompt. +- Order: ABBA interleaved (A1 B1 B2 A2 per seed), with one warm-up generation discarded after each load. +- Record per run: native gen s; tokens (state whether the first token is excluded); rounds; drafted; accepted; **tokens/round; ms/round**; empty-draft steps; first-content s; wall s; finish reason; driver version; desktop state (displays/apps); free VRAM before/after (DXGI). +- **Pass (≥40 contract):** all 6 runs of the candidate ≥ 40.0 t/s, **and** mean ms/round improved over baseline by more than 2× the baseline's seed-matched spread, **and** acceptance (tokens/round) within ±3% of baseline. That last check rules out a "win" coming from content drift. +- **Stretch:** mean ≥ 45. "Approaching 50" requires ms/round ≤ ~101 at 5.03 tokens/round. +- **Fail / reject:** any run < baseline min, any correctness diff (below), or free VRAM below the governor reserve. + +## B. Completed agentic coding tasks (the real objective) +- A fixed suite of ≥12 tasks with hidden tests (e.g. the existing 16-task suite noted in the pack: "16/16 agent tasks, 60.5 s"; that is unverified here). Each task runs through the **real MCP path**. +- Measure per task: `t_first_native_token`, **`t_first_visible_mcp_output`** (client-side timestamp when the MCP tool result or first streamed chunk reaches the agent), **`t_task_total`** (request → tests pass), number of turns, tool-call parse failures, continuation failures (truncation/finish=length mid-edit), and tests passed. +- **Pass:** tests passed ≥ baseline (no regression on any task), zero new tool-call parse failures, median `t_task_total` ≤ 0.95 × baseline, p90 not worse. +- **Correctness guard for engine changes:** greedy (temp 0, thinking off) output on 5 fixed prompts must be **token-identical** to the baseline engine for kernel-only changes. Speculative decoding is lossless under greedy verification. Any diff is a bug until explained. + +## C. Desktop responsiveness and headroom (B60 drives the display) +During runs: record DWM frame time or a simple UI-latency probe, and dedicated/shared GPU memory. **Fail** if shared-memory spill grows (WDDM paging) or the governor's headroom alarms fire. diff --git a/docs/research/context_budget.md b/docs/research/context_budget.md new file mode 100644 index 0000000..fd32bdc --- /dev/null +++ b/docs/research/context_budget.md @@ -0,0 +1,30 @@ +# Context feasibility (Section F) — ESTIMATES ONLY; no larger-context benchmark proposed + +Calculator: `python3 tools/context_budget.py` (output in `tools/context_budget_output.json`). + +## Architecture (public Qwen3.5-27B config; "Qwen3.8" assumed to share it — UNVERIFIED) +`huggingface.co/Qwen/Qwen3.5-27B/raw/main/config.json`: 64 layers, `full_attention_interval 4` → **16 full-attention layers** + 48 Gated-DeltaNet layers; 4 KV heads × head_dim 256; GDN 16 K-heads / 48 V-heads × 128. +- **f16 KV per token** = 16 × 2 (K,V) × 4 × 256 × 2 B = **65,536 B = 64.0 KiB**. The user's 64.5 KiB is within 1% (probably padding or measured from the log), and I use 64.5 conservatively. 32K → 2.02 GiB. **32K→96K adds 4.03 GiB** (confirmed). +- **Recurrent state does not grow with context, but it is multiplied by DFlash rollback snapshots.** `n_rows = mem_size × (1 + n_rs_seq)` (llama-memory-recurrent.cpp L101), with `n_rs_seq = draft n_max = 7` (common.h L399-404). Estimate: 48 × (48·128·128 + 3·10240) × 4 B × 8 ≈ **1.17 GiB**. Draft depth 5 would make it ≈0.88 GiB. Read the real value from the `RS buffer size` log line. +- q8_0 KV = 34/64 of f16 → 34.3 KiB/token. On this install **q8_0 main KV leaves the Intel Xe FA path** (`xe_fa_supported_dtype` requires F16), so FA falls to FA_SCALAR (see #30503 and coopmat_reconciliation.md). Expect both a prefill regression and quality risk. PR #29357 community data on B580 shows q8_0 KV getting little or no prefill gain (−10% to +2%). +- Draft KV q8_0: 2.1-10.6 KiB/token (1 full layer + SWA … 5 layers full context; the draft config is unverified). + +## Budget (GiB), 24 total, 1.5 reserve. Rows = used / margin after reserve +| Scenario | ctx | f16 used | f16 margin | q8_0 used | q8_0 margin | +|---|---|---|---|---|---| +| best (embd on CPU, compute 0.8, display 0.75) | 32K | 21.15 | +1.35 | 20.21 | +2.29 | +| | 48K | 22.19 | +0.31 | 20.77 | +1.73 | +| | 56K | 22.71 | **−0.21** | 21.06 | +1.44 | +| | 64K | 23.23 | −0.73 | 21.34 | +1.16 | +| | 96K | 25.31 | −2.81 | 22.48 | +0.02 | +| mid (compute 1.6, display 1.5) | 32K | 22.70 | −0.20 | 21.76 | +0.74 | +| | 48K | 23.74 | −1.24 | 22.32 | +0.18 | +| | 56K | 24.26 | −1.76 | 22.61 | −0.11 | +| worst (embd on GPU, display 3.0) | 32K | 25.42 | −2.92 | 24.48 | −1.98 | + +**Calibration:** 32K f16 runs healthily today, so the "worst" row is falsified, and reality sits near the best or mid row. The pack's repo claims that 64K f16 / ub256 ran, with 0.71 GiB free at ub512, and that dwm.exe uses 2.6-3.3 GB. That is unverified, and it is inconsistent with this arithmetic unless WDDM is paging. It is exactly why measured values are needed. + +**Verdict:** 48K f16 is plausible but thin (≈0.3 GiB above a 1.5 GiB reserve in the best case). 56-64K f16 does not fit without freeing about 1 GiB or more. q8_0 KV would make 56-64K fit on paper, but it moves FA off the Intel path, so it is a performance and quality experiment, not a free win. **Don't equate weight-repack savings with usable context.** Usable context also needs measured prefill time, quality and governor headroom at that depth. + +## Measure before deciding (read-only, from the next normal launch log) +`load_tensors: Vulkan0 model buffer size`, `CPU_Mapped model buffer size` (shows whether token_embd is on the CPU), `llama_kv_cache: size`, `llama_memory_recurrent: size … RS buffer size`, `Vulkan0 compute buffer size` (main and draft contexts), plus the Windows DXGI `QueryVideoMemoryInfo` Budget/CurrentUsage (Task Manager "Dedicated GPU memory" is an acceptable proxy) with the normal desktop open. diff --git a/docs/research/coopmat_reconciliation.md b/docs/research/coopmat_reconciliation.md new file mode 100644 index 0000000..77cdefa --- /dev/null +++ b/docs/research/coopmat_reconciliation.md @@ -0,0 +1,46 @@ +# Cooperative-matrix reconciliation (Priority C) + +**Revision note.** `c85e6c598f89d11c3591616355a138c33737cee3` is **not public**. GitHub API returns `422 No commit found`, and `git fetch` of the SHA from ggml-org/llama.cpp returns `not our ref`. The pack's own plan (CODEX_PROMPT_AND_PLAN.md L12) says the install is `b11524` (`86a283532`) plus PR #29357 commits `61cc4c2` and `1a5137a`, built into `vulkan-intelfa`. I rebuilt that tree on the box (`src/recon-c85e6c5`): b11524 + cherry-pick 61cc4c2 + 1a5137a. Both picks applied cleanly. The SHA differs because the committer metadata differs. **All line numbers below are in that reconstruction (APPROXIMATE).** For files PR #29357 does not touch (everything outside ggml-vulkan), the line numbers match upstream b11524 exactly. Public tag `b11526` is `5e4878e9787fff9bcc5c12478c47618b73268610`. "IntelFA" is a local build of the open PR #29357, not a public fork name. + +## 1. What the driver advertises +- **Community report, unverified locally.** On a B580 with driver 32.0.101.9033, issue #30503 says the f16 cooperative-matrix list contains **only `M=8 N=16 K=16`**, for both f32 and f16 accumulation, subgroup scope. PR #29357's author, an Intel engineer, writes: "CM1 FA kernel require m16n16k16 coopMat shape that not supported in driver yet" (PR #29357 comment, 2026-09-25). +- `vulkaninfo` does not print the shape list. You get it from `vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR`, and ggml prints it only in a `VK_LOG_DEBUG` build (ggml-vulkan.cpp, inside the shape loop around L4700). +- **Vulkan spec point:** the SPIR-V `OpTypeCooperativeMatrixKHR` dimensions a shader uses must match an enumerated `VkCooperativeMatrixPropertiesKHR` entry. Running an un-advertised 16x16x16 form is outside the API contract. "It worked on 10 probes" (issue #30503) is driver behaviour, not a guarantee. It can change between drivers and can produce silently wrong results. + +## 2. How ggml-vulkan enumerates and admits shapes +| Step | Code (recon) | Effect on B60 (0xE211, Xe2, minSubgroupSize 16) | +|---|---|---| +| Arch detect | `get_device_architecture`, L60-100 | `INTEL_XE2` (minSubgroupSize==16) | +| Vendor gate | `ggml_vk_khr_cooperative_matrix_support` L16306 | Xe2 allowed | +| Feature gate | L4563 `coopmat_support && coopmat_features.cooperativeMatrix` | on | +| Shape loop | ~L4710-4780 | **The first** f16/f16/subgroup entry sets `coopmat_m/n/k`, which becomes **8/16/16**. `coopmat_support_16x16x16_*` is set only if a 16x16x16 entry exists, so it stays **false** | +| mul_mm (cm1 GEMM) | `mul_mm.comp` L167-169, L343-345 use spec constants TM/TN/TK = `coopmat_m/n/k` | Instantiates the **advertised 8x16x16**. Valid and in use (prefill GEMM) | +| mul_mmq_cm1 (int8) | `use_cm1_int` only on AMD RDNA3/4 | Not used on Intel | +| Generic FA cm1 | `get_fa_tuning_params` L1356 `shape_ok` requires 16x16x16; `flash_attn_cm1.comp` L26-27 hard-codes `MatBr=MatBc=16` and K=16 | Rejected, so `FA_SCALAR`. This is #30503 | +| conv2d cm1 | requires 16x16x16 and subgroup 32/64 | Not used | +| **Intel Xe FA (PR #29357 + #24406)** | `xe_fa_supported_platform` L8241. `neq1>8` selects the prefill shader (L8264), otherwise the decode dual-phase pair. Shaders: `flash_attn_prefill.comp` L60-61 and `flash_attn_decode_phase_1/2.comp` `#define TM 8, TK 16`, TN spec constant = `xe_native_sub_group_size` = 16 (L3197) | **8x16x16 = the advertised shape**, pipelines pinned to subgroup 16 (`required_subgroup_size`). Requires **F16 K/V**, mask F16, no softcap/ALiBi | + +### Consequence for this install (the key reconciliation) +- **Main model, f16 KV:** prefill (`neq1>8`) and DFlash verification (`neq1 = draft+1 ≤ 8`) already run on the Intel Xe FA shaders, which use the advertised 8x16x16. **The #30503 gate is not on the main model's hot path.** That is consistent with the 653/513/420 t/s prefill numbers the pack credits to PR #29357. +- **Where #30503 does bite:** any FA whose K/V is **not f16**. Here that is the **DFlash draft context (`-ctkd/-ctvd q8_0`)**, which falls through to `get_fa_tuning_params`, gets `shape_ok=false`, and lands on `FA_SCALAR`. The same would apply to a future **q8_0 main KV** used to reach 50-60K. On the draft side, the cost per round is inside the 20.8 ms draft timer and the inject decode, and it is **unmeasured**. +- **Decode with N==1 uses scalar on every vendor anyway** (L1366). So #30503 cannot help single-token decode. +- **Subgroup sizes:** Xe2 supports 16 and 32. ggml reports "warp size 32". The Xe shaders pin 16. The generic cm1 FA uses `device->subgroup_size` (32) with 16x16 fragments, which Intel has said is not a native shape. + +## 3. Fallback behaviour if pipeline creation fails +`ggml_vk_create_pipeline_func` (L577-800): `createShaderModule`, `createPipelineLayout` and `createComputePipeline` each `catch (vk::SystemError) { std::cerr << ...; throw; }` (compute pipeline: L777-781). **There is no fallback.** Pipelines compile lazily on first use (`ggml_vk_load_shaders(device, requested)`, claim/compile at ~L3974-3990). That means a failure surfaces mid-request as a C++ exception. Also, the `compile_pending` flag is set before compile (~L3976) and `compile_cv.wait(... compiled)` (L4015) waits on `compiled`. If one thread throws, another thread waiting on the same pipeline may never be released. **This is a hazard; I have not proven it reachable.** The pack's claim that a fallback exists (patch L13-15, plan Task 1) is **false**: its diff contains no such code. + +## 4. What a *valid* 8x16x16 generic FA cm1 path would need (UNTESTED design, no code claimed working) +Don't relax `shape_ok`. Instead: +1. In `flash_attn_cm1.comp`, turn `MatBr` and the K-step `16` into spec constants. All `coopmat<..., MatBc, 16, UseA>` / `<16, MatBr, UseB>` / accumulators must form an advertised (M,N,K) triple. With M=8: S = K·Qᵀ tiles become `MatBc=8` (M), `MatBr=16` (N), K=16. For P·V, swap the A/B roles so the 8-row side is M. PR #29357's prefill shader does exactly that ("swapped P/V order to use V as matrixA"). +2. Recompute every derived stride and shared-memory size (`kvsh_stride`, `osh_stride`, `pvsh`, `Psh`, `v_cols`, `num_hsv_tiles`), plus `get_fa_tuning_params_coopmat1` / `ggml_vk_flash_attn_coopmat_shmem_support` Br/Bc/row_split. +3. Pin `required_subgroup_size = 16` on Intel (as the Xe shaders do) and require `subgroup_require_full_support`. +4. Admission: `shape_ok = has_shape(M_sel,16,16, acc)`, where M_sel comes from enumerated properties, never assumed. +5. Validation gates: `test-backend-ops -o FLASH_ATTN_EXT` all pass, including q8_0/q4_0 K/V and HSK=HSV=256 with GQA 6 (Qwen3.5-27B: 24 Q heads / 4 KV heads). Greedy token-identical output against FA_SCALAR on a fixed prompt set. Then the q8_0 draft-KV A/B. + +Lower-effort alternative (UNTESTED): extend `xe_fa_supported_dtype` to q8_0 K/V by dequantizing to f16 scratch. The `use_dequant_kv` / `pipeline_dequant_transpose` machinery already exists (~L8110-8118). That would route the draft's q8_0 FA onto the already-valid 8x16x16 Xe shaders, at the cost of an f16 scratch copy. + +## 5. Recommendation +Do **not** apply the pack's gate bypass. It is malformed anyway: it targets a non-existent `ggml_vk_has_coopmat_support` and a different function signature. Measure first. A GGML_VK_PERF_LOGGER run shows whether `flash_attn_f32_f16*` scalar FA in the draft context is a material share of each round. Only if it is should you pursue §4 or the dequant route. + +## 6. Upstream lead (not in this install) +PR #29357 head now has `b583d8d` (2026-10-14), "add m16n16k16/SIMD32 support for Xe FA prefill shader". It parametrises the prefill shader shape per subgroup (8→{8,8,16}, 16→{16,8,16}, 32→{16,16,16}), and per its author it is prefill-only ("decode/spec decode XE FA shaders were not changed"). A later stride-gate relaxation for single-KV-head models was also discussed. It doesn't apply here: Qwen3.5 has 4 KV heads. diff --git a/docs/research/dflash_timing_analysis.md b/docs/research/dflash_timing_analysis.md new file mode 100644 index 0000000..47219e2 --- /dev/null +++ b/docs/research/dflash_timing_analysis.md @@ -0,0 +1,62 @@ +# DFlash timing analysis (Section D) + +Reproduce with `python3 tools/dflash_timing.py` (output: `tools/dflash_timing_output.json`). Every input is a user-reported number or a public spec. No new measurements. + +## 1. Arithmetic from the traced run +| Quantity | Value | Note | +|---|---|---| +| native t/s | 2303/60.898 = **37.817** | Matches the reported 37.8176 only if the first token (from prefill) is excluded. 2304/60.898 = 37.834 | +| tokens / verification round | 2304/458 = **5.03** | | +| drafted / round | 2576/458 = 5.62 | p-min 0.5 truncates below n_max=7 | +| accepted / round | 1789/458 = 3.91 | acceptance 1789/2576 = **69.4%** | +| tokens explained by rounds (accepted + 1 bonus each) | 2247 | **56-57 tokens unexplained**. Likely empty-draft single-token steps (not counted as verification rounds) plus the first token. Needs a counter | +| ms / round | **132.97** | | +| draft timer / round | **20.82 ms** (15.7% of gen time) | Excludes readback/injection, per the user | +| remainder / round | **112.15 ms** | Target verify + readback + concat + inject + sync + lattice readback + selector + server overhead. **Cannot be split without instrumentation** | +| wall − native | 0.866 s | ≈ first-content latency 0.864 s, i.e. prompt processing + first token | + +### Bandwidth bound (EXTRAPOLATION) +B60 = **456 GB/s** (Intel ARK, SKU 243916). One target forward has to read every VRAM-resident weight at least once: +- whole file 17.44 GB → 38.3 ms, so **≤26.1 forwards/s** +- with token_embd kept on the CPU (llama.cpp default for the input layer; embedding type unverified) → 36.0-36.7 ms, so ≤27.3-27.8 forwards/s + +So non-speculative decode is bounded at ~26-28 t/s at 100% bandwidth efficiency. Real kernels reach 60-85%, which gives roughly 16-23 t/s. The ~38-44 t/s seen is only possible because of speculation (5.03 tokens per target forward). + +A verify of 6.6 tokens costs ≥ the single-token floor. On Intel the mat-vec path stays bandwidth-bound up to `mul_mat_vec_max_cols = 8` (ggml-vulkan-types.h L383), so verify cost should be close to, but above, ~36-38 ms. That leaves **at most ~74 ms per round not explained by the weight-read floor plus the draft timer**. The "ideal" round (verify at floor + draft) is 59 ms, which would give ~85 t/s at the current 5.03 tokens/round. **This is a ceiling, not a forecast.** + +### What 40/50 t/s requires on this contract +| Target | Round time needed at 5.03 tok/round | Or tokens/round needed at 133 ms | +|---|---|---| +| 40 | ≤125.8 ms (−7.2 ms, −5.4%) | ≥5.32 | +| 45 | ≤111.8 ms | ≥5.98 | +| 50 | ≤100.6 ms (−32.4 ms, −24%) | ≥6.65 (close to the n_max=7 cap of 8, not realistic at 69% acceptance) | + +**Implication:** 50 t/s has to come mostly from cutting per-round overhead, not from acceptance. The original runs (38.79 / 42.71 / 43.91, mean 41.8, sd 2.7) already straddle 40. Seed-to-seed variance is about the size of the gap, so any acceptance test must report tokens/round and ms/round per run (see acceptance_test_spec.md). + +## 2. What the code does each round (reconstructed revision; common/speculative.cpp is unchanged from b11524) +1. **Target verify decode** of `[id_last, draft...]`. llama-context `extract_layer_inputs` (L2294-2325) issues `ggml_backend_tensor_get_async` for **each extracted target layer input** (`[TAG_EXTRACT_TARGET_EMBEDDINGS]`, L2028). That is a GPU→host copy of n_extract × 5120 × f32 per token. +2. **Readback sync:** `llama_get_embeddings_layer_inp()` calls `ctx->synchronize()` (llama-context.cpp ~L4176) and then `output_reorder()`. This is a full CPU wait for the target graph to finish. +3. **CPU concatenation:** `common_speculative_impl_draft_dflash::process` L1206-1222 does a per-token, per-layer `memcpy` into `features_buf` (n_chunk × n_extract·5120 floats). +4. **Injection:** `batch_inject.add_embd` and then `llama_process(ctx_dft, DECODE, batch_inject)` (L1230). This is a **separate draft-graph run** that uploads the features host→device and writes the draft K/V. It is called from the server via `common_speculative_process(spec, batch.view)` (server-context.cpp L4232), on **all tokens of the verify batch, including drafted tokens that are about to be rejected**. Upstream marks this redundancy as `TODO [TAG_SPEC_AVOID_DRAFT_REEVAL]` (L3415, L4226). The rejected positions are removed by `llama_memory_seq_rm(ctx_dft, ..., ckpt.pos_max+1, -1)` (L3420-3424) before the next draft. +5. **Draft decode:** one batch of `n_max+1` tokens `[id_last, ×n_max]` (L1264-1277). +6. **DFlash2 selection:** `llama_get_embeddings_nextn(ctx_dft)` (L1297, another readback + sync), then a **CPU** argmax over `selector_top_k` per position, plus the p-min softmax check (L1300-1318). There is no vocabulary sampling. +7. **Target rollback:** for the hybrid Qwen3.5-style target, `n_rs_seq = n_max` (common.h L399-404). Recurrent-state snapshots stay on device, so no host checkpoint is needed when `draft.size() ≤ n_rs_seq` (server-context.cpp L3429-3440). + +### Important source facts +- **`--spec-draft-backend-sampling` is a no-op for DFlash2.** The constructor only installs backend samplers when `backend_sampling && !is_dflash2` (L1101). That explains why the "GPU/backend sampling" battery result (43.95 vs 43.94) did not move. The pack's Task 3 / launcher flag cannot help this draft. +- **Feature traffic is small per round but large per prompt** (`feature_traffic()` in the script; n_extract is 5 or 8 depending on the draft, unverified for Qwen3.8-DFlash2). Per round: 0.65-1.04 MiB each way, 0.05-0.11 ms of transfer at a practical 10-14 GB/s on PCIe 4.0 x8 (3700X platform). So per-round cost comes from **sync/latency, not bytes**. Per prefill: a 32K-token prompt implies 3.1-5.0 GiB each way (≈0.24-0.54 s each way), plus a draft inject pass over every prompt token. **That is relevant to time to first useful output in agentic turns with big contexts.** +- **FORCE_MMVQ:** with the default policy `n>1` already selects MMVQ (`ggml_vk_should_use_mmvq` L6604). `GGML_VK_FORCE_MMVQ=1` therefore only changes **n==1** mat-vec calls on the Intel Windows driver (L6620-6632 returns false for non-Q2/Q3/Q6 types). The measured ~5 t/s loss when it was removed means n==1 matmuls are material inside the loop. Which nodes those are is **unverified**. Candidates: the empty-draft steps (the 56 unexplained tokens) and DFlash2 conv/selector nodes. The per-op profile in the next experiment answers this. + +## 3. Measured vs needs instrumentation +| Component | Status | +|---|---| +| Draft decode (step 5) + selector (6) | Partly measured by the existing draft timer (20.8 ms/round). Whether inject (4) is inside it is unclear; the user says the readback/injection path is excluded | +| Target verify GPU time (1) | **Not isolated** | +| Readback sync wait (2) | **Not measured** | +| CPU concat (3) | **Not measured** (expected well under 1 ms) | +| Inject decode (4) incl. upload + redundant rejected positions | **Not measured** | +| Lattice readback + sync (6) | **Not measured** | +| Empty-draft / single-token steps | **Not counted** | +| Per-op GPU time (which FA path, which matmuls have n==1) | Available today with no code change: `GGML_VK_PERF_LOGGER=1` (+ `GGML_VK_PERF_LOGGER_FREQUENCY`). This serialises submissions, so use it as a diagnostic, not for throughput numbers | + +See `instrumentation_patch_UNTESTED.diff` for timers around steps 1-6. diff --git a/docs/research/instrumentation_patch_UNTESTED.diff b/docs/research/instrumentation_patch_UNTESTED.diff new file mode 100644 index 0000000..46f2381 --- /dev/null +++ b/docs/research/instrumentation_patch_UNTESTED.diff @@ -0,0 +1,63 @@ +# UNTESTED SKETCH - NOT COMPILED, NOT RUN. Hand-written against the reconstructed tree +# (b11524 + PR#29357 61cc4c2/1a5137a). Line offsets approximate. Intended for a scratch +# build only; production engine must not be replaced by default. +# Purpose: split the uninstrumented ~112 ms/round remainder into named buckets. +# Output: one line per N rounds via LOG_INF, plus totals at slot release. +--- a/common/speculative.cpp ++++ b/common/speculative.cpp +@@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { ++ // [INSTR] cumulative microseconds per bucket ++ struct { int64_t sync_feat = 0, concat = 0, inject = 0, draft = 0, sync_lattice = 0, select = 0; ++ int64_t n_inject_tok = 0, n_rounds = 0; } instr; +@@ bool process(const common_batch & batch_in) override { +- for (uint32_t k = 0; k < target_layer_ids_n; ++k) { +- const float * layer = llama_get_embeddings_layer_inp(ctx_tgt, (uint32_t) target_layer_ids[k]); ++ const int64_t t0 = ggml_time_us(); ++ llama_synchronize(ctx_tgt); // [INSTR] isolate the wait for target verify + async readback ++ const int64_t t1 = ggml_time_us(); ++ instr.sync_feat += t1 - t0; ++ for (uint32_t k = 0; k < target_layer_ids_n; ++k) { ++ const float * layer = llama_get_embeddings_layer_inp(ctx_tgt, (uint32_t) target_layer_ids[k]); // now no-wait +@@ +- const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); ++ const int64_t t2 = ggml_time_us(); ++ instr.concat += t2 - t1; ++ const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); ++ llama_synchronize(ctx_dft); // [INSTR] adds a sync point: attributes inject GPU time, perturbs overlap ++ instr.inject += ggml_time_us() - t2; ++ instr.n_inject_tok += n_chunk; +@@ void draft(common_speculative_draft_params_vec & dparams) override { +- int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); ++ const int64_t t3 = ggml_time_us(); ++ int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); ++ llama_synchronize(ctx_dft); // [INSTR] ++ const int64_t t4 = ggml_time_us(); ++ instr.draft += t4 - t3; ++ instr.n_rounds++; +@@ +- const float * lattice = llama_get_embeddings_nextn(ctx_dft); ++ const int64_t t5 = ggml_time_us(); ++ const float * lattice = llama_get_embeddings_nextn(ctx_dft); ++ instr.sync_lattice += ggml_time_us() - t5; ++ const int64_t t6 = ggml_time_us(); +@@ (after the selector loop) ++ instr.select += ggml_time_us() - t6; ++ if (instr.n_rounds % 64 == 0) { ++ LOG_INF("dflash-instr rounds=%lld inject_tok=%lld us/round sync_feat=%.0f concat=%.0f inject=%.0f draft=%.0f sync_lat=%.0f select=%.0f\n", ++ (long long) instr.n_rounds, (long long) instr.n_inject_tok, ++ instr.sync_feat/(double)instr.n_rounds, instr.concat/(double)instr.n_rounds, instr.inject/(double)instr.n_rounds, ++ instr.draft/(double)instr.n_rounds, instr.sync_lattice/(double)instr.n_rounds, instr.select/(double)instr.n_rounds); ++ } +--- a/tools/server/server-context.cpp ++++ b/tools/server/server-context.cpp +@@ (around target decode of the verify batch, ~L4180) ++ const int64_t t_v0 = ggml_time_us(); // [INSTR] host time to enqueue target verify + ret = llama_process(ctx_tgt, ...); ++ slot.instr_verify_enqueue_us += ggml_time_us() - t_v0; // GPU completion is captured by sync_feat above +@@ (where drafts are generated, ~L3400) ++ if (draft.empty()) slot.instr_empty_draft_steps++; // [INSTR] explains the ~56 tokens not covered by rounds +# Notes: +# - The added llama_synchronize() calls REMOVE CPU/GPU overlap. Report results as an attribution +# profile, never as throughput. Compare the sum of buckets with the uninstrumented ms/round. +# - Pair with GGML_VK_PERF_LOGGER=1 in a separate run for per-op GPU time (FA path names, +# mat-vec column counts, scalar FA in the q8_0 draft context). diff --git a/docs/research/pack_defects_review.md b/docs/research/pack_defects_review.md new file mode 100644 index 0000000..597216a --- /dev/null +++ b/docs/research/pack_defects_review.md @@ -0,0 +1,25 @@ +# Pack defects review (read-only; nothing from the pack was executed except the two sandboxed checks noted) + +Pack: `inputs/pack/` (included unchanged in the zip). `docs/B60-RESEARCH-AND-BENCHMARKS.md` and `CODEX_PROMPT_AND_PLAN.md` look like the "Gemini research". + +| # | User's finding | Verified? | Evidence | +|---|---|---|---| +| 1 | Vulkan patch corrupt | **Yes** | `git apply --check` on a scratch copy of b11526 → `error: corrupt patch at line 42`. Hunk header `@@ -2840,9 +2840,24 @@` claims 9/24 lines but the body has ~16 and ends mid-hunk (patch L25-41). With `--recount`: `patch failed: ggml-vulkan.cpp:2840` | +| 2 | Python patcher doesn't match predicate | **Yes** | Ran `apply_xe2_coopmat_30503.py` on a scratch copy → `[ERROR] Could not locate shape_ok 16x16x16 gate`, exit 2. It looks for `ggml_vk_has_coopmat_support(device, f16_type, f32_type, 16,16,16)` (L36-40), but the real code is `bool shape_ok = (f32acc && device->coopmat_support_16x16x16_f32acc) \|\| (!f32acc && device->coopmat_support_16x16x16_f16acc);` (ggml-vulkan.cpp L1356). `ggml_vk_has_coopmat_support` does not exist (`rg` 0 hits). The fallback regex (L55-56) needs a literal `16, 16, 16`, which isn't there either. Also has an invalid `\A` escape in the docstring (SyntaxWarning) | +| 3 | Admits 8x16x16 while the shader instantiates 16-dim | **Yes** | `flash_attn_cm1.comp` L26-27 `MatBr=16, MatBc=16`, K=16 literals at L269-270. The patch (L35-37) admits 8x16x16 without touching the shader | +| 4 | Claimed pipeline-failure fallback not implemented | **Yes** | Patch description L13-15 claims it, but the diff has no such code. Upstream `ggml_vk_create_pipeline_func` rethrows (L777-781) | +| 5 | Build script destructive | **Yes** | `build-xe2-coopmat.ps1`: `git checkout -f`, `git reset --hard`, `git clean -fd` (L38-40 in the pack file, i.e. lines 127-130 of the concatenated listing), `Remove-Item -Recurse -Force $cmakeBuildDir`, `Copy-Item ... -Force` into the output dir. It also applies every non-30503 `*.patch` with `git apply`, but the pack contains no PR #29357 patches, so the "vendored Intel FA" step is a no-op. It uses `-DGGML_NATIVE=ON` and `-DLLAMA_BUILD_TESTS=OFF`, so `test-backend-ops` cannot be run to validate | +| 6 | Benchmark 128 tokens, no DFlash/sustained contract | **Yes** | `bench-30503-prefill-and-q8kv.ps1`: `-n 128 -r 2`, llama-bench, no `-md`/DFlash, KV {f16,q8_0,q4_0}. Header promises 512/16384/32768 but loops 512/4096/16384. Engine names hard-code `b11526`. It scans `python*` processes as "contending" | +| 7 | Launcher picks ctx from file size | **Yes** | `launch-b60-vulkan-next.ps1`: `$sizeGiB -le 14.6 → 98304 else 65536`. No measured headroom. Also: `-StopOllamaFirst` calls `Stop-Process -Force` (forced closure). Adds `--spec-draft-backend-sampling`, which is a **no-op for DFlash2** (speculative.cpp L1101). Defaults to 65536 while the user actually runs 32768. Sets `--reasoning-budget 4096` globally | +| 8 | Router xhigh on simple first turns; doesn't preserve nested/canonical | **Yes, tested** | `len(messages) <= 2 → ("xhigh", 4096)` (router L57-59). Unit tests in `tests/test_reasoning_resolver.py::PackRouterRegression` (pass = defect confirmed): a system+user "hello" gets xhigh; a nested `chat_template_kwargs.reasoning_effort="low"` is clobbered by an injected top-level `xhigh` (the server gives top-level precedence); effort is injected even when `enable_thinking=false`; `thinking_budget_tokens` is added alongside a canonical `reasoning_budget_tokens`; the caller's dict is mutated in place | +| 9 | Linux/SYCL/container recipes need security review | **Yes** | docker-compose: `privileged: true`, `network_mode: host`, `restart: unless-stopped`; vLLM: `--privileged --network host`, HF cache mounted rw; podman: `--security-opt label=disable`. SYCL build: `git merge ... \|\| true` and `git apply ... \|\| true` (failures ignored); third-party branches unpinned (`torchit1/*`, cookbook clone at HEAD) | +| 10 | Non-transferable figures | **Yes** | The benchmark table mixes B70/B65 (32 GB, 608 GB/s), B580, vLLM multi-client aggregate (296.5 t/s at 64 clients), cached-prefix prefill (1388.7 warm), other models/quants. Its own CSV lists the baseline as "Vulkan + PR #29357 … b11526" with 64K context, which contradicts the user's 32K | + +## Additional defects found +11. **Impossible display fix:** docs §2.4 says to move the monitors to the CPU iGPU / set BIOS Primary Display = iGPU. **The Ryzen 7 3700X has no iGPU**, so this cannot be done on this machine. +12. **Clock/voltage advice:** docs §2.5 recommends a +100-150 MHz V-F offset and power-limit changes. That violates the no-clock/voltage rule. Not acceptable as a default. +13. **"Hidden IQ" diagnosis doesn't apply:** the user's GGUF header has 0 IQ/Q2_K/Q3_K tensors. The repack script's advice (`llama-quantize --pure --token-embedding-type q4_k`) is a weight change and is **not lossless**. It also suggests downloading a third-party checkpoint. The XMX "dpas.8x8 linear INT" claims are unsourced, and the Vulkan path dequantises in shaders anyway. +14. **The #30503 framing misses the install's real FA path:** with f16 KV, PR #29357's Xe FA shaders (advertised 8x16x16) already handle prefill and verify. The patch would mainly affect q8_0 K/V FA (draft context / future q8_0 main KV). Its expected decode gain is not established. +15. **Unverified numbers presented as "verified":** "53.3 mean per-req", "0.788 acceptance", "16/16 tasks 60.5 s", "dwm 2.6-3.3 GB" and the "52.7 → 22.2 contention drop" (references a `gpu-contention-20261017.csv` not in the pack). Several Reddit thread IDs and blog figures could not be checked here (community, unverified). +16. **Unsafe patch-application idempotency:** the patcher treats any file containing the string "Issue #30503" as already patched (L31). A comment would make it skip. +17. **Task 2 encourages raising ctx to 96K** on the basis of the 2.17 GiB weight saving. That equates checkpoint savings with usable context, and the context math above shows 96K f16 still doesn't fit. diff --git a/docs/research/reasoning_policy.md b/docs/research/reasoning_policy.md new file mode 100644 index 0000000..5dd24d1 --- /dev/null +++ b/docs/research/reasoning_policy.md @@ -0,0 +1,26 @@ +# Reasoning policy (Section E) + +## Server facts at the revision (tools/server/server-common.cpp, b11524 lines ≈ recon) +1. Request `chat_template_kwargs` is merged per key over the CLI `--chat-template-kwargs` (L1400-1404). +2. Nested `enable_thinking` must be a JSON boolean; a quoted string is rejected (L1407-1414). +3. **Top-level `reasoning_effort` overwrites nested `chat_template_kwargs.reasoning_effort`** (L1417-1425). `"none"` also forces `enable_thinking=false`. Any other value does **not** turn thinking on. +4. Budget = `reasoning_budget_tokens`, else `thinking_budget_tokens`, else **CLI `--reasoning-budget` when the result is -1** (L1458-1462). An explicit `-1` from the caller cannot be told apart from "omitted". The budget only applies when the template exposes thinking end tags (L1464). +5. Anthropic `/v1/messages`: `thinking.type=enabled` without `budget_tokens` defaults to **10000** (server-chat.cpp ~L600-606). Responses API `reasoning.effort` maps to `reasoning_effort` (server-chat.cpp ~L300-306). +6. Effort levels supported by the ThinkingCap template (low/medium/xhigh; high→xhigh) come from the user's statement. **Not verified on the box: I don't have the template.** + +## Policy (caller wins, then route default, then global default; the gateway never escalates silently) +- **Code/MCP route:** default `enable_thinking=false`. A caller-supplied explicit `enable_thinking=true` is honoured. Effort alone never turns thinking on (matches server semantics). +- **general/plan/vision:** if effort is omitted, use `medium`/`medium`/`low` (never `xhigh`). Escalate to `xhigh` only when the caller asks. +- **Emit one canonical form:** nested `chat_template_kwargs.{enable_thinking, reasoning_effort}`, no top-level effort (so nothing can clobber the nested value), and an explicit integer `reasoning_budget_tokens` whenever thinking is on. +- **Reject conflicts** (top vs nested effort, `reasoning_budget_tokens` vs `thinking_budget_tokens`, `effort=none` + `enable_thinking=true`, string booleans, unknown efforts) with HTTP 400, rather than following the server's silent overwrite. `conflict_policy="server"` is available for compatibility. +- **Sampling presets:** record the *effective* temperature/top_p/top_k/presence in response metadata. Don't silently replace caller-sent values. The current 0.2 → 0.7 code-preset override is real, and Qwen's non-thinking guidance is 0.7, but it is not shown to cause slowdown. Deciding which value wins is a product decision that needs a quality A/B, not a speed claim. +- **Visible latency:** the MCP helper buffers the whole response, so native TTFT (0.864 s) is not what the user sees. Streaming natively is the only fix. Consuming SSE internally and returning once does not help. Measure `t_first_visible_mcp` separately (acceptance_test_spec.md). + +## Precedence tests required before integration +`tests/precedence_matrix.csv` has 22 request shapes with their expected resolved (enable_thinking, effort, budget, error). `tests/test_reasoning_resolver.py` runs them against `tools/reasoning_resolver_UNTESTED.py`, plus 5 regression tests that **demonstrate the pack router's defects**. On the box: **27/27 pass** (`tests/test_run_output.txt`). That is a unit test of the reference logic only. + +Integration tests still required (not run here): +1. For each matrix row, send the resolved body to the live llama-server (`/apply-template` or a `max_tokens=1` request) and assert that the rendered prompt has / lacks the think-prefix and shows the expected effort. +2. Budget enforcement: thinking on with budget 64 → assert reasoning tokens ≤ 64 + end tag. +3. No-thinking code mode: 20 MCP coding requests, assert zero reasoning content. +4. Governor interplay: the AUTO/MAX/BALANCED/LEAN profiles must not change the resolved fields. diff --git a/docs/research/sources.md b/docs/research/sources.md new file mode 100644 index 0000000..51a50bb --- /dev/null +++ b/docs/research/sources.md @@ -0,0 +1,24 @@ +# Sources + +## Primary code (read on the box) +- ggml-org/llama.cpp tag **b11526** = `5e4878e9787fff9bcc5c12478c47618b73268610` (2026-10-09). https://github.com/ggml-org/llama.cpp/tree/5e4878e9787fff9bcc5c12478c47618b73268610 +- **b11524** = `86a283532072722c5f3363d37d59a874d09fa99b`. https://github.com/ggml-org/llama.cpp/tree/86a283532072722c5f3363d37d59a874d09fa99b +- PR #29357 "vulkan : Intel FA kernel for prefill" (open): https://github.com/ggml-org/llama.cpp/pull/29357. Commits `61cc4c2` (Intel customized FA shader for prefill), `1a5137a` (max_bias/logit_softcap check), `b583d8d` (m16n16k16/SIMD32, 2026-10-14, *not* in the install per the pack). +- Reconstruction used for line numbers: b11524 + cherry-pick 61cc4c2 + 1a5137a (APPROXIMATE stand-in for the non-public `c85e6c598…`). Files cited: `ggml/src/ggml-vulkan/ggml-vulkan.cpp`; `vulkan-shaders/{mul_mm.comp, flash_attn_cm1.comp, flash_attn_prefill.comp, flash_attn_decode_phase_1.comp, flash_attn_decode_phase_2.comp}`; `ggml-vulkan-types.h`; `common/speculative.cpp`; `common/common.{h,cpp}`; `src/llama-context.cpp`; `src/llama-memory-recurrent.cpp`; `src/llama-arch.cpp`; `tools/server/{server-context.cpp, server-common.cpp, server-chat.cpp}`; `common/jinja/caps.cpp`. +- `c85e6c598f89d11c3591616355a138c33737cee3`: **not found** in ggml-org/llama.cpp (API 422; git upload-pack "not our ref"). + +## Issues / PRs +- Issue #30503 (open): https://github.com/ggml-org/llama.cpp/issues/30503. Single B580 report; the 896 → 2731 pp16384 figure is from Gemma-4-E4B (community, unverified). +- PR #24406 Intel Xe FA decode kernels (referenced in PR #29357). +- PR #14001 enabling KHR_coopmat on Xe2: https://github.com/ggml-org/llama.cpp/pull/14001 +- Issue #17628 / PR #23056: Intel Windows MMVQ policy (cited in the source comment). + +## Official specs / docs +- Intel Arc Pro B60 specifications (456 GB/s, 192-bit, 24 GB GDDR6, PCIe 5.0 x8, device ID 0xE211): https://www.intel.com/content/www/us/en/products/sku/243916/intel-arc-pro-b60-graphics/specifications.html +- Vulkan `VkCooperativeMatrixPropertiesKHR`: https://docs.vulkan.org/refpages/latest/refpages/source/VkCooperativeMatrixPropertiesKHR.html +- Qwen3.5-27B config: https://huggingface.co/Qwen/Qwen3.5-27B/raw/main/config.json (local copy `src/qwen35_27b_config.json`) +- DFlash paper arXiv:2602.06036: https://arxiv.org/abs/2602.06036 ; code https://github.com/z-lab/dflash ; draft configs https://huggingface.co/z-lab/Qwen3.5-27B-DFlash , https://huggingface.co/z-lab/Qwen3.6-27B-DFlash + +## Community (unverified, labelled wherever used) +- PR #29357 B580 benchmark comments (stornic56), SleepinDevil B70 numbers. +- All Reddit/blog figures in the pack's `docs/B60-RESEARCH-AND-BENCHMARKS.md` and `data/b60-external-benchmarks.csv`. Not re-checked; they do not transfer to B60 single-stream. From 28b11f89d280d4101ad2d33764b4c6d4276e0989 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:00:02 +1100 Subject: [PATCH 05/16] Research tools (offline) --- docs/research/tools/context_budget.py | 37 +++ .../research/tools/context_budget_output.json | 276 ++++++++++++++++++ docs/research/tools/dflash_timing.py | 114 ++++++++ docs/research/tools/dflash_timing_output.json | 119 ++++++++ .../tools/reasoning_resolver_UNTESTED.py | 110 +++++++ 5 files changed, 656 insertions(+) create mode 100644 docs/research/tools/context_budget.py create mode 100644 docs/research/tools/context_budget_output.json create mode 100644 docs/research/tools/dflash_timing.py create mode 100644 docs/research/tools/dflash_timing_output.json create mode 100644 docs/research/tools/reasoning_resolver_UNTESTED.py diff --git a/docs/research/tools/context_budget.py b/docs/research/tools/context_budget.py new file mode 100644 index 0000000..f4e2206 --- /dev/null +++ b/docs/research/tools/context_budget.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""VRAM feasibility calculator (ESTIMATES). Replace every *_est with values read from +the llama-server load log (model buffer / KV / RS / compute buffer lines) and the +Windows DXGI budget before trusting any row. Does NOT prove usable context.""" +import json +GiB = 2**30 +TOTAL = 24.0 # Intel spec 24 GB GDDR6; usable dedicated is lower (measure) +W_MAIN_GPU = (15.27, 16.2445) # low: token_embd kept on CPU (llama.cpp default, Q4_K/Q6_K est) ; high: whole file +W_DRAFT = 1.0645 +RS_EST = 8 * 48 * (48*128*128*4 + 3*10240*4) / GiB # 48 GDN layers, f32, (1+n_rs_seq=7) rows -> ~1.17 GiB +COMPUTE_EST = (0.8, 1.6) # main+draft compute/prealloc buffers at ub256 (est.) +DISPLAY = (0.75, 1.5, 3.0) # DWM/display on the only GPU; pack's repo log claims 2.6-3.3 GB (unverified) +RESERVE = 1.5 # governor headroom (pack's own guardrail: >=1.5 GiB free) +KV_F16_KIB = 64.5 # user estimate; public config gives exactly 64.0 (16 attn layers x 4 KV x 256 x 2 x 2B) +KV_Q8_KIB = KV_F16_KIB * 34/64 # q8_0 = 34 bytes per 32 elems vs 64 for f16 +DRAFT_KV_Q8_KIB = (2.1, 10.6) # 1 full-attn layer only (SWA) .. 5 layers full ctx, 8 KV x 128, q8_0 (est.) + +def row(ctx, kv_kib, scen): + w, comp, disp = scen + kv = ctx*kv_kib*1024/GiB + dkv = ctx*DRAFT_KV_Q8_KIB[1]*1024/GiB if scen is WORST else ctx*DRAFT_KV_Q8_KIB[0]*1024/GiB + 4*2048*2.1*1024/GiB + used = w + W_DRAFT + RS_EST + comp + disp + kv + dkv + return dict(ctx=ctx, main_kv_GiB=round(kv,3), draft_kv_GiB=round(dkv,3), used_GiB=round(used,2), + margin_vs_reserve_GiB=round(TOTAL-used-RESERVE,2), fits=TOTAL-used-RESERVE >= 0) + +BEST = (W_MAIN_GPU[0], COMPUTE_EST[0], DISPLAY[0]) +MID = (W_MAIN_GPU[0], COMPUTE_EST[1], DISPLAY[1]) +WORST = (W_MAIN_GPU[1], COMPUTE_EST[1], DISPLAY[2]) + +if __name__ == "__main__": + out = {"assumptions": dict(TOTAL=TOTAL, W_MAIN_GPU=W_MAIN_GPU, W_DRAFT=W_DRAFT, RS_EST_GiB=round(RS_EST,3), + COMPUTE_EST=COMPUTE_EST, DISPLAY=DISPLAY, RESERVE=RESERVE, KV_F16_KIB=KV_F16_KIB, KV_Q8_KIB=round(KV_Q8_KIB,2)), + "check_32K_to_96K_delta_f16_GiB": round((98304-32768)*KV_F16_KIB*1024/GiB, 3)} + for name, scen in (("best", BEST), ("mid", MID), ("worst", WORST)): + for kvname, kib in (("f16", KV_F16_KIB), ("q8_0", KV_Q8_KIB)): + out[f"{name}/{kvname}"] = [row(c, kib, scen) for c in (32768, 49152, 57344, 65536, 98304)] + print(json.dumps(out, indent=1)) diff --git a/docs/research/tools/context_budget_output.json b/docs/research/tools/context_budget_output.json new file mode 100644 index 0000000..04a2fe9 --- /dev/null +++ b/docs/research/tools/context_budget_output.json @@ -0,0 +1,276 @@ +{ + "assumptions": { + "TOTAL": 24.0, + "W_MAIN_GPU": [ + 15.27, + 16.2445 + ], + "W_DRAFT": 1.0645, + "RS_EST_GiB": 1.169, + "COMPUTE_EST": [ + 0.8, + 1.6 + ], + "DISPLAY": [ + 0.75, + 1.5, + 3.0 + ], + "RESERVE": 1.5, + "KV_F16_KIB": 64.5, + "KV_Q8_KIB": 34.27 + }, + "check_32K_to_96K_delta_f16_GiB": 4.031, + "best/f16": [ + { + "ctx": 32768, + "main_kv_GiB": 2.016, + "draft_kv_GiB": 0.082, + "used_GiB": 21.15, + "margin_vs_reserve_GiB": 1.35, + "fits": true + }, + { + "ctx": 49152, + "main_kv_GiB": 3.023, + "draft_kv_GiB": 0.115, + "used_GiB": 22.19, + "margin_vs_reserve_GiB": 0.31, + "fits": true + }, + { + "ctx": 57344, + "main_kv_GiB": 3.527, + "draft_kv_GiB": 0.131, + "used_GiB": 22.71, + "margin_vs_reserve_GiB": -0.21, + "fits": false + }, + { + "ctx": 65536, + "main_kv_GiB": 4.031, + "draft_kv_GiB": 0.148, + "used_GiB": 23.23, + "margin_vs_reserve_GiB": -0.73, + "fits": false + }, + { + "ctx": 98304, + "main_kv_GiB": 6.047, + "draft_kv_GiB": 0.213, + "used_GiB": 25.31, + "margin_vs_reserve_GiB": -2.81, + "fits": false + } + ], + "best/q8_0": [ + { + "ctx": 32768, + "main_kv_GiB": 1.071, + "draft_kv_GiB": 0.082, + "used_GiB": 20.21, + "margin_vs_reserve_GiB": 2.29, + "fits": true + }, + { + "ctx": 49152, + "main_kv_GiB": 1.606, + "draft_kv_GiB": 0.115, + "used_GiB": 20.77, + "margin_vs_reserve_GiB": 1.73, + "fits": true + }, + { + "ctx": 57344, + "main_kv_GiB": 1.874, + "draft_kv_GiB": 0.131, + "used_GiB": 21.06, + "margin_vs_reserve_GiB": 1.44, + "fits": true + }, + { + "ctx": 65536, + "main_kv_GiB": 2.142, + "draft_kv_GiB": 0.148, + "used_GiB": 21.34, + "margin_vs_reserve_GiB": 1.16, + "fits": true + }, + { + "ctx": 98304, + "main_kv_GiB": 3.212, + "draft_kv_GiB": 0.213, + "used_GiB": 22.48, + "margin_vs_reserve_GiB": 0.02, + "fits": true + } + ], + "mid/f16": [ + { + "ctx": 32768, + "main_kv_GiB": 2.016, + "draft_kv_GiB": 0.082, + "used_GiB": 22.7, + "margin_vs_reserve_GiB": -0.2, + "fits": false + }, + { + "ctx": 49152, + "main_kv_GiB": 3.023, + "draft_kv_GiB": 0.115, + "used_GiB": 23.74, + "margin_vs_reserve_GiB": -1.24, + "fits": false + }, + { + "ctx": 57344, + "main_kv_GiB": 3.527, + "draft_kv_GiB": 0.131, + "used_GiB": 24.26, + "margin_vs_reserve_GiB": -1.76, + "fits": false + }, + { + "ctx": 65536, + "main_kv_GiB": 4.031, + "draft_kv_GiB": 0.148, + "used_GiB": 24.78, + "margin_vs_reserve_GiB": -2.28, + "fits": false + }, + { + "ctx": 98304, + "main_kv_GiB": 6.047, + "draft_kv_GiB": 0.213, + "used_GiB": 26.86, + "margin_vs_reserve_GiB": -4.36, + "fits": false + } + ], + "mid/q8_0": [ + { + "ctx": 32768, + "main_kv_GiB": 1.071, + "draft_kv_GiB": 0.082, + "used_GiB": 21.76, + "margin_vs_reserve_GiB": 0.74, + "fits": true + }, + { + "ctx": 49152, + "main_kv_GiB": 1.606, + "draft_kv_GiB": 0.115, + "used_GiB": 22.32, + "margin_vs_reserve_GiB": 0.18, + "fits": true + }, + { + "ctx": 57344, + "main_kv_GiB": 1.874, + "draft_kv_GiB": 0.131, + "used_GiB": 22.61, + "margin_vs_reserve_GiB": -0.11, + "fits": false + }, + { + "ctx": 65536, + "main_kv_GiB": 2.142, + "draft_kv_GiB": 0.148, + "used_GiB": 22.89, + "margin_vs_reserve_GiB": -0.39, + "fits": false + }, + { + "ctx": 98304, + "main_kv_GiB": 3.212, + "draft_kv_GiB": 0.213, + "used_GiB": 24.03, + "margin_vs_reserve_GiB": -1.53, + "fits": false + } + ], + "worst/f16": [ + { + "ctx": 32768, + "main_kv_GiB": 2.016, + "draft_kv_GiB": 0.331, + "used_GiB": 25.42, + "margin_vs_reserve_GiB": -2.92, + "fits": false + }, + { + "ctx": 49152, + "main_kv_GiB": 3.023, + "draft_kv_GiB": 0.497, + "used_GiB": 26.6, + "margin_vs_reserve_GiB": -4.1, + "fits": false + }, + { + "ctx": 57344, + "main_kv_GiB": 3.527, + "draft_kv_GiB": 0.58, + "used_GiB": 27.18, + "margin_vs_reserve_GiB": -4.68, + "fits": false + }, + { + "ctx": 65536, + "main_kv_GiB": 4.031, + "draft_kv_GiB": 0.662, + "used_GiB": 27.77, + "margin_vs_reserve_GiB": -5.27, + "fits": false + }, + { + "ctx": 98304, + "main_kv_GiB": 6.047, + "draft_kv_GiB": 0.994, + "used_GiB": 30.12, + "margin_vs_reserve_GiB": -7.62, + "fits": false + } + ], + "worst/q8_0": [ + { + "ctx": 32768, + "main_kv_GiB": 1.071, + "draft_kv_GiB": 0.331, + "used_GiB": 24.48, + "margin_vs_reserve_GiB": -1.98, + "fits": false + }, + { + "ctx": 49152, + "main_kv_GiB": 1.606, + "draft_kv_GiB": 0.497, + "used_GiB": 25.18, + "margin_vs_reserve_GiB": -2.68, + "fits": false + }, + { + "ctx": 57344, + "main_kv_GiB": 1.874, + "draft_kv_GiB": 0.58, + "used_GiB": 25.53, + "margin_vs_reserve_GiB": -3.03, + "fits": false + }, + { + "ctx": 65536, + "main_kv_GiB": 2.142, + "draft_kv_GiB": 0.662, + "used_GiB": 25.88, + "margin_vs_reserve_GiB": -3.38, + "fits": false + }, + { + "ctx": 98304, + "main_kv_GiB": 3.212, + "draft_kv_GiB": 0.994, + "used_GiB": 27.28, + "margin_vs_reserve_GiB": -4.78, + "fits": false + } + ] +} diff --git a/docs/research/tools/dflash_timing.py b/docs/research/tools/dflash_timing.py new file mode 100644 index 0000000..9ca72ae --- /dev/null +++ b/docs/research/tools/dflash_timing.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Reproduces the DFlash timing arithmetic in dflash_timing_analysis.md. + +Inputs are ONLY the numbers the user reported for the latest traced run plus +public specs. No new measurements are introduced. Every derived value is an +arithmetic consequence of those inputs; anything that would need a split of the +uninstrumented remainder is printed as UNKNOWN. +""" +from __future__ import annotations +import json + +# ---- user-reported traced run (authoritative per brief) ---- +RUN = dict( + output_tokens=2304, + native_gen_s=60.898, + wall_s=61.764, + first_content_s=0.864, + rounds=458, + drafted=2576, + accepted=1789, + draft_timer_s=9.535, # excludes feature readback/injection path + draft_n_max=7, +) + +# ---- public specs / configs ---- +B60_BW_GBPS = 456.0 # Intel ARK, Arc Pro B60 (decimal GB/s) +MAIN_FILE_BYTES = 17_442_400_352 +# Qwen3.5-27B public config (Qwen3.8 assumed same shape - UNVERIFIED) +VOCAB, HIDDEN = 248_320, 5_120 + + +def derive(r=RUN): + d = {} + d["tps_native"] = r["output_tokens"] / r["native_gen_s"] + d["tokens_per_round"] = r["output_tokens"] / r["rounds"] + d["drafted_per_round"] = r["drafted"] / r["rounds"] + d["accepted_per_round"] = r["accepted"] / r["rounds"] + d["acceptance_rate"] = r["accepted"] / r["drafted"] + # each verification round emits accepted + 1 (bonus/correction) tokens + d["tokens_explained_by_rounds"] = r["accepted"] + r["rounds"] + d["tokens_unexplained"] = r["output_tokens"] - d["tokens_explained_by_rounds"] + d["ms_per_round"] = 1000 * r["native_gen_s"] / r["rounds"] + d["draft_ms_per_round"] = 1000 * r["draft_timer_s"] / r["rounds"] + d["remainder_ms_per_round"] = d["ms_per_round"] - d["draft_ms_per_round"] + d["draft_share"] = r["draft_timer_s"] / r["native_gen_s"] + d["wall_minus_native_s"] = r["wall_s"] - r["native_gen_s"] + + # bandwidth floor of ONE target forward (all VRAM-resident weights read once) + emb_q4k = VOCAB * HIDDEN * 4.5 / 8 # token_embd if Q4_K (4.5 bpw) + emb_q6k = VOCAB * HIDDEN * 6.5625 / 8 # token_embd if Q6_K + for label, emb in (("emb_on_gpu", 0.0), ("emb_cpu_q4k", emb_q4k), ("emb_cpu_q6k", emb_q6k)): + bytes_read = MAIN_FILE_BYTES - emb + t_ms = 1000 * bytes_read / (B60_BW_GBPS * 1e9) + d[f"fwd_floor_ms[{label}]"] = t_ms + d[f"nonspec_tps_ceiling[{label}]"] = 1000 / t_ms + + # targets: what must change to reach 40 / 50 t/s on this same contract + for tgt in (40, 45, 50): + d[f"round_ms_needed_at_current_tpr[{tgt}]"] = 1000 * d["tokens_per_round"] / tgt + d[f"tpr_needed_at_current_round_ms[{tgt}]"] = tgt * d["ms_per_round"] / 1000 + # optimistic bound: verify at bandwidth floor + measured draft time, nothing else + floor = d["fwd_floor_ms[emb_on_gpu]"] + d["ideal_round_ms(verify_floor+draft)"] = floor + d["draft_ms_per_round"] + d["ideal_tps_at_current_tpr"] = 1000 * d["tokens_per_round"] / d["ideal_round_ms(verify_floor+draft)"] + d["remainder_minus_verify_floor_ms"] = d["remainder_ms_per_round"] - floor + d["UNKNOWN_split"] = ("target verify GPU time, feature readback (GPU->host), CPU concat, " + "inject upload + inject decode, synchronize waits, lattice readback, " + "CPU selector argmax, sampling/accept, server loop overhead") + return d + + +def sustained_runs(): + runs = { + "original MAX14/draft7": [38.79, 42.71, 43.91], + "MMVQ override removed": [36.01, 37.16, 36.92], + "8 workers (BALANCED, not isolated)": [38.36, 37.28, 42.81], + "MAX14/draft5": [37.68, 40.76, 41.24], + } + out = {} + for k, v in runs.items(): + m = sum(v) / len(v) + sd = (sum((x - m) ** 2 for x in v) / (len(v) - 1)) ** 0.5 + out[k] = dict(mean=round(m, 3), sd=round(sd, 3), min=min(v), max=max(v), all_ge_40=all(x >= 40 for x in v)) + return out + + +if __name__ == "__main__": + d = derive() + print(json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in d.items()}, indent=2)) + print(json.dumps(sustained_runs(), indent=2)) + + +def feature_traffic(n_extract_options=(5, 8), pcie_gbps_practical=(10.0, 14.0), prompt_tokens=(2048, 8192, 32768)): + """Host traffic implied by common/speculative.cpp DFlash process(): + llama_get_embeddings_layer_inp() -> host copy of n_extract x n_embd_tgt f32 per token, + CPU memcpy concat, then upload again as batch_inject embeddings. + n_extract for the Qwen3.8 DFlash2 draft is UNVERIFIED (z-lab Qwen3.5-27B-DFlash: 8, Qwen3.6-27B-DFlash: 5).""" + out = {} + tpr_batch = RUN["drafted"] / RUN["rounds"] + 1 # tokens in each verify batch + for n in n_extract_options: + per_tok = n * HIDDEN * 4 + out[f"n_extract={n}"] = { + "bytes_per_token_KiB": per_tok / 1024, + "per_round_MiB_one_direction": per_tok * tpr_batch / 2**20, + "per_round_ms_transfer_at_practical_pcie": [round(1000 * per_tok * tpr_batch / (g * 1e9), 3) for g in pcie_gbps_practical], + "prefill_GiB_one_direction": {p: round(per_tok * p / 2**30, 3) for p in prompt_tokens}, + "prefill_s_one_direction_at_practical_pcie": {p: [round(per_tok * p / (g * 1e9), 3) for g in pcie_gbps_practical] for p in prompt_tokens}, + } + return out + + +if __name__ == "__main__": + print(json.dumps({"native_tps_if_first_token_excluded": round((RUN['output_tokens'] - 1) / RUN['native_gen_s'], 4)}, indent=2)) + print(json.dumps(feature_traffic(), indent=2)) diff --git a/docs/research/tools/dflash_timing_output.json b/docs/research/tools/dflash_timing_output.json new file mode 100644 index 0000000..cca85bf --- /dev/null +++ b/docs/research/tools/dflash_timing_output.json @@ -0,0 +1,119 @@ +{ + "tps_native": 37.8338, + "tokens_per_round": 5.0306, + "drafted_per_round": 5.6245, + "accepted_per_round": 3.9061, + "acceptance_rate": 0.6945, + "tokens_explained_by_rounds": 2247, + "tokens_unexplained": 57, + "ms_per_round": 132.9651, + "draft_ms_per_round": 20.8188, + "remainder_ms_per_round": 112.1463, + "draft_share": 0.1566, + "wall_minus_native_s": 0.866, + "fwd_floor_ms[emb_on_gpu]": 38.2509, + "nonspec_tps_ceiling[emb_on_gpu]": 26.1432, + "fwd_floor_ms[emb_cpu_q4k]": 36.6825, + "nonspec_tps_ceiling[emb_cpu_q4k]": 27.2609, + "fwd_floor_ms[emb_cpu_q6k]": 35.9637, + "nonspec_tps_ceiling[emb_cpu_q6k]": 27.8058, + "round_ms_needed_at_current_tpr[40]": 125.7642, + "tpr_needed_at_current_round_ms[40]": 5.3186, + "round_ms_needed_at_current_tpr[45]": 111.7904, + "tpr_needed_at_current_round_ms[45]": 5.9834, + "round_ms_needed_at_current_tpr[50]": 100.6114, + "tpr_needed_at_current_round_ms[50]": 6.6483, + "ideal_round_ms(verify_floor+draft)": 59.0697, + "ideal_tps_at_current_tpr": 85.1633, + "remainder_minus_verify_floor_ms": 73.8954, + "UNKNOWN_split": "target verify GPU time, feature readback (GPU->host), CPU concat, inject upload + inject decode, synchronize waits, lattice readback, CPU selector argmax, sampling/accept, server loop overhead" +} +{ + "original MAX14/draft7": { + "mean": 41.803, + "sd": 2.678, + "min": 38.79, + "max": 43.91, + "all_ge_40": false + }, + "MMVQ override removed": { + "mean": 36.697, + "sd": 0.607, + "min": 36.01, + "max": 37.16, + "all_ge_40": false + }, + "8 workers (BALANCED, not isolated)": { + "mean": 39.483, + "sd": 2.931, + "min": 37.28, + "max": 42.81, + "all_ge_40": false + }, + "MAX14/draft5": { + "mean": 39.893, + "sd": 1.932, + "min": 37.68, + "max": 41.24, + "all_ge_40": false + } +} +{ + "native_tps_if_first_token_excluded": 37.8173 +} +{ + "n_extract=5": { + "bytes_per_token_KiB": 100.0, + "per_round_MiB_one_direction": 0.6469193504366813, + "per_round_ms_transfer_at_practical_pcie": [ + 0.068, + 0.048 + ], + "prefill_GiB_one_direction": { + "2048": 0.195, + "8192": 0.781, + "32768": 3.125 + }, + "prefill_s_one_direction_at_practical_pcie": { + "2048": [ + 0.021, + 0.015 + ], + "8192": [ + 0.084, + 0.06 + ], + "32768": [ + 0.336, + 0.24 + ] + } + }, + "n_extract=8": { + "bytes_per_token_KiB": 160.0, + "per_round_MiB_one_direction": 1.0350709606986899, + "per_round_ms_transfer_at_practical_pcie": [ + 0.109, + 0.078 + ], + "prefill_GiB_one_direction": { + "2048": 0.312, + "8192": 1.25, + "32768": 5.0 + }, + "prefill_s_one_direction_at_practical_pcie": { + "2048": [ + 0.034, + 0.024 + ], + "8192": [ + 0.134, + 0.096 + ], + "32768": [ + 0.537, + 0.383 + ] + } + } +} diff --git a/docs/research/tools/reasoning_resolver_UNTESTED.py b/docs/research/tools/reasoning_resolver_UNTESTED.py new file mode 100644 index 0000000..cb68267 --- /dev/null +++ b/docs/research/tools/reasoning_resolver_UNTESTED.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""UNTESTED-IN-PRODUCTION reference resolver for the gateway (unit-tested on the box only). +Goal: emit ONE canonical, explicit request to llama-server so server-side precedence +(tools/server/server-common.cpp ~L1399-1465 at the reconstructed revision) can never surprise us: + * top-level reasoning_effort OVERWRITES chat_template_kwargs.reasoning_effort (server) + * reasoning_effort=="none" forces enable_thinking=false (server) + * budget = reasoning_budget_tokens, else thinking_budget_tokens, else CLI default when -1 (server) +Policy (caller wins, then route default, then global default; never escalate silently):""" +from __future__ import annotations +import copy + +VALID_EFFORT = {"none", "low", "medium", "high", "xhigh"} +TEMPLATE_EFFORT = {"low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh"} # per user: template maps high->xhigh (UNVERIFIED locally) +ROUTE_DEFAULTS = { # effort used only when the caller is silent + "code": {"enable_thinking": False, "effort": None, "budget": 0}, + "general": {"enable_thinking": True, "effort": "medium", "budget": 1536}, + "plan": {"enable_thinking": True, "effort": "medium", "budget": 2048}, + "vision": {"enable_thinking": True, "effort": "low", "budget": 1024}, +} + +class PolicyError(ValueError): + pass + +def _bool(v, name): + if isinstance(v, bool): + return v + raise PolicyError(f"{name} must be boolean, got {type(v).__name__}") + +def resolve(body: dict, route: str = "general", conflict_policy: str = "reject") -> dict: + """Returns a new body with canonical fields + '_resolution' audit dict (strip before sending if desired).""" + if route not in ROUTE_DEFAULTS: + raise PolicyError(f"unknown route {route}") + b = copy.deepcopy(body) + ctk = dict(b.get("chat_template_kwargs") or {}) + rd = ROUTE_DEFAULTS[route] + src = {} + + # ---- effort: top-level vs nested ---- + top = b.get("reasoning_effort") + nested = ctk.get("reasoning_effort") + if b.get("reasoning") and isinstance(b["reasoning"], dict) and "effort" in b["reasoning"] and top is None: + top = b["reasoning"]["effort"] # Responses API shape + for v, n in ((top, "reasoning_effort"), (nested, "chat_template_kwargs.reasoning_effort")): + if v is not None and v not in VALID_EFFORT: + raise PolicyError(f"invalid {n}={v!r}") + if top is not None and nested is not None and top != nested: + if conflict_policy == "reject": + raise PolicyError(f"conflicting effort: top-level {top!r} vs nested {nested!r}") + effort, src["effort"] = top, "caller_top_level(server_semantics)" + elif top is not None: + effort, src["effort"] = top, "caller_top_level" + elif nested is not None: + effort, src["effort"] = nested, "caller_nested" + else: + effort, src["effort"] = None, "unset" + + # ---- enable_thinking ---- + et_top = b.get("enable_thinking") + et_nested = ctk.get("enable_thinking") + if et_top is not None and et_nested is not None and _bool(et_top, "enable_thinking") != _bool(et_nested, "chat_template_kwargs.enable_thinking"): + raise PolicyError("conflicting enable_thinking (top-level vs nested)") + if et_nested is not None: + thinking, src["thinking"] = _bool(et_nested, "chat_template_kwargs.enable_thinking"), "caller_nested" + elif et_top is not None: + thinking, src["thinking"] = _bool(et_top, "enable_thinking"), "caller_top_level" + elif effort == "none": + thinking, src["thinking"] = False, "effort_none" + elif isinstance(b.get("thinking"), dict) and b["thinking"].get("type") in ("enabled", "disabled"): + thinking, src["thinking"] = b["thinking"]["type"] == "enabled", "caller_anthropic" + else: + thinking, src["thinking"] = rd["enable_thinking"], f"route_default:{route}" + if effort == "none" and thinking: + raise PolicyError("reasoning_effort='none' contradicts enable_thinking=true") + if effort is None and thinking: + effort, src["effort"] = rd["effort"] or "medium", f"route_default:{route}" + + # ---- budget ---- + rbt, tbt = b.get("reasoning_budget_tokens"), b.get("thinking_budget_tokens") + ab = b["thinking"].get("budget_tokens") if isinstance(b.get("thinking"), dict) else None + for v, n in ((rbt, "reasoning_budget_tokens"), (tbt, "thinking_budget_tokens"), (ab, "thinking.budget_tokens")): + if v is not None and (not isinstance(v, int) or isinstance(v, bool) or v < -1): + raise PolicyError(f"invalid {n}={v!r}") + if rbt is not None and tbt is not None and rbt != tbt and conflict_policy == "reject": + raise PolicyError("conflicting reasoning_budget_tokens vs thinking_budget_tokens") + if rbt is not None and rbt != -1: + budget, src["budget"] = rbt, "caller_reasoning_budget_tokens" + elif tbt is not None and tbt != -1: + budget, src["budget"] = tbt, "caller_thinking_budget_tokens" + elif ab is not None and ab != -1: + budget, src["budget"] = ab, "caller_anthropic_budget" + elif rbt == -1 or tbt == -1: + budget, src["budget"] = -1, "caller_explicit_unlimited" + else: + budget, src["budget"] = rd["budget"], f"route_default:{route}" + + # ---- emit canonical: nested only (no top-level effort, so nothing can clobber), explicit numbers ---- + b.pop("reasoning_effort", None); b.pop("enable_thinking", None); b.pop("thinking_budget_tokens", None); b.pop("reasoning", None) + ctk["enable_thinking"] = thinking + if thinking: + ctk["reasoning_effort"] = TEMPLATE_EFFORT[effort] + else: + ctk.pop("reasoning_effort", None) + b["chat_template_kwargs"] = ctk + if thinking: + b["reasoning_budget_tokens"] = budget + else: + b.pop("reasoning_budget_tokens", None) + b["_resolution"] = {"enable_thinking": thinking, "effort": TEMPLATE_EFFORT.get(effort) if thinking else None, + "budget": budget if thinking else None, "source": src, "route": route} + return b From d914e9a5578501c2f0c123d95c4231d049591fa3 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:00:58 +1100 Subject: [PATCH 06/16] Research tests (untested resolver) --- docs/research/tests/precedence_matrix.csv | 23 ++++++++ .../research/tests/test_reasoning_resolver.py | 54 +++++++++++++++++++ docs/research/tests/test_run_output.txt | 32 +++++++++++ 3 files changed, 109 insertions(+) create mode 100644 docs/research/tests/precedence_matrix.csv create mode 100644 docs/research/tests/test_reasoning_resolver.py create mode 100644 docs/research/tests/test_run_output.txt diff --git a/docs/research/tests/precedence_matrix.csv b/docs/research/tests/precedence_matrix.csv new file mode 100644 index 0000000..72b14a4 --- /dev/null +++ b/docs/research/tests/precedence_matrix.csv @@ -0,0 +1,23 @@ +id,route,request_json,expected_enable_thinking,expected_effort,expected_budget,expected_error,rationale +P01,code,{},false,,,,code route default = no thinking +P02,code,"{""chat_template_kwargs"":{""enable_thinking"":false}}",false,,,,MCP coding request preserved +P03,code,"{""chat_template_kwargs"":{""enable_thinking"":true}}",true,medium,0,,explicit caller wins over route default; budget from code route default +P04,general,{},true,medium,1536,,omitted effort must NOT become xhigh +P05,plan,{},true,medium,2048,,omitted effort must NOT become xhigh +P06,vision,{},true,low,1024,, +P07,general,"{""reasoning_effort"":""xhigh""}",true,xhigh,1536,,explicit top-level effort kept +P08,general,"{""chat_template_kwargs"":{""reasoning_effort"":""low""}}",true,low,1536,,nested effort preserved (pack router would clobber this) +P09,general,"{""reasoning_effort"":""xhigh"",""chat_template_kwargs"":{""reasoning_effort"":""low""}}",,,,PolicyError,conflict rejected instead of silent server-side overwrite +P10,general,"{""reasoning_effort"":""high""}",true,xhigh,1536,,high maps to xhigh visibly +P11,general,"{""reasoning_effort"":""none""}",false,,,,none disables thinking +P12,general,"{""reasoning_effort"":""none"",""chat_template_kwargs"":{""enable_thinking"":true}}",,,,PolicyError,contradiction rejected +P13,general,"{""reasoning_budget_tokens"":512,""thinking_budget_tokens"":4096}",,,,PolicyError,budget conflict rejected +P14,general,"{""thinking_budget_tokens"":4096}",true,medium,4096,,legacy alias honoured +P15,general,"{""reasoning_budget_tokens"":-1}",true,medium,-1,,explicit -1 kept explicit (server would otherwise fall to CLI default) +P16,general,"{""thinking"":{""type"":""enabled"",""budget_tokens"":2000}}",true,medium,2000,,Anthropic shape +P17,general,"{""thinking"":{""type"":""disabled""}}",false,,,,Anthropic disabled +P18,code,"{""reasoning_effort"":""low""}",false,,,,effort alone does not enable thinking in code route (matches server: only none toggles) +P19,general,"{""reasoning_effort"":""ultra""}",,,,PolicyError,unknown effort rejected +P20,general,"{""chat_template_kwargs"":{""enable_thinking"":""false""}}",,,,PolicyError,string boolean rejected (server also rejects quoted string) +P21,general,"{""reasoning"":{""effort"":""low""}}",true,low,1536,,Responses API shape +P22,code,"{""enable_thinking"":false,""chat_template_kwargs"":{""enable_thinking"":true}}",,,,PolicyError,top vs nested enable_thinking conflict diff --git a/docs/research/tests/test_reasoning_resolver.py b/docs/research/tests/test_reasoning_resolver.py new file mode 100644 index 0000000..eaab19a --- /dev/null +++ b/docs/research/tests/test_reasoning_resolver.py @@ -0,0 +1,54 @@ +import csv, json, os, sys, unittest, importlib.util +HERE = os.path.dirname(__file__) +spec = importlib.util.spec_from_file_location("rr", os.path.join(HERE, "..", "tools", "reasoning_resolver_UNTESTED.py")) +rr = importlib.util.module_from_spec(spec); spec.loader.exec_module(rr) + +class Matrix(unittest.TestCase): + pass + +def make(row): + def t(self): + body = json.loads(row["request_json"]) + if row["expected_error"]: + with self.assertRaises(rr.PolicyError): + rr.resolve(body, row["route"]) + return + out = rr.resolve(body, row["route"]) + r = out["_resolution"] + self.assertEqual(r["enable_thinking"], row["expected_enable_thinking"] == "true") + self.assertEqual(r["effort"] or "", row["expected_effort"]) + self.assertEqual("" if r["budget"] is None else str(r["budget"]), row["expected_budget"]) + self.assertNotIn("reasoning_effort", out) # nothing top-level that could clobber nested + self.assertEqual(out["chat_template_kwargs"]["enable_thinking"], r["enable_thinking"]) + self.assertEqual(body, json.loads(row["request_json"])) # input not mutated + return t + +for row in csv.DictReader(open(os.path.join(HERE, "precedence_matrix.csv"))): + setattr(Matrix, f"test_{row['id']}", make(row)) + +class PackRouterRegression(unittest.TestCase): + """Demonstrates the pack router's defects (#8) against the same matrix shapes.""" + @classmethod + def setUpClass(cls): + p = os.path.join(HERE, "..", "inputs", "pack", "agents", "reasoning_effort_router.py") + if not os.path.exists(p): raise unittest.SkipTest("the rejected pack router is not shipped in arc-llm-lab (see docs/TRIED-AND-REJECTED.md)") + s = importlib.util.spec_from_file_location("pack_router", p); cls.m = importlib.util.module_from_spec(s); s.loader.exec_module(cls.m) + def test_first_turn_simple_gets_xhigh(self): + eff, bud = self.m.classify_turn_effort([{"role": "system", "content": "x"}, {"role": "user", "content": "hello"}]) + self.assertEqual((eff, bud), ("xhigh", 4096)) + def test_nested_effort_clobbered(self): + out = self.m.apply_dynamic_reasoning_to_payload({"messages": [{"role": "user", "content": "hi"}], "chat_template_kwargs": {"reasoning_effort": "low"}}) + self.assertEqual(out["reasoning_effort"], "xhigh") # server gives top-level precedence -> caller's 'low' lost + def test_no_thinking_code_mode_gets_effort_injected(self): + out = self.m.apply_dynamic_reasoning_to_payload({"messages": [{"role": "user", "content": "fix bug"}], "chat_template_kwargs": {"enable_thinking": False}}) + self.assertIn("reasoning_effort", out) + def test_canonical_budget_ignored(self): + out = self.m.apply_dynamic_reasoning_to_payload({"messages": [{"role": "user", "content": "hi"}], "reasoning_budget_tokens": 100}) + self.assertIn("thinking_budget_tokens", out) # adds alias alongside canonical field + def test_input_mutated(self): + p = {"messages": [{"role": "user", "content": "hi"}]} + self.m.apply_dynamic_reasoning_to_payload(p) + self.assertIn("reasoning_effort", p) + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/docs/research/tests/test_run_output.txt b/docs/research/tests/test_run_output.txt new file mode 100644 index 0000000..6ad30eb --- /dev/null +++ b/docs/research/tests/test_run_output.txt @@ -0,0 +1,32 @@ +test_P01 (__main__.Matrix.test_P01) ... ok +test_P02 (__main__.Matrix.test_P02) ... ok +test_P03 (__main__.Matrix.test_P03) ... ok +test_P04 (__main__.Matrix.test_P04) ... ok +test_P05 (__main__.Matrix.test_P05) ... ok +test_P06 (__main__.Matrix.test_P06) ... ok +test_P07 (__main__.Matrix.test_P07) ... ok +test_P08 (__main__.Matrix.test_P08) ... ok +test_P09 (__main__.Matrix.test_P09) ... ok +test_P10 (__main__.Matrix.test_P10) ... ok +test_P11 (__main__.Matrix.test_P11) ... ok +test_P12 (__main__.Matrix.test_P12) ... ok +test_P13 (__main__.Matrix.test_P13) ... ok +test_P14 (__main__.Matrix.test_P14) ... ok +test_P15 (__main__.Matrix.test_P15) ... ok +test_P16 (__main__.Matrix.test_P16) ... ok +test_P17 (__main__.Matrix.test_P17) ... ok +test_P18 (__main__.Matrix.test_P18) ... ok +test_P19 (__main__.Matrix.test_P19) ... ok +test_P20 (__main__.Matrix.test_P20) ... ok +test_P21 (__main__.Matrix.test_P21) ... ok +test_P22 (__main__.Matrix.test_P22) ... ok +test_canonical_budget_ignored (__main__.PackRouterRegression.test_canonical_budget_ignored) ... ok +test_first_turn_simple_gets_xhigh (__main__.PackRouterRegression.test_first_turn_simple_gets_xhigh) ... ok +test_input_mutated (__main__.PackRouterRegression.test_input_mutated) ... ok +test_nested_effort_clobbered (__main__.PackRouterRegression.test_nested_effort_clobbered) ... ok +test_no_thinking_code_mode_gets_effort_injected (__main__.PackRouterRegression.test_no_thinking_code_mode_gets_effort_injected) ... ok + +---------------------------------------------------------------------- +Ran 27 tests in 0.004s + +OK From b3bd8b74ef53d58a278f64b4683d7470f5f077db Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:01:27 +1100 Subject: [PATCH 07/16] Research: public Qwen3.5-27B config used for KV arithmetic --- docs/research/src/qwen35_27b_config.json | 135 +++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 docs/research/src/qwen35_27b_config.json diff --git a/docs/research/src/qwen35_27b_config.json b/docs/research/src/qwen35_27b_config.json new file mode 100644 index 0000000..bde2be7 --- /dev/null +++ b/docs/research/src/qwen35_27b_config.json @@ -0,0 +1,135 @@ +{ + "architectures": [ + "Qwen3_5ForConditionalGeneration" + ], + "image_token_id": 248056, + "model_type": "qwen3_5", + "text_config": { + "attention_bias": false, + "attention_dropout": 0.0, + "attn_output_gate": true, + "dtype": "bfloat16", + "eos_token_id": 248044, + "full_attention_interval": 4, + "head_dim": 256, + "hidden_act": "silu", + "hidden_size": 5120, + "initializer_range": 0.02, + "intermediate_size": 17408, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "linear_conv_kernel_dim": 4, + "linear_key_head_dim": 128, + "linear_num_key_heads": 16, + "linear_num_value_heads": 48, + "linear_value_head_dim": 128, + "max_position_embeddings": 262144, + "mlp_only_layers": [], + "model_type": "qwen3_5_text", + "mtp_num_hidden_layers": 1, + "mtp_use_dedicated_embeddings": false, + "num_attention_heads": 24, + "num_hidden_layers": 64, + "num_key_value_heads": 4, + "rms_norm_eps": 1e-06, + "use_cache": true, + "vocab_size": 248320, + "mamba_ssm_dtype": "float32", + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 11, + 11, + 10 + ], + "rope_type": "default", + "rope_theta": 10000000, + "partial_rotary_factor": 0.25 + } + }, + "tie_word_embeddings": false, + "transformers_version": "4.57.0.dev0", + "video_token_id": 248057, + "vision_config": { + "deepstack_visual_indexes": [], + "depth": 27, + "hidden_act": "gelu_pytorch_tanh", + "hidden_size": 1152, + "in_channels": 3, + "initializer_range": 0.02, + "intermediate_size": 4304, + "model_type": "qwen3_5", + "num_heads": 16, + "num_position_embeddings": 2304, + "out_hidden_size": 5120, + "patch_size": 16, + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "vision_end_token_id": 248054, + "vision_start_token_id": 248053 +} \ No newline at end of file From 77c436b2158e52f67061560246fb05eec4657754 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:01:56 +1100 Subject: [PATCH 08/16] Data: KV depth, footprint variants, context spill CSVs --- data/context-spill-20261018.csv | 4 ++++ data/footprint-variants-20261017.csv | 10 ++++++++++ data/kv-cache-depth-20261017.csv | 11 +++++++++++ 3 files changed, 25 insertions(+) create mode 100644 data/context-spill-20261018.csv create mode 100644 data/footprint-variants-20261017.csv create mode 100644 data/kv-cache-depth-20261017.csv diff --git a/data/context-spill-20261018.csv b/data/context-spill-20261018.csv new file mode 100644 index 0000000..6c3d0e4 --- /dev/null +++ b/data/context-spill-20261018.csv @@ -0,0 +1,4 @@ +date,ctx,free_margin_gib,llama_dedicated_gib,llama_shared_gib,others_gib,warm_gen_tok_s_min,warm_gen_tok_s_max,source +2026-10-16,40960,1.35,,,,48.0,48.0,maintainer governor.log (shared usage not recorded before 18 Oct) +2026-10-18,57344,1.35,19.70,2.90,1.74,20.0,22.3,maintainer governor.log + PDH readback (not published) +2026-10-18,36864,2.5,20.10,1.23,1.80,26.7,28.3,maintainer governor.log + PDH readback (not published) diff --git a/data/footprint-variants-20261017.csv b/data/footprint-variants-20261017.csv new file mode 100644 index 0000000..979a50f --- /dev/null +++ b/data/footprint-variants-20261017.csv @@ -0,0 +1,10 @@ +variant,ctx,dedicated_gib,shared_gib,adapter_free_gib,gen_tok_s,note,source +production (mmproj + DFlash2 + -ub 256),32768,19.14,1.68,2.89,29.86,,raw/ctxlab-20261017/run.log +no mmproj,32768,19.14,1.68,2.84,33.33,mmproj lives CPU-side: 0 GiB saved,raw/ctxlab-20261017/run.log +no drafter,32768,17.69,0.70,4.33,16.39,saves 1.45 GiB but loses the drafter,raw/ctxlab-20261017/run.log +-ub 128,32768,18.98,1.66,3.04,28.66,,raw/ctxlab-20261017/run.log +-ub 512,32768,19.50,1.72,2.51,25.70,,raw/ctxlab-20261017/run.log +-ub 256 -b 512,32768,19.14,1.65,2.87,26.58,,raw/ctxlab-20261017/run.log +drafter on CPU,32768,18.99,1.77,3.03,16.66,,raw/ctxlab-20261017/run.log +-ot blk.(62|63)=CPU,32768,19.53,1.29,2.55,31.90,more dedicated not less,raw/ctxlab-20261017/run.log +q8_0 main KV,32768,19.11,0.75,2.97,46.10,short prompt only; q8_0 KV collapses at depth (kv-cache-depth-20261017.csv),raw/ctxlab-20261017/run.log diff --git a/data/kv-cache-depth-20261017.csv b/data/kv-cache-depth-20261017.csv new file mode 100644 index 0000000..abc3328 --- /dev/null +++ b/data/kv-cache-depth-20261017.csv @@ -0,0 +1,11 @@ +tool,kv_cache,depth_tokens,prompt_tokens,prompt_tok_s,gen_tok_s,drafter,ctx,source +llama-bench,f16,0,512,484.53,13.01,none,,raw/ctxlab-20261017/kv-batch1.md +llama-bench,f16,16384,512,378.60,14.39,none,,raw/ctxlab-20261017/kv-batch1.md +llama-bench,f16,32768,512,354.27,12.69,none,,raw/ctxlab-20261017/kv-batch1.md +llama-bench,q8_0,0,512,587.56,15.68,none,,raw/ctxlab-20261017/kv-batch1.md +llama-bench,q8_0,16384,512,197.66,11.53,none,,raw/ctxlab-20261017/kv-batch1.md +llama-bench,q8_0,32768,512,122.83,9.51,none,,raw/ctxlab-20261017/kv-batch2.md +llama-server,f16,0,3875,473.11,30.93,DFlash2 n=7,40960,raw/ctxlab-20261017/server-depth-f16.log +llama-server,f16,25243,25243,428.15,25.48,DFlash2 n=7,40960,raw/ctxlab-20261017/server-depth-f16.log +llama-server,q8_0,0,3875,413.14,33.82,DFlash2 n=7,40960,raw/ctxlab-20261017/server-depth-q8_0.log +llama-server,q8_0,25243,25243,199.16,10.93,DFlash2 n=7,40960,raw/ctxlab-20261017/server-depth-q8_0.log From ec8f41dbf517ce0e856b48412cf37f11e48ee45a Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:02:23 +1100 Subject: [PATCH 09/16] Raw data index: ctxlab-20261017 --- data/raw/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/data/raw/README.md b/data/raw/README.md index 17c5893..b5e318b 100644 --- a/data/raw/README.md +++ b/data/raw/README.md @@ -17,6 +17,7 @@ If a number in a document points here, the line it comes from is in one of these | [build.log](build.log) | The Intel FA engine build | [engine/build.ps1](../../engine/build.ps1) | Compiler and commit versions, glslc capability lines | | [governor.log](governor.log) | The governor's launch and decision log for the day | [governor/](../../governor/) | Profile and context choices | | [config-history/](config-history/) | Copies of `governor/profiles.json` taken before the Intel FA switch and before the 64K tuning | `qwen snapshot` | What changed between configurations | +| [ctxlab-20261017/](ctxlab-20261017/README.md) | 17 Oct context lab: `llama-bench` f16 vs q8_0 KV at depth, llama-server depth runs with the drafter, and a 9-variant VRAM footprint sweep with per-process **shared** usage | maintainer ctxlab scripts (not published) | [kv-cache-depth-20261017.csv](../kv-cache-depth-20261017.csv), [footprint-variants-20261017.csv](../footprint-variants-20261017.csv), [FIELD-REPORT-20261018](../../docs/FIELD-REPORT-20261018.md) | ## Read these before quoting a number From 523869389504c10126acfa74310f8f6c0981f963 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:02:52 +1100 Subject: [PATCH 10/16] Raw ctxlab logs, 17 Oct (per-process lists redacted) --- data/raw/ctxlab-20261017/README.md | 16 + data/raw/ctxlab-20261017/kv-batch1.md | 50 ++ data/raw/ctxlab-20261017/kv-batch2.md | 15 + data/raw/ctxlab-20261017/run.log | 80 +++ data/raw/ctxlab-20261017/server-depth-f16.log | 607 +++++++++++++++++ .../raw/ctxlab-20261017/server-depth-q8_0.log | 612 ++++++++++++++++++ 6 files changed, 1380 insertions(+) create mode 100644 data/raw/ctxlab-20261017/README.md create mode 100644 data/raw/ctxlab-20261017/kv-batch1.md create mode 100644 data/raw/ctxlab-20261017/kv-batch2.md create mode 100644 data/raw/ctxlab-20261017/run.log create mode 100644 data/raw/ctxlab-20261017/server-depth-f16.log create mode 100644 data/raw/ctxlab-20261017/server-depth-q8_0.log diff --git a/data/raw/ctxlab-20261017/README.md b/data/raw/ctxlab-20261017/README.md new file mode 100644 index 0000000..fbbef28 --- /dev/null +++ b/data/raw/ctxlab-20261017/README.md @@ -0,0 +1,16 @@ +# Context lab, 17 October 2026 + +Raw output from one session on the maintainer's Arc Pro B60 24GB (Windows 11, Ryzen 7 3700X, 32 GB RAM), 16:08–17:05 local time, with the PC in normal use. Files are unedited, except that the per-process VRAM lists in the `baseline VRAM` lines were cut down to the adapter total, the free figure and the compositor (`dwm`). The application names and PIDs were removed. + +**Conditions:** llama.cpp b11526 (`c85e6c598`), the Intel FA build (b11524 plus the [vendored patches](../../../engine/patches/)), `GGML_VK_FORCE_MMVQ=1`, `-t 8`, `--prio -1`, ThinkingCap-Qwen3.8-27B Q4_K_M. Single runs unless `r=3`. + +| File | What it is | +|---|---| +| [kv-batch1.md](kv-batch1.md), [kv-batch2.md](kv-batch2.md) | `llama-bench -ngl 99 -fa on -lm dio -ub 256 -b 2048`, `pp512`/`tg32`, no drafter: f16 KV at depths 0, 16K and 32K; q8_0 KV at 0, 16K (batch 1) and 32K (batch 2) | +| [server-depth-f16.log](server-depth-f16.log), [server-depth-q8_0.log](server-depth-q8_0.log) | llama-server at ctx 40960 with the DFlash2 drafter (n_max 7, p-min 0.5, q8_0 draft KV): a 3,875-token prompt, then a 25,243-token prompt, 256 tokens generated each. The `print_timing` lines carry the numbers | +| [run.log](run.log) | Driver log for the whole session, including the 9-variant footprint sweep at ctx 32768 (`ded` = llama-server dedicated GiB, `shr` = its WDDM **shared** GiB, `free` = adapter free, `gen` = tok/s on a short request) | + +**Two things to know before quoting these:** + +- The `depth kv=…` lines in `run.log` near 16:56 are from an aborted first attempt: the long runs are empty. The depth figures come from the two `server-depth-*.log` files. +- `tg32` here (13.0 tok/s at depth 0) is about 19% below the 16.0–16.1 tok/s that the same kind of command gave on 12 Oct. That slowdown is an open issue ([field report](../../../docs/FIELD-REPORT-20261018.md#2-an-open-throughput-regression)), so compare these rows with each other, not with older tables. diff --git a/data/raw/ctxlab-20261017/kv-batch1.md b/data/raw/ctxlab-20261017/kv-batch1.md new file mode 100644 index 0000000..0256468 --- /dev/null +++ b/data/raw/ctxlab-20261017/kv-batch1.md @@ -0,0 +1,50 @@ +# bench-kv batch 1 2026-10-17T16:08:48 +baseline: ["16:08:48 GPU-exclusive begin: mode OFF + unload","16:08:56 baseline VRAM: {\"adapter_dedicated_gib\":2.42,\"free_gib\":21.46,\"dwm_dedicated_gib\":5.37}",{"adapter_dedicated_gib":2.42,"free_gib":21.46,"dwm_dedicated_gib":5.37}] + +## ctk=f16 ctv=f16 d=0 r=3 +ggml_vulkan: Found 1 Vulkan devices: +ggml_vulkan: 0 = Intel(R) Arc(TM) Pro B60 Graphics (Intel Corporation) | uma: 0 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat +| model | size | params | backend | ngl | n_ubatch | fa | lm | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | --: | -------: | --: | ---------: | --------------: | -------------------: | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | pp512 | 484.53 ± 19.30 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | tg32 | 13.01 ± 0.19 | + +build: c85e6c598 (11526) +elapsed 28 s + +## ctk=f16 ctv=f16 d=16384,32768 r=1 +ggml_vulkan: Found 1 Vulkan devices: +ggml_vulkan: 0 = Intel(R) Arc(TM) Pro B60 Graphics (Intel Corporation) | uma: 0 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat +| model | size | params | backend | ngl | n_ubatch | fa | lm | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | --: | -------: | --: | ---------: | --------------: | -------------------: | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | pp512 @ d16384 | 378.60 ± 0.00 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | tg32 @ d16384 | 14.39 ± 0.00 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | pp512 @ d32768 | 354.27 ± 0.00 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | 1 | dio | tg32 @ d32768 | 12.69 ± 0.00 | + +build: c85e6c598 (11526) +elapsed 134 s + +## ctk=q8_0 ctv=q8_0 d=0 r=3 +ggml_vulkan: Found 1 Vulkan devices: +ggml_vulkan: 0 = Intel(R) Arc(TM) Pro B60 Graphics (Intel Corporation) | uma: 0 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat +| model | size | params | backend | ngl | n_ubatch | type_k | type_v | fa | lm | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | --: | -------: | -----: | -----: | --: | ---------: | --------------: | -------------------: | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | pp512 | 587.56 ± 5.70 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | tg32 | 15.68 ± 0.17 | + +build: c85e6c598 (11526) +elapsed 24 s + +## ctk=q8_0 ctv=q8_0 d=16384 r=1 +ggml_vulkan: Found 1 Vulkan devices: +ggml_vulkan: 0 = Intel(R) Arc(TM) Pro B60 Graphics (Intel Corporation) | uma: 0 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat +| model | size | params | backend | ngl | n_ubatch | type_k | type_v | fa | lm | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | --: | -------: | -----: | -----: | --: | ---------: | --------------: | -------------------: | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | pp512 @ d16384 | 197.66 ± 0.00 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | tg32 @ d16384 | 11.53 ± 0.00 | + +build: c85e6c598 (11526) +elapsed 75 s + +DONE 2026-10-17T16:13:47 diff --git a/data/raw/ctxlab-20261017/kv-batch2.md b/data/raw/ctxlab-20261017/kv-batch2.md new file mode 100644 index 0000000..ac97303 --- /dev/null +++ b/data/raw/ctxlab-20261017/kv-batch2.md @@ -0,0 +1,15 @@ +# bench-kv batch 2 2026-10-17T16:38:41 +baseline: ["16:38:41 GPU-exclusive begin: mode OFF + unload","16:38:49 baseline VRAM: {\"adapter_dedicated_gib\":1.8,\"free_gib\":22.08,\"dwm_dedicated_gib\":5.32}",{"adapter_dedicated_gib":1.8,"free_gib":22.08,"dwm_dedicated_gib":5.32}] + +## ctk=q8_0 ctv=q8_0 d=32768 r=1 +ggml_vulkan: Found 1 Vulkan devices: +ggml_vulkan: 0 = Intel(R) Arc(TM) Pro B60 Graphics (Intel Corporation) | uma: 0 | fp16: 1 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat +| model | size | params | backend | ngl | n_ubatch | type_k | type_v | fa | lm | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | --: | -------: | -----: | -----: | --: | ---------: | --------------: | -------------------: | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | pp512 @ d32768 | 122.83 ± 0.00 | +| qwen35 27B Q4_K - Medium | 16.23 GiB | 27.32 B | Vulkan | 99 | 256 | q8_0 | q8_0 | 1 | dio | tg32 @ d32768 | 9.51 ± 0.00 | + +build: c85e6c598 (11526) +elapsed 181 s + +DONE 2026-10-17T16:42:21 diff --git a/data/raw/ctxlab-20261017/run.log b/data/raw/ctxlab-20261017/run.log new file mode 100644 index 0000000..6460e87 --- /dev/null +++ b/data/raw/ctxlab-20261017/run.log @@ -0,0 +1,80 @@ +16:08:48 GPU-exclusive begin: mode OFF + unload +16:08:56 baseline VRAM: {"adapter_dedicated_gib":2.42,"free_gib":21.46,"dwm_dedicated_gib":5.37} +16:08:56 bench ctk=f16 ctv=f16 d=0 r=3 +16:09:23 bench ctk=f16 ctv=f16 d=16384,32768 r=1 +16:11:37 bench ctk=q8_0 ctv=q8_0 d=0 r=3 +16:12:01 bench ctk=q8_0 ctv=q8_0 d=16384 r=1 +16:13:17 GPU-exclusive end: mode AUTO + load +16:13:42 load: qwen3.8-27b loaded in 22.3 s +16:13:47 status: Mode AUTO | profile LEAN | model starting | ctx | quiet 0 min | PC: idle 7s | RAM free 11.36 GB | VRAM used 22.43/23.9 GiB (model 3.52, others 18.91) | CPU others 18% | Governor: none (not loaded (starting)) | pressure 0s | agent active | DEGRADED: loop errors 0 (streak 0, heals 0) last_error= | sense: model starting: keeping last good others +16:38:41 GPU-exclusive begin: mode OFF + unload +16:38:49 baseline VRAM: {"adapter_dedicated_gib":1.8,"free_gib":22.08,"dwm_dedicated_gib":5.32} +16:38:49 bench ctk=q8_0 ctv=q8_0 d=32768 r=1 +16:41:50 GPU-exclusive end: mode AUTO + load +16:42:16 load: qwen3.8-27b loaded in 23.3 s +16:42:21 status: Mode AUTO | profile LEAN | model starting | ctx | quiet 0 min | PC: idle 240s | RAM free 11.42 GB | VRAM used 17.24/23.9 GiB (model 0, others 18.79) | CPU others 37% | Governor: none (not loaded (starting)) | pressure 0s | agent active | DEGRADED: loop errors 0 (streak 0, heals 0) last_error= | sense: model starting: keeping last good others +16:43:33 GPU-exclusive begin: mode OFF + unload +16:43:40 baseline VRAM: {"adapter_dedicated_gib":1.85,"free_gib":22.03,"dwm_dedicated_gib":5.32} +16:43:40 launch prod-mmproj-draft-ub256 +16:44:20 done prod-mmproj-draft-ub256 load=16.7s ded=19.14 shr=1.68 free=2.89 gen=29.86 +16:44:20 launch nommproj-draft-ub256 +16:45:00 done nommproj-draft-ub256 load=16.6s ded=19.14 shr=1.68 free=2.84 gen=33.33 +16:45:00 launch nommproj-nodraft-ub256 +16:45:46 done nommproj-nodraft-ub256 load=14.6s ded=17.69 shr=0.7 free=4.33 gen=16.39 +16:45:46 launch nommproj-draft-ub128 +16:46:24 done nommproj-draft-ub128 load=14.6s ded=18.98 shr=1.66 free=3.04 gen=28.66 +16:46:24 launch nommproj-draft-ub512 +16:47:05 done nommproj-draft-ub512 load=16.6s ded=19.5 shr=1.72 free=2.51 gen=25.70 +16:47:05 launch nommproj-draft-ub256-b512 +16:47:46 done nommproj-draft-ub256-b512 load=16.6s ded=19.14 shr=1.65 free=2.87 gen=26.58 +16:47:46 launch nommproj-draftcpu-ub256 +16:48:32 done nommproj-draftcpu-ub256 load=14.6s ded=18.99 shr=1.77 free=3.03 gen=16.66 +16:48:32 launch nommproj-draft-ub256-ot2cpu +16:49:09 done nommproj-draft-ub256-ot2cpu load=15.6s ded=19.53 shr=1.29 free=2.55 gen=31.90 +16:49:09 launch nommproj-draft-ub256-q8kv +16:49:45 done nommproj-draft-ub256-q8kv load=16.6s ded=19.11 shr=0.75 free=2.97 gen=46.10 +16:49:45 GPU-exclusive end: mode AUTO + load +16:50:12 load: qwen3.8-27b loaded in 24.2 s +16:50:17 status: Mode AUTO | profile MAX | model starting | ctx | quiet 0 min | PC: idle 721s | RAM free 11.19 GB | VRAM used 17.19/23.9 GiB (model 15.39, others 1.8) | CPU others 29% | Governor: none (not loaded (starting)) | pressure 0s | agent active | DEGRADED: loop errors 0 (streak 0, heals 0) last_error= | sense: model starting: keeping last good others +16:52:52 GPU-exclusive begin: mode OFF + unload +16:53:00 baseline VRAM: {"adapter_dedicated_gib":1.81,"free_gib":22.07,"dwm_dedicated_gib":5.32} +16:53:00 depth launch kv=f16,q8_0 +16:54:33 GPU-exclusive begin: mode OFF + unload +16:54:39 baseline VRAM: {"adapter_dedicated_gib":1.85,"free_gib":22.03,"dwm_dedicated_gib":5.51} +16:54:39 GPU-exclusive begin: mode OFF + unload +16:54:45 baseline VRAM: {"adapter_dedicated_gib":1.85,"free_gib":22.03,"dwm_dedicated_gib":5.51} +16:54:45 depth launch kv=f16 +16:55:31 GPU-exclusive begin: mode OFF + unload +16:56:00 baseline VRAM: {"adapter_dedicated_gib":1.89,"free_gib":21.99,"dwm_dedicated_gib":5.51} +16:56:00 depth launch kv=f16 +16:56:22 depth kv=f16 idle VRAM: ded=19.65 shr=1.69 free=2.35 +16:56:34 depth kv=f16 short run1 prompt_n=3862 pp=480.2 gen=16.90 wall=10 ded=19.74 shr=1.92 +16:56:38 depth kv=f16 short run2 prompt_n=260 pp=288.5 gen=20.20 wall=1.7 ded=19.74 shr=1.92 +16:56:40 depth kv=f16 long run1 prompt_n= pp= gen= wall= ded=19.74 shr=1.92 +16:56:42 depth kv=f16 long run2 prompt_n= pp= gen= wall= ded=19.74 shr=1.92 +16:56:45 depth launch kv=q8_0 +16:57:09 depth kv=q8_0 idle VRAM: ded=19.38 shr=0.75 free=2.61 +16:57:22 depth kv=q8_0 short run1 prompt_n=3862 pp=418.9 gen=22.09 wall=10.3 ded=19.51 shr=0.98 +16:57:25 depth kv=q8_0 short run2 prompt_n=260 pp=270.2 gen=29.63 wall=1.6 ded=19.51 shr=0.98 +16:57:28 depth kv=q8_0 long run1 prompt_n= pp= gen= wall= ded=19.51 shr=0.98 +16:57:30 depth kv=q8_0 long run2 prompt_n= pp= gen= wall= ded=19.51 shr=0.98 +16:57:33 GPU-exclusive end: mode AUTO + load +16:58:04 load: qwen3.8-27b loaded in 28.7 s +16:58:10 status: Mode AUTO | profile MAX | model starting | ctx | quiet 0 min | PC: idle 1190s | RAM free 11.19 GB | VRAM used 17.26/23.9 GiB (model 15.37, others 1.89) | CPU others 38% | Governor: none (not loaded (starting)) | pressure 0s | agent active | DEGRADED: loop errors 0 (streak 0, heals 0) last_error= | sense: model starting: keeping last good others +16:58:32 GPU-exclusive begin: mode OFF + unload +16:58:40 baseline VRAM: {"adapter_dedicated_gib":1.87,"free_gib":22.01,"dwm_dedicated_gib":5.51} +16:58:40 depth launch kv=f16 +16:59:02 depth kv=f16 idle VRAM: ded=19.65 shr=1.69 free=2.34 +16:59:20 depth kv=f16 short run1 prompt_n=3875 pp=473.1 gen=30.93 wall=16.5 ded=19.74 shr=1.92 +16:59:33 depth kv=f16 short run2 prompt_n=260 pp=330.6 gen=27.22 wall=10.2 ded=19.74 shr=1.92 +17:00:44 depth kv=f16 long run1 prompt_n=25243 pp=428.2 gen=25.48 wall=69 ded=19.75 shr=1.92 +17:00:58 depth kv=f16 long run2 prompt_n=260 pp=270.0 gen=22.96 wall=12.1 ded=19.75 shr=1.92 +17:01:01 depth launch kv=q8_0 +17:01:21 depth kv=q8_0 idle VRAM: ded=19.38 shr=0.75 free=2.62 +17:01:40 depth kv=q8_0 short run1 prompt_n=3875 pp=413.1 gen=33.82 wall=16.9 ded=19.51 shr=0.98 +17:01:51 depth kv=q8_0 short run2 prompt_n=260 pp=274.6 gen=30.62 wall=9.3 ded=19.51 shr=0.98 +17:04:23 depth kv=q8_0 long run1 prompt_n=25243 pp=199.2 gen=10.93 wall=150.1 ded=19.62 shr=0.98 +17:04:52 depth kv=q8_0 long run2 prompt_n=260 pp=108.2 gen=10.49 wall=26.8 ded=19.62 shr=0.98 +17:04:55 GPU-exclusive end: mode AUTO + load +17:05:33 load: qwen3.8-27b loaded in 35 s +17:05:39 status: Mode AUTO | profile MAX | model LOADED (BALANCED) | ctx 45056 | quiet 0.3 min | PC: idle 1653s | RAM free 6.38 GB | VRAM used 20.82/23.9 GiB (model 18.94, others 1.88) | CPU others 17% | Governor: none (steady) | pressure 0s | agent active diff --git a/data/raw/ctxlab-20261017/server-depth-f16.log b/data/raw/ctxlab-20261017/server-depth-f16.log new file mode 100644 index 0000000..e2e679b --- /dev/null +++ b/data/raw/ctxlab-20261017/server-depth-f16.log @@ -0,0 +1,607 @@ +0.00.141.220 I srv llama_server: initializing ... +0.00.141.249 I cmn common_param: common_params_print_info: build 11526 (c85e6c598) with GNU 16.2.0 for Windows AMD64 +0.00.141.250 I cmn common_param: common_params_print_info: verbosity = 4 (adjust with the `-lv N` CLI arg) +0.00.141.250 I cmn common_param: device_info: +0.00.142.425 I cmn common_param: - Vulkan0 : Intel(R) Arc(TM) Pro B60 Graphics (24454 MiB, 23685 MiB free) +0.00.142.430 I cmn common_param: - CPU : AMD Ryzen 7 3700X 8-Core Processor (32656 MiB, 12423 MiB free) +0.00.142.460 I cmn common_param: system_info: n_threads = 8 (n_threads_batch = 8) / 16 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | REPACK = 1 | +0.00.142.884 I srv init: using 15 threads for HTTP server +0.00.142.946 W srv llama_server: security: no API key is set and CORS allows all origins (see https://github.com/ggml-org/llama.cpp/pull/25655) +0.00.157.691 I srv load_model: loading model 'C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf' +0.00.157.693 I srv load_model: local path 'C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf' +0.00.258.200 I llama_model_loader: loaded meta data with 50 key-value pairs and 866 tensors from C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf (version GGUF V3 (latest)) +0.00.258.251 I llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output. +0.00.258.256 I llama_model_loader: - kv 0: general.architecture str = qwen35 +0.00.258.257 I llama_model_loader: - kv 1: general.type str = model +0.00.258.261 I llama_model_loader: - kv 2: general.sampling.top_k i32 = 20 +0.00.258.269 I llama_model_loader: - kv 3: general.sampling.top_p f32 = 0.950000 +0.00.258.271 I llama_model_loader: - kv 4: general.sampling.temp f32 = 1.000000 +0.00.258.272 I llama_model_loader: - kv 5: general.size_label str = 27B +0.00.258.273 I llama_model_loader: - kv 6: general.license str = apache-2.0 +0.00.258.274 I llama_model_loader: - kv 7: general.base_model.count u32 = 1 +0.00.258.275 I llama_model_loader: - kv 8: general.base_model.0.name str = Qwen3.8 27B +0.00.258.276 I llama_model_loader: - kv 9: general.base_model.0.organization str = Qwen +0.00.258.279 I llama_model_loader: - kv 10: general.base_model.0.repo_url str = https://huggingface.co/Qwen/Qwen3.8-27B +0.00.258.290 I llama_model_loader: - kv 11: general.tags arr[str,3] = ["qwen3_8", "token-efficient", "effic... +0.00.258.291 I llama_model_loader: - kv 12: qwen35.block_count u32 = 65 +0.00.258.292 I llama_model_loader: - kv 13: qwen35.context_length u32 = 262144 +0.00.258.293 I llama_model_loader: - kv 14: qwen35.embedding_length u32 = 5120 +0.00.258.294 I llama_model_loader: - kv 15: qwen35.feed_forward_length u32 = 17408 +0.00.258.294 I llama_model_loader: - kv 16: qwen35.attention.head_count u32 = 24 +0.00.258.295 I llama_model_loader: - kv 17: qwen35.attention.head_count_kv u32 = 4 +0.00.258.297 I llama_model_loader: - kv 18: qwen35.rope.dimension_sections arr[i32,4] = [11, 11, 10, 0] +0.00.258.299 I llama_model_loader: - kv 19: qwen35.rope.freq_base f32 = 10000000.000000 +0.00.258.300 I llama_model_loader: - kv 20: qwen35.attention.layer_norm_rms_epsilon f32 = 0.000001 +0.00.258.301 I llama_model_loader: - kv 21: qwen35.attention.key_length u32 = 256 +0.00.258.302 I llama_model_loader: - kv 22: qwen35.attention.value_length u32 = 256 +0.00.258.303 I llama_model_loader: - kv 23: qwen35.nextn_predict_layers u32 = 1 +0.00.258.304 I llama_model_loader: - kv 24: qwen35.ssm.conv_kernel u32 = 4 +0.00.258.305 I llama_model_loader: - kv 25: qwen35.ssm.state_size u32 = 128 +0.00.258.306 I llama_model_loader: - kv 26: qwen35.ssm.group_count u32 = 16 +0.00.258.307 I llama_model_loader: - kv 27: qwen35.ssm.time_step_rank u32 = 48 +0.00.258.307 I llama_model_loader: - kv 28: qwen35.ssm.inner_size u32 = 6144 +0.00.258.314 I llama_model_loader: - kv 29: qwen35.attention.recurrent_layers arr[bool,65] = [true, true, true, false, true, true,... +0.00.258.315 I llama_model_loader: - kv 30: qwen35.full_attention_interval u32 = 4 +0.00.258.316 I llama_model_loader: - kv 31: qwen35.rope.dimension_count u32 = 64 +0.00.258.317 I llama_model_loader: - kv 32: tokenizer.ggml.model str = gpt2 +0.00.258.318 I llama_model_loader: - kv 33: tokenizer.ggml.pre str = qwen35 +0.00.291.717 I llama_model_loader: - kv 34: tokenizer.ggml.tokens arr[str,248320] = ["!", "\"", "#", "$", "%", "&", "'", ... +0.00.297.406 I llama_model_loader: - kv 35: tokenizer.ggml.token_type arr[i32,248320] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... +0.00.330.703 I llama_model_loader: - kv 36: tokenizer.ggml.merges arr[str,247587] = ["Ġ Ġ", "ĠĠ ĠĠ", "i n", "Ġ t",... +0.00.330.706 I llama_model_loader: - kv 37: tokenizer.ggml.eos_token_id u32 = 248046 +0.00.330.707 I llama_model_loader: - kv 38: tokenizer.ggml.padding_token_id u32 = 248044 +0.00.330.708 I llama_model_loader: - kv 39: tokenizer.ggml.bos_token_id u32 = 248044 +0.00.330.710 I llama_model_loader: - kv 40: tokenizer.ggml.add_bos_token bool = false +0.00.330.716 I llama_model_loader: - kv 41: tokenizer.chat_template str = {%- set image_count = namespace(value... +0.00.330.717 I llama_model_loader: - kv 42: general.quantization_version u32 = 2 +0.00.330.718 I llama_model_loader: - kv 43: general.file_type u32 = 15 +0.00.330.719 I llama_model_loader: - kv 44: general.name str = ThinkingCap Qwen3.8 27B +0.00.330.720 I llama_model_loader: - kv 45: general.basename str = ThinkingCap-Qwen3.8 +0.00.330.723 I llama_model_loader: - kv 46: quantize.imatrix.file str = /mnt/storage/caveman/oplatek/Thinking... +0.00.330.725 I llama_model_loader: - kv 47: quantize.imatrix.dataset str = /mnt/storage/caveman/oplatek/gguf-cal... +0.00.330.726 I llama_model_loader: - kv 48: quantize.imatrix.entries_count u32 = 496 +0.00.330.727 I llama_model_loader: - kv 49: quantize.imatrix.chunks_count u32 = 583 +0.00.330.728 I llama_model_loader: - type f32: 456 tensors +0.00.330.728 I llama_model_loader: - type q4_0: 8 tensors +0.00.330.729 I llama_model_loader: - type q8_0: 64 tensors +0.00.330.730 I llama_model_loader: - type q4_K: 257 tensors +0.00.330.730 I llama_model_loader: - type q5_K: 2 tensors +0.00.330.731 I llama_model_loader: - type q6_K: 79 tensors +0.00.330.736 I print_info: file format = GGUF V3 (latest) +0.00.330.738 I print_info: file type = Q4_K - Medium +0.00.330.744 I print_info: file size = 16.23 GiB (5.10 BPW) +0.00.332.445 I llama_prepare_model_devices: using device Vulkan0 (Intel(R) Arc(TM) Pro B60 Graphics) (unknown id) - 23685 MiB free +0.00.560.896 I load: 0 unused tokens +0.00.636.217 I load: printing all EOG tokens: +0.00.636.218 I load: - 248044 ('<|endoftext|>') +0.00.636.219 I load: - 248046 ('<|im_end|>') +0.00.636.219 I load: - 248063 ('<|fim_pad|>') +0.00.636.220 I load: - 248064 ('<|repo_name|>') +0.00.636.220 I load: - 248065 ('<|file_sep|>') +0.00.636.722 I load: special tokens cache size = 33 +0.00.721.643 I load: token to piece cache size = 1.7581 MB +0.00.721.660 I print_info: arch = qwen35 +0.00.721.661 I print_info: vocab_only = 0 +0.00.721.661 I print_info: no_alloc = 0 +0.00.721.662 I print_info: n_ctx_train = 262144 +0.00.721.663 I print_info: n_embd_inp = 5120 +0.00.721.663 I print_info: n_embd = 5120 +0.00.721.663 I print_info: n_embd_out = 5120 +0.00.721.664 I print_info: n_layer = 64 +0.00.721.664 I print_info: n_layer_all = 65 +0.00.721.671 I print_info: n_head = 24 +0.00.721.673 I print_info: n_head_kv = 4 +0.00.721.673 I print_info: n_rot = 64 +0.00.721.674 I print_info: n_swa = 0 +0.00.721.674 I print_info: is_swa_any = 0 +0.00.721.675 I print_info: non_causal_type = 0 +0.00.721.675 I print_info: n_embd_head_k = 256 +0.00.721.676 I print_info: n_embd_head_v = 256 +0.00.721.677 I print_info: n_gqa = 6 +0.00.721.679 I print_info: n_embd_k_gqa = 1024 +0.00.721.681 I print_info: n_embd_v_gqa = 1024 +0.00.721.682 I print_info: f_norm_eps = 0.0e+00 +0.00.721.683 I print_info: f_norm_rms_eps = 1.0e-06 +0.00.721.684 I print_info: f_clamp_kqv = 0.0e+00 +0.00.721.685 I print_info: f_max_alibi_bias = 0.0e+00 +0.00.721.685 I print_info: f_logit_scale = 0.0e+00 +0.00.721.686 I print_info: f_attn_scale = 0.0e+00 +0.00.721.686 I print_info: f_attn_value_scale = 0.0000 +0.00.721.688 I print_info: n_ff = 17408 +0.00.721.688 I print_info: n_expert = 0 +0.00.721.689 I print_info: n_expert_used = 0 +0.00.721.689 I print_info: n_expert_groups = 0 +0.00.721.689 I print_info: n_group_used = 0 +0.00.721.690 I print_info: causal attn = 1 +0.00.721.690 I print_info: pooling type = -1 +0.00.721.691 I print_info: rope type = 40 +0.00.721.691 I print_info: rope scaling = linear +0.00.721.692 I print_info: freq_base_train = 10000000.0 +0.00.721.692 I print_info: freq_scale_train = 1 +0.00.721.693 I print_info: n_ctx_orig_yarn = 262144 +0.00.721.694 I print_info: rope_yarn_log_mul = 0.0000 +0.00.721.694 I print_info: rope_finetuned = unknown +0.00.721.695 I print_info: mrope sections = [11, 11, 10, 0] +0.00.721.695 I print_info: ssm_d_conv = 4 +0.00.721.696 I print_info: ssm_d_inner = 6144 +0.00.721.696 I print_info: ssm_d_state = 128 +0.00.721.696 I print_info: ssm_dt_rank = 48 +0.00.721.697 I print_info: ssm_n_group = 16 +0.00.721.697 I print_info: ssm_dt_b_c_rms = 0 +0.00.721.698 I print_info: model type = 27B +0.00.721.700 I print_info: model params = 27.32 B +0.00.721.701 I print_info: general.name = ThinkingCap Qwen3.8 27B +0.00.721.704 I print_info: vocab type = BPE +0.00.721.704 I print_info: n_vocab = 248320 +0.00.721.704 I print_info: n_merges = 247587 +0.00.721.705 I print_info: BOS token = 248044 '<|endoftext|>' +0.00.721.705 I print_info: EOS token = 248046 '<|im_end|>' +0.00.721.706 I print_info: EOT token = 248046 '<|im_end|>' +0.00.721.706 I print_info: PAD token = 248044 '<|endoftext|>' +0.00.721.707 I print_info: LF token = 198 'Ċ' +0.00.721.707 I print_info: FIM PRE token = 248060 '<|fim_prefix|>' +0.00.721.708 I print_info: FIM SUF token = 248062 '<|fim_suffix|>' +0.00.721.708 I print_info: FIM MID token = 248061 '<|fim_middle|>' +0.00.721.709 I print_info: FIM PAD token = 248063 '<|fim_pad|>' +0.00.721.709 I print_info: FIM REP token = 248064 '<|repo_name|>' +0.00.721.710 I print_info: FIM SEP token = 248065 '<|file_sep|>' +0.00.721.711 I print_info: EOG token = 248044 '<|endoftext|>' +0.00.721.711 I print_info: EOG token = 248046 '<|im_end|>' +0.00.721.712 I print_info: EOG token = 248063 '<|fim_pad|>' +0.00.721.712 I print_info: EOG token = 248064 '<|repo_name|>' +0.00.721.713 I print_info: EOG token = 248065 '<|file_sep|>' +0.00.721.713 I print_info: max token length = 256 +0.00.722.633 I load_tensors: loading model tensors, this can take a while... (load_mode = dio) +0.00.769.780 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring +0.00.769.791 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring +0.00.769.819 W model has unused tensor blk.64.attn_q.weight (size = 35389440 bytes) -- ignoring +0.00.769.828 W model has unused tensor blk.64.attn_k.weight (size = 2949120 bytes) -- ignoring +0.00.769.838 W model has unused tensor blk.64.attn_v.weight (size = 2949120 bytes) -- ignoring +0.00.769.874 W model has unused tensor blk.64.attn_output.weight (size = 17694720 bytes) -- ignoring +0.00.769.884 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring +0.00.769.894 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring +0.00.769.903 W model has unused tensor blk.64.ffn_gate.weight (size = 50135040 bytes) -- ignoring +0.00.769.913 W model has unused tensor blk.64.ffn_down.weight (size = 50135040 bytes) -- ignoring +0.00.769.922 W model has unused tensor blk.64.ffn_up.weight (size = 50135040 bytes) -- ignoring +0.00.769.933 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 29491200 bytes) -- ignoring +0.00.769.944 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring +0.00.769.954 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring +0.00.769.984 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring +0.02.804.775 I load_tensors: offloading output layer to GPU +0.02.804.780 I load_tensors: offloading 64 repeating layers to GPU +0.02.804.781 I load_tensors: offloaded 66/66 layers to GPU +0.02.804.786 I load_tensors: Vulkan0 model buffer size = 15713.94 MiB +0.02.804.788 I load_tensors: Vulkan_Host model buffer size = 682.03 MiB +0.12.056.886 I cmn common_init_: added <|endoftext|> logit bias = -inf +0.12.056.892 I cmn common_init_: added <|im_end|> logit bias = -inf +0.12.056.893 I cmn common_init_: added <|fim_pad|> logit bias = -inf +0.12.056.894 I cmn common_init_: added <|repo_name|> logit bias = -inf +0.12.056.894 I cmn common_init_: added <|file_sep|> logit bias = -inf +0.12.058.565 I llama_context: constructing llama_context +0.12.058.574 I llama_context: n_seq_max = 1 +0.12.058.575 I llama_context: n_ctx = 40960 +0.12.058.576 I llama_context: n_ctx_seq = 40960 +0.12.058.576 I llama_context: n_batch = 2048 +0.12.058.577 I llama_context: n_ubatch = 256 +0.12.058.577 I llama_context: causal_attn = 1 +0.12.058.578 I llama_context: flash_attn = enabled +0.12.058.579 I llama_context: kv_unified = false +0.12.058.581 I llama_context: freq_base = 10000000.0 +0.12.058.582 I llama_context: freq_scale = 1 +0.12.058.583 I llama_context: n_rs_seq = 7 +0.12.058.583 I llama_context: n_outputs_max = 8 +0.12.058.584 I llama_context: n_outputs_max_per_seq = 8 +0.12.058.585 I llama_context: n_ctx_seq (40960) < n_ctx_train (262144) -- the full capacity of the model will not be utilized +0.12.059.333 I llama_context: Vulkan_Host output buffer size = 0.95 MiB +0.12.413.840 I llama_kv_cache: Vulkan0 KV buffer size = 2560.00 MiB +0.12.432.449 I llama_kv_cache: size = 2560.00 MiB ( 40960 cells, 16 layers, 1/1 seqs), K (f16): 1280.00 MiB, V (f16): 1280.00 MiB +0.12.432.460 I llama_kv_cache: n_rot_k = 0, n_embd_head_k_all = 256 +0.12.432.460 I llama_kv_cache: n_rot_v = 0, n_embd_head_k_all = 256 +0.12.599.032 I llama_memory_recurrent: Vulkan0 RS buffer size = 1197.00 MiB +0.12.599.046 I llama_memory_recurrent: size = 1197.00 MiB ( 1 cells, 64 layers, 1 seqs 7 rs_seq), R (f32): 45.00 MiB, S (f32): 1152.00 MiB, P (f32): 0.00 MiB +0.12.599.059 I sched_reserve: reserving ... +0.12.603.390 I resolve_fused_ops: resolving fused DeepSeek V4 HC support: +0.12.613.928 I resolve_fused_ops: fused DeepSeek V4 HC pre enabled +0.12.622.278 I resolve_fused_ops: fused DeepSeek V4 HC comb enabled +0.12.630.409 I resolve_fused_ops: fused DeepSeek V4 HC post enabled +0.12.674.949 I sched_reserve: Vulkan0 compute buffer size = 92.13 MiB +0.12.674.955 I sched_reserve: Vulkan_Host compute buffer size = 40.01 MiB +0.12.674.958 I sched_reserve: graph: nodes = 4857, splits = 2, input objects = 4, input tensors = 10 +0.12.674.960 I sched_reserve: reserve took 75.74 ms, sched copies = 1 +0.12.675.245 I cmn init: llama threadpool init, n_threads = 8 +0.12.675.761 I cmn common_init_: warming up the model with an empty run - please wait ... (--no-warmup to disable) +0.12.793.332 I common_speculative_init_result: loading draft model 'C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf' +0.12.878.362 I llama_model_loader: loaded meta data with 48 key-value pairs and 81 tensors from C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf (version GGUF V3 (latest)) +0.12.878.372 I llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output. +0.12.878.375 I llama_model_loader: - kv 0: general.architecture str = dflash +0.12.878.377 I llama_model_loader: - kv 1: general.type str = model +0.12.878.378 I llama_model_loader: - kv 2: general.name str = Qwen3.8-27B-DFlash2 +0.12.878.379 I llama_model_loader: - kv 3: general.author str = Inco AI +0.12.878.380 I llama_model_loader: - kv 4: general.organization str = z-lab +0.12.878.381 I llama_model_loader: - kv 5: general.finetune str = DFlash2 +0.12.878.382 I llama_model_loader: - kv 6: general.basename str = Qwen3.8-27B +0.12.878.383 I llama_model_loader: - kv 7: general.size_label str = 1.9B +0.12.878.384 I llama_model_loader: - kv 8: general.license str = apache-2.0 +0.12.878.388 I llama_model_loader: - kv 9: general.source.url str = https://huggingface.co/z-lab/Qwen3.8-... +0.12.878.390 I llama_model_loader: - kv 10: general.base_model.count u32 = 1 +0.12.878.391 I llama_model_loader: - kv 11: general.base_model.0.name str = Qwen3.8 27B +0.12.878.392 I llama_model_loader: - kv 12: general.base_model.0.organization str = Qwen +0.12.878.394 I llama_model_loader: - kv 13: general.base_model.0.repo_url str = https://huggingface.co/Qwen/Qwen3.8-27B +0.12.878.404 I llama_model_loader: - kv 14: general.tags arr[str,6] = ["dflash2", "speculative-decoding", "... +0.12.878.405 I llama_model_loader: - kv 15: dflash.block_count u32 = 5 +0.12.878.405 I llama_model_loader: - kv 16: dflash.context_length u32 = 262144 +0.12.878.406 I llama_model_loader: - kv 17: dflash.embedding_length u32 = 5120 +0.12.878.407 I llama_model_loader: - kv 18: dflash.feed_forward_length u32 = 17408 +0.12.878.408 I llama_model_loader: - kv 19: dflash.attention.head_count u32 = 32 +0.12.878.409 I llama_model_loader: - kv 20: dflash.attention.head_count_kv u32 = 8 +0.12.878.410 I llama_model_loader: - kv 21: dflash.attention.causal bool = false +0.12.878.415 I llama_model_loader: - kv 22: dflash.rope.freq_base f32 = 10000000.000000 +0.12.878.417 I llama_model_loader: - kv 23: dflash.attention.layer_norm_rms_epsilon f32 = 0.000001 +0.12.878.418 I llama_model_loader: - kv 24: dflash.attention.key_length u32 = 128 +0.12.878.419 I llama_model_loader: - kv 25: dflash.attention.value_length u32 = 128 +0.12.878.419 I llama_model_loader: - kv 26: dflash.block_size u32 = 8 +0.12.878.420 I llama_model_loader: - kv 27: dflash.conv_kernel_size u32 = 2 +0.12.878.421 I llama_model_loader: - kv 28: dflash.conv_group_size u32 = 16 +0.12.878.422 I llama_model_loader: - kv 29: dflash.selector_rank u32 = 256 +0.12.878.423 I llama_model_loader: - kv 30: dflash.selector_top_k u32 = 16 +0.12.878.426 I llama_model_loader: - kv 31: dflash.target_layers arr[i32,5] = [6, 20, 34, 48, 62] +0.12.878.427 I llama_model_loader: - kv 32: dflash.attention.sliding_window u32 = 2048 +0.12.878.429 I llama_model_loader: - kv 33: dflash.attention.sliding_window_pattern arr[bool,5] = [true, true, true, true, true] +0.12.878.430 I llama_model_loader: - kv 34: tokenizer.ggml.model str = gpt2 +0.12.878.431 I llama_model_loader: - kv 35: tokenizer.ggml.pre str = qwen35 +0.12.914.382 I llama_model_loader: - kv 36: tokenizer.ggml.tokens arr[str,248320] = ["!", "\"", "#", "$", "%", "&", "'", ... +0.12.920.121 I llama_model_loader: - kv 37: tokenizer.ggml.token_type arr[i32,248320] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... +0.12.955.095 I llama_model_loader: - kv 38: tokenizer.ggml.merges arr[str,247587] = ["Ġ Ġ", "ĠĠ ĠĠ", "i n", "Ġ t",... +0.12.955.098 I llama_model_loader: - kv 39: tokenizer.ggml.eos_token_id u32 = 248046 +0.12.955.099 I llama_model_loader: - kv 40: tokenizer.ggml.padding_token_id u32 = 248044 +0.12.955.100 I llama_model_loader: - kv 41: tokenizer.ggml.bos_token_id u32 = 248044 +0.12.955.102 I llama_model_loader: - kv 42: tokenizer.ggml.add_bos_token bool = false +0.12.955.110 I llama_model_loader: - kv 43: tokenizer.chat_template str = {%- set image_count = namespace(value... +0.12.955.112 I llama_model_loader: - kv 44: tokenizer.ggml.mask_token_id u32 = 248070 +0.12.955.113 I llama_model_loader: - kv 45: general.quantization_version u32 = 2 +0.12.955.114 I llama_model_loader: - kv 46: general.file_type u32 = 15 +0.12.955.117 I llama_model_loader: - kv 47: dflash.rope.dimension_sections arr[i32,4] = [64, 0, 0, 0] +0.12.955.118 I llama_model_loader: - type f32: 32 tensors +0.12.955.119 I llama_model_loader: - type q4_K: 45 tensors +0.12.955.119 I llama_model_loader: - type q6_K: 4 tensors +0.12.955.121 I print_info: file format = GGUF V3 (latest) +0.12.955.122 I print_info: file type = Q4_K - Medium +0.12.955.125 I print_info: file size = 1.05 GiB (4.71 BPW) +0.12.956.804 I llama_prepare_model_devices: using device Vulkan0 (Intel(R) Arc(TM) Pro B60 Graphics) (unknown id) - 3475 MiB free +0.12.957.062 I load_arch_hparams: DFlash extract_layers = [6, 20, 34, 48, 62] +0.13.184.217 I load: 0 unused tokens +0.13.258.259 I load: printing all EOG tokens: +0.13.258.260 I load: - 248044 ('<|endoftext|>') +0.13.258.261 I load: - 248046 ('<|im_end|>') +0.13.258.261 I load: - 248063 ('<|fim_pad|>') +0.13.258.262 I load: - 248064 ('<|repo_name|>') +0.13.258.262 I load: - 248065 ('<|file_sep|>') +0.13.258.833 I load: special tokens cache size = 33 +0.13.353.389 I load: token to piece cache size = 1.7581 MB +0.13.353.401 I print_info: arch = dflash +0.13.353.402 I print_info: vocab_only = 0 +0.13.353.403 I print_info: no_alloc = 0 +0.13.353.403 I print_info: n_ctx_train = 262144 +0.13.353.404 I print_info: n_embd_inp = 5120 +0.13.353.405 I print_info: n_embd = 5120 +0.13.353.405 I print_info: n_embd_out = 5120 +0.13.353.406 I print_info: n_layer = 5 +0.13.353.406 I print_info: n_layer_all = 5 +0.13.353.412 I print_info: n_head = 32 +0.13.353.413 I print_info: n_head_kv = 8 +0.13.353.414 I print_info: n_rot = 128 +0.13.353.414 I print_info: n_swa = 2048 +0.13.353.415 I print_info: is_swa_any = 1 +0.13.353.415 I print_info: non_causal_type = 0 +0.13.353.416 I print_info: n_embd_head_k = 128 +0.13.353.416 I print_info: n_embd_head_v = 128 +0.13.353.417 I print_info: n_gqa = 4 +0.13.353.419 I print_info: n_embd_k_gqa = 1024 +0.13.353.420 I print_info: n_embd_v_gqa = 1024 +0.13.353.421 I print_info: f_norm_eps = 0.0e+00 +0.13.353.423 I print_info: f_norm_rms_eps = 1.0e-06 +0.13.353.424 I print_info: f_clamp_kqv = 0.0e+00 +0.13.353.425 I print_info: f_max_alibi_bias = 0.0e+00 +0.13.353.425 I print_info: f_logit_scale = 0.0e+00 +0.13.353.426 I print_info: f_attn_scale = 0.0e+00 +0.13.353.427 I print_info: f_attn_value_scale = 0.0000 +0.13.353.429 I print_info: n_ff = 17408 +0.13.353.429 I print_info: n_expert = 0 +0.13.353.430 I print_info: n_expert_used = 0 +0.13.353.430 I print_info: n_expert_groups = 0 +0.13.353.431 I print_info: n_group_used = 0 +0.13.353.431 I print_info: causal attn = 0 +0.13.353.432 I print_info: pooling type = -1 +0.13.353.432 I print_info: rope type = 8 +0.13.353.433 I print_info: rope scaling = linear +0.13.353.434 I print_info: freq_base_train = 10000000.0 +0.13.353.435 I print_info: freq_scale_train = 1 +0.13.353.436 I print_info: freq_base_swa = 10000000.0 +0.13.353.436 I print_info: freq_scale_swa = 1 +0.13.353.437 I print_info: n_embd_head_k_swa = 128 +0.13.353.437 I print_info: n_embd_head_v_swa = 128 +0.13.353.438 I print_info: n_rot_swa = 128 +0.13.353.438 I print_info: n_ctx_orig_yarn = 262144 +0.13.353.439 I print_info: rope_yarn_log_mul = 0.0000 +0.13.353.439 I print_info: rope_finetuned = unknown +0.13.353.440 I print_info: mrope sections = [64, 0, 0, 0] +0.13.353.441 I print_info: model type = ?B +0.13.353.442 I print_info: model params = 1.92 B +0.13.353.443 I print_info: general.name = Qwen3.8-27B-DFlash2 +0.13.353.444 I print_info: vocab type = BPE +0.13.353.445 I print_info: n_vocab = 248320 +0.13.353.446 I print_info: n_merges = 247587 +0.13.353.446 I print_info: BOS token = 248044 '<|endoftext|>' +0.13.353.447 I print_info: EOS token = 248046 '<|im_end|>' +0.13.353.447 I print_info: EOT token = 248046 '<|im_end|>' +0.13.353.448 I print_info: PAD token = 248044 '<|endoftext|>' +0.13.353.449 I print_info: MASK token = 248070 '<|audio_start|>' +0.13.353.449 I print_info: LF token = 198 'Ċ' +0.13.353.450 I print_info: FIM PRE token = 248060 '<|fim_prefix|>' +0.13.353.451 I print_info: FIM SUF token = 248062 '<|fim_suffix|>' +0.13.353.451 I print_info: FIM MID token = 248061 '<|fim_middle|>' +0.13.353.452 I print_info: FIM PAD token = 248063 '<|fim_pad|>' +0.13.353.452 I print_info: FIM REP token = 248064 '<|repo_name|>' +0.13.353.453 I print_info: FIM SEP token = 248065 '<|file_sep|>' +0.13.353.454 I print_info: EOG token = 248044 '<|endoftext|>' +0.13.353.454 I print_info: EOG token = 248046 '<|im_end|>' +0.13.353.455 I print_info: EOG token = 248063 '<|fim_pad|>' +0.13.353.455 I print_info: EOG token = 248064 '<|repo_name|>' +0.13.353.456 I print_info: EOG token = 248065 '<|file_sep|>' +0.13.353.456 I print_info: max token length = 256 +0.13.354.739 I load_tensors: loading model tensors, this can take a while... (load_mode = dio) +0.13.356.204 I load_arch_tensors: DFlash2 conv kernel = 2, group = 16, selector rank = 256, top-k = 16 +0.14.124.480 I load_tensors: offloading output layer to GPU +0.14.124.481 I load_tensors: offloading 4 repeating layers to GPU +0.14.124.481 I load_tensors: offloaded 6/6 layers to GPU +0.14.124.485 I load_tensors: Vulkan0 model buffer size = 1079.61 MiB +0.14.687.996 I llama_context: constructing llama_context +0.14.688.004 I llama_context: n_seq_max = 1 +0.14.688.005 I llama_context: n_ctx = 40960 +0.14.688.007 I llama_context: n_ctx_seq = 40960 +0.14.688.008 I llama_context: n_batch = 2048 +0.14.688.008 I llama_context: n_ubatch = 256 +0.14.688.008 I llama_context: causal_attn = 0 +0.14.688.009 I llama_context: flash_attn = enabled +0.14.688.010 I llama_context: kv_unified = false +0.14.688.013 I llama_context: freq_base = 10000000.0 +0.14.688.014 I llama_context: freq_scale = 1 +0.14.688.014 I llama_context: n_rs_seq = 0 +0.14.688.015 I llama_context: n_outputs_max = 2048 +0.14.688.015 I llama_context: n_outputs_max_per_seq = 8 +0.14.688.016 I llama_context: n_ctx_seq (40960) < n_ctx_train (262144) -- the full capacity of the model will not be utilized +0.14.688.608 I llama_context: Vulkan_Host output buffer size = 0.95 MiB +0.14.688.618 I llama_kv_cache_iswa: creating non-SWA KV cache, size = 40960 cells +0.14.689.020 I llama_kv_cache: size = 0.00 MiB ( 40960 cells, 0 layers, 1/1 seqs), K (q8_0): 0.00 MiB, V (q8_0): 0.00 MiB +0.14.689.023 I llama_kv_cache: n_rot_k = 0, n_embd_head_k_all = 0 +0.14.689.024 I llama_kv_cache: n_rot_v = 0, n_embd_head_k_all = 0 +0.14.689.027 I llama_kv_cache_iswa: creating SWA KV cache, size = 2304 cells +0.14.692.352 I llama_kv_cache: Vulkan0 KV buffer size = 23.91 MiB +0.14.692.601 I llama_kv_cache: size = 23.91 MiB ( 2304 cells, 5 layers, 1/1 seqs), K (q8_0): 11.95 MiB, V (q8_0): 11.95 MiB +0.14.692.605 I llama_kv_cache: n_rot_k = 128, n_embd_head_k_all = 128 +0.14.692.605 I llama_kv_cache: n_rot_v = 64, n_embd_head_k_all = 128 +0.14.692.621 I sched_reserve: reserving ... +0.14.692.746 I resolve_fused_ops: resolving fused DeepSeek V4 HC support: +0.14.693.738 I resolve_fused_ops: fused DeepSeek V4 HC pre enabled +0.14.694.492 I resolve_fused_ops: fused DeepSeek V4 HC comb enabled +0.14.695.372 I resolve_fused_ops: fused DeepSeek V4 HC post enabled +0.14.734.944 I sched_reserve: Vulkan0 compute buffer size = 277.73 MiB +0.14.734.945 I sched_reserve: Vulkan_Host compute buffer size = 6.21 MiB +0.14.734.948 I sched_reserve: graph (pp bs=256, tg bs=1): nodes = 751 / 531, splits = 2 / 2, input objects = 3 / 3, input tensors = 7 / 7 +0.14.734.950 I sched_reserve: reserve took 42.33 ms, sched copies = 1 +0.14.735.032 I cmn common_conte: the context supports bounded partial sequence removal +0.14.735.033 I srv load_model: initializing, n_slots = 1, n_ctx_slot = 40960, kv_unified = 'false' +0.14.735.338 I common_speculative_impl_draft_dflash: adding speculative implementation 'draft-dflash' +0.14.735.340 I common_speculative_impl_draft_dflash: - n_max=7, n_min=0, p_min=0.50 +0.14.735.341 I common_speculative_impl_draft_dflash: - block_size=8, mask_token_id=248070, n_extract=5, sample_from_anchor=true +0.14.735.785 I sched_reserve: reserving ... +0.14.780.095 I sched_reserve: Vulkan0 compute buffer size = 277.73 MiB +0.14.780.097 I sched_reserve: Vulkan_Host compute buffer size = 6.21 MiB +0.14.780.099 I sched_reserve: graph (pp bs=256, tg bs=1): nodes = 751 / 531, splits = 2 / 2, input objects = 3 / 3, input tensors = 7 / 7 +0.14.780.101 I sched_reserve: reserve took 44.31 ms, sched copies = 1 +0.14.885.347 I srv load_model: speculative decoding context initialized +0.14.885.348 I slot load_model: id 0 | task -1 | new slot, n_ctx = 40960 +0.14.885.502 I srv load_model: prompt cache is enabled, size limit: 2048 MiB +0.14.885.502 I srv load_model: use `--cache-ram 0` to disable the prompt cache +0.14.885.503 I srv load_model: for more info see https://github.com/ggml-org/llama.cpp/pull/16391 +0.14.885.504 I srv load_model: context checkpoints enabled, max = 32, min spacing = 8192 +0.14.885.659 I srv init: idle slots will be saved to prompt cache upon starting a new task +0.14.893.773 I srv init: init: chat template, example_format: '<|im_start|>system +Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer. + +You are a helpful assistant<|im_end|> +<|im_start|>user +Hello<|im_end|> +<|im_start|>assistant + + + + +Hi there<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant + +' +0.14.895.333 I srv init: init: chat template, thinking = 1 +0.14.895.459 I srv init: preserve_reasoning kwarg: true +0.14.895.460 W srv init: chat template supports preserving reasoning, it is enabled by default (may use more tokens, disable via --no-reasoning-preserve) +0.14.895.896 I srv llama_server: model loaded +0.14.895.898 I srv llama_server: listening on http://127.0.0.1:10012 +0.14.896.374 I srv update_slots: all slots are idle +0.21.730.864 I srv server_strea: conv_id= (empty=1) +0.21.740.204 I srv operator(): chat format: peg-native +0.21.742.005 I slot get_availabl: id 0 | task -1 | - skipping, slot is empty +0.21.742.006 I slot get_availabl: id 0 | task -1 | selected slot by LRU, t_last = -1 +0.21.742.006 I srv get_availabl: updating prompt cache +0.21.742.145 I srv load: - looking for better prompt, base f_keep = -1.000, f_sim = 0.000 +0.21.742.147 I srv update: - cache state: 0 prompts, 0.000 MiB (limits: 2048.000 MiB, 40960 tokens, 2147483648 est) +0.21.742.148 I srv get_availabl: prompt cache update took 0.14 ms +0.21.742.742 I cmn common_reaso: activated, budget=4096 tokens +0.21.742.744 I cmn common_reaso: deactivated (natural end) +0.21.743.084 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.21.743.096 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.21.743.098 I slot launch_slot_: id 0 | task 0 | processing task, is_child = 0 +0.21.743.242 I slot operator(): id 0 | task 0 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 3875 +0.21.743.363 I slot operator(): id 0 | task 0 | cached n_tokens = 0, memory_seq_rm [0, end) +0.21.744.203 I sched_reserve: reserving ... +0.21.791.234 I sched_reserve: Vulkan0 compute buffer size = 116.01 MiB +0.21.791.236 I sched_reserve: Vulkan_Host compute buffer size = 40.01 MiB +0.21.791.238 I sched_reserve: graph: nodes = 4857, splits = 2, input objects = 4, input tensors = 10 +0.21.791.240 I sched_reserve: reserve took 47.03 ms, sched copies = 1 +0.25.738.978 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 2048, progress = 0.53, t = 3.28 s / 623.95 tokens per second +0.25.738.988 I slot operator(): id 0 | task 0 | cached n_tokens = 2048, memory_seq_rm [2048, end) +0.28.957.278 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 3615, progress = 0.93, t = 6.73 s / 537.47 tokens per second +0.28.957.286 I slot operator(): id 0 | task 0 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.29.070.782 I slot create_check: id 0 | task 0 | created context checkpoint 1 of 32 (pos_min = 3614, pos_max = 3614, n_tokens = 3615, size = 170.923 MiB) +0.29.658.782 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 3871, progress = 1.00, t = 7.41 s / 522.17 tokens per second +0.29.658.788 I slot operator(): id 0 | task 0 | cached n_tokens = 3871, memory_seq_rm [3871, end) +0.29.659.972 I slot init_sampler: id 0 | task 0 | init sampler, took 1.07 ms, tokens: text = 3875, total = 3875 +0.29.809.086 I slot create_check: id 0 | task 0 | created context checkpoint 2 of 32 (pos_min = 3870, pos_max = 3870, n_tokens = 3871, size = 170.923 MiB) +0.33.592.271 I slot print_timing: id 0 | task 0 | n_gen = 100, tg = 27.06 t/s, tg_3s = 27.33 t/s +0.36.755.548 I slot print_timing: id 0 | task 0 | n_gen = 207, tg = 30.20 t/s, tg_3s = 33.83 t/s +0.38.177.461 I slot print_timing: id 0 | task 0 | prompt eval time = 8190.41 ms / 3875 tokens ( 2.11 ms per token, 473.11 tokens per second) +0.38.177.471 I slot print_timing: id 0 | task 0 | eval time = 8243.65 ms / 256 tokens ( 32.33 ms per token, 30.93 tokens per second) +0.38.177.472 I slot print_timing: id 0 | task 0 | total time = 16434.06 ms / 4131 tokens +0.38.177.474 I slot print_timing: id 0 | task 0 | graphs reused = 29 +0.38.177.487 I slot print_timing: id 0 | task 0 | draft acceptance = 0.83333 ( 215 accepted / 258 generated), mean len = 6.51 +0.38.177.487 I slot print_timing: id 0 | task 0 | acc per pos = (0.974, 0.923, 0.846, 0.821, 0.718, 0.667, 0.564) +0.38.177.945 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 1 40 39, #gen drafts = 39, #acc drafts = 38, #gen tokens = 258, #acc tokens = 215, #mean acc len = 6.51, #acc rate/pos = (0.974, 0.923, 0.846, 0.821, 0.718, 0.667, 0.564), dur(b,g,a) = 0.234, 3775.735, 0.023 ms +0.38.178.280 I slot release: id 0 | task 0 | stop processing: n_tokens = 4130, truncated = 0 +0.38.178.507 I srv update_slots: all slots are idle +0.40.332.871 I srv server_strea: conv_id= (empty=1) +0.40.339.575 I srv operator(): chat format: peg-native +0.40.339.865 I slot get_availabl: id 0 | task -1 | - checking sim = 0.997 (3864/3875) > 0.100 +0.40.339.867 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 0.997 (> 0.100 thold), f_keep = 0.936 +0.40.339.925 I cmn common_reaso: activated, budget=4096 tokens +0.40.339.926 I cmn common_reaso: deactivated (natural end) +0.40.340.256 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.40.340.267 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.40.340.269 I slot launch_slot_: id 0 | task 45 | processing task, is_child = 0 +0.40.340.276 I slot operator(): id 0 | task 45 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 3875 +0.40.340.281 I slot operator(): id 0 | task 45 | checking checkpoint with [3870, 3870] against 3864... +0.40.340.282 I slot operator(): id 0 | task 45 | checking checkpoint with [3614, 3614] against 3864... +0.40.358.293 I slot operator(): id 0 | task 45 | restored context checkpoint (pos_min = 3614, pos_max = 3614, n_tokens = 3615, n_past = 3615, size = 170.923 MiB) +0.40.358.296 I slot operator(): id 0 | task 45 | erased invalidated context checkpoint (pos_min = 3870, pos_max = 3870, n_tokens = 3871, n_swa = 0, pos_next = 3615, size = 170.923 MiB) +0.40.372.063 I slot operator(): id 0 | task 45 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.40.372.250 I slot create_check: id 0 | task 45 | superseding context checkpoint at n_tokens = 3615 +0.40.458.307 I slot create_check: id 0 | task 45 | created context checkpoint 1 of 32 (pos_min = 3614, pos_max = 3614, n_tokens = 3615, size = 170.923 MiB) +0.40.966.997 I slot operator(): id 0 | task 45 | cached n_tokens = 3871, memory_seq_rm [3871, end) +0.40.967.545 I slot init_sampler: id 0 | task 45 | init sampler, took 0.48 ms, tokens: text = 3875, total = 3875 +0.41.036.704 I slot create_check: id 0 | task 45 | created context checkpoint 2 of 32 (pos_min = 3870, pos_max = 3870, n_tokens = 3871, size = 170.923 MiB) +0.44.800.778 I slot print_timing: id 0 | task 45 | n_gen = 101, tg = 27.22 t/s, tg_3s = 27.49 t/s +0.47.825.422 I slot print_timing: id 0 | task 45 | n_gen = 174, tg = 25.83 t/s, tg_3s = 24.14 t/s +0.50.493.180 I slot print_timing: id 0 | task 45 | prompt eval time = 786.41 ms / 260 tokens ( 3.02 ms per token, 330.62 tokens per second) +0.50.493.185 I slot print_timing: id 0 | task 45 | eval time = 9366.41 ms / 256 tokens ( 36.73 ms per token, 27.22 tokens per second) +0.50.493.186 I slot print_timing: id 0 | task 45 | total time = 10152.81 ms / 516 tokens +0.50.493.187 I slot print_timing: id 0 | task 45 | graphs reused = 64 +0.50.493.195 I slot print_timing: id 0 | task 45 | draft acceptance = 0.72165 ( 210 accepted / 291 generated), mean len = 5.77 +0.50.493.196 I slot print_timing: id 0 | task 45 | acc per pos = (0.909, 0.818, 0.727, 0.705, 0.591, 0.523, 0.500) +0.50.493.215 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 2 85 83, #gen drafts = 83, #acc drafts = 78, #gen tokens = 549, #acc tokens = 425, #mean acc len = 6.12, #acc rate/pos = (0.940, 0.867, 0.783, 0.759, 0.651, 0.590, 0.530), dur(b,g,a) = 0.235, 8113.421, 0.042 ms +0.50.493.290 I slot release: id 0 | task 45 | stop processing: n_tokens = 4130, truncated = 0 +0.50.493.309 I srv update_slots: all slots are idle +0.52.575.268 I srv server_strea: conv_id= (empty=1) +0.52.611.079 I srv operator(): chat format: peg-native +0.52.611.896 I slot get_availabl: id 0 | task -1 | - checking sim = 0.132 (3821/28858) > 0.100 +0.52.611.898 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 0.132 (> 0.100 thold), f_keep = 0.925 +0.52.611.963 I cmn common_reaso: activated, budget=4096 tokens +0.52.611.964 I cmn common_reaso: deactivated (natural end) +0.52.612.133 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.52.612.146 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.52.612.149 I slot launch_slot_: id 0 | task 93 | processing task, is_child = 0 +0.52.612.157 I slot operator(): id 0 | task 93 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 28858 +0.52.612.164 I slot operator(): id 0 | task 93 | checking checkpoint with [3870, 3870] against 3821... +0.52.612.164 I slot operator(): id 0 | task 93 | checking checkpoint with [3614, 3614] against 3821... +0.52.629.760 I slot operator(): id 0 | task 93 | restored context checkpoint (pos_min = 3614, pos_max = 3614, n_tokens = 3615, n_past = 3615, size = 170.923 MiB) +0.52.629.761 I slot operator(): id 0 | task 93 | erased invalidated context checkpoint (pos_min = 3870, pos_max = 3870, n_tokens = 3871, n_swa = 0, pos_next = 3615, size = 170.923 MiB) +0.52.636.276 I slot operator(): id 0 | task 93 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.56.703.832 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 2048, progress = 0.20, t = 3.38 s / 606.55 tokens per second +0.56.703.837 I slot operator(): id 0 | task 93 | cached n_tokens = 5663, memory_seq_rm [5663, end) +1.00.892.189 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 4096, progress = 0.27, t = 7.55 s / 542.84 tokens per second +1.00.892.198 I slot operator(): id 0 | task 93 | cached n_tokens = 7711, memory_seq_rm [7711, end) +1.05.155.669 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 6144, progress = 0.34, t = 11.78 s / 521.64 tokens per second +1.05.155.673 I slot operator(): id 0 | task 93 | cached n_tokens = 9759, memory_seq_rm [9759, end) +1.09.508.596 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 8192, progress = 0.41, t = 16.15 s / 507.37 tokens per second +1.09.508.601 I slot operator(): id 0 | task 93 | cached n_tokens = 11807, memory_seq_rm [11807, end) +1.14.039.289 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 10240, progress = 0.48, t = 20.68 s / 495.15 tokens per second +1.14.039.294 I slot operator(): id 0 | task 93 | cached n_tokens = 13855, memory_seq_rm [13855, end) +1.18.689.299 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 12288, progress = 0.55, t = 25.32 s / 485.31 tokens per second +1.18.689.306 I slot operator(): id 0 | task 93 | cached n_tokens = 15903, memory_seq_rm [15903, end) +1.23.454.804 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 14336, progress = 0.62, t = 30.07 s / 476.74 tokens per second +1.23.454.809 I slot operator(): id 0 | task 93 | cached n_tokens = 17951, memory_seq_rm [17951, end) +1.28.476.652 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 16384, progress = 0.69, t = 34.95 s / 468.76 tokens per second +1.28.476.659 I slot operator(): id 0 | task 93 | cached n_tokens = 19999, memory_seq_rm [19999, end) +1.33.498.786 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 18432, progress = 0.76, t = 40.08 s / 459.89 tokens per second +1.33.498.794 I slot operator(): id 0 | task 93 | cached n_tokens = 22047, memory_seq_rm [22047, end) +1.38.651.967 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 20480, progress = 0.83, t = 45.22 s / 452.90 tokens per second +1.38.651.971 I slot operator(): id 0 | task 93 | cached n_tokens = 24095, memory_seq_rm [24095, end) +1.43.977.914 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 22528, progress = 0.91, t = 50.51 s / 446.05 tokens per second +1.43.977.918 I slot operator(): id 0 | task 93 | cached n_tokens = 26143, memory_seq_rm [26143, end) +1.49.373.887 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 24576, progress = 0.98, t = 55.91 s / 439.58 tokens per second +1.49.373.894 I slot operator(): id 0 | task 93 | cached n_tokens = 28191, memory_seq_rm [28191, end) +1.50.667.371 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 24983, progress = 0.99, t = 57.44 s / 434.96 tokens per second +1.50.667.375 I slot operator(): id 0 | task 93 | cached n_tokens = 28598, memory_seq_rm [28598, end) +1.50.728.830 I slot create_check: id 0 | task 93 | created context checkpoint 2 of 32 (pos_min = 28597, pos_max = 28597, n_tokens = 28598, size = 170.923 MiB) +1.51.404.629 I slot print_timing: id 0 | task 93 | prompt processing, n_tokens = 25239, progress = 1.00, t = 58.13 s / 434.15 tokens per second +1.51.404.633 I slot operator(): id 0 | task 93 | cached n_tokens = 28854, memory_seq_rm [28854, end) +1.51.408.210 I slot init_sampler: id 0 | task 93 | init sampler, took 3.52 ms, tokens: text = 28858, total = 28858 +1.51.470.996 I slot create_check: id 0 | task 93 | created context checkpoint 3 of 32 (pos_min = 28853, pos_max = 28853, n_tokens = 28854, size = 170.923 MiB) +1.55.533.268 I slot print_timing: id 0 | task 93 | n_gen = 100, tg = 24.98 t/s, tg_3s = 25.23 t/s +1.58.726.807 I slot print_timing: id 0 | task 93 | n_gen = 179, tg = 24.87 t/s, tg_3s = 24.74 t/s +2.01.578.975 I slot print_timing: id 0 | task 93 | prompt eval time = 58958.00 ms / 25243 tokens ( 2.34 ms per token, 428.15 tokens per second) +2.01.578.984 I slot print_timing: id 0 | task 93 | eval time = 10008.51 ms / 256 tokens ( 39.25 ms per token, 25.48 tokens per second) +2.01.578.985 I slot print_timing: id 0 | task 93 | total time = 68966.51 ms / 25499 tokens +2.01.578.986 I slot print_timing: id 0 | task 93 | graphs reused = 91 +2.01.578.997 I slot print_timing: id 0 | task 93 | draft acceptance = 0.73077 ( 209 accepted / 286 generated), mean len = 5.64 +2.01.578.998 I slot print_timing: id 0 | task 93 | acc per pos = (0.956, 0.911, 0.778, 0.622, 0.533, 0.467, 0.378) +2.01.579.027 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 3 131 128, #gen drafts = 128, #acc drafts = 121, #gen tokens = 835, #acc tokens = 634, #mean acc len = 5.95, #acc rate/pos = (0.945, 0.883, 0.781, 0.711, 0.609, 0.547, 0.477), dur(b,g,a) = 0.236, 12538.951, 0.059 ms +2.01.579.518 I slot release: id 0 | task 93 | stop processing: n_tokens = 29113, truncated = 0 +2.01.579.537 I srv update_slots: all slots are idle +2.03.694.010 I srv server_strea: conv_id= (empty=1) +2.03.734.822 I srv operator(): chat format: peg-native +2.03.735.707 I slot get_availabl: id 0 | task -1 | - checking sim = 1.000 (28847/28858) > 0.100 +2.03.735.709 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 1.000 (> 0.100 thold), f_keep = 0.991 +2.03.735.781 I cmn common_reaso: activated, budget=4096 tokens +2.03.735.782 I cmn common_reaso: deactivated (natural end) +2.03.735.932 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +2.03.735.942 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +2.03.735.943 I slot launch_slot_: id 0 | task 155 | processing task, is_child = 0 +2.03.735.950 I slot operator(): id 0 | task 155 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 28858 +2.03.735.961 I slot operator(): id 0 | task 155 | checking checkpoint with [28853, 28853] against 28847... +2.03.735.962 I slot operator(): id 0 | task 155 | checking checkpoint with [28597, 28597] against 28847... +2.03.753.504 I slot operator(): id 0 | task 155 | restored context checkpoint (pos_min = 28597, pos_max = 28597, n_tokens = 28598, n_past = 28598, size = 170.923 MiB) +2.03.753.505 I slot operator(): id 0 | task 155 | erased invalidated context checkpoint (pos_min = 28853, pos_max = 28853, n_tokens = 28854, n_swa = 0, pos_next = 28598, size = 170.923 MiB) +2.03.760.251 I slot operator(): id 0 | task 155 | cached n_tokens = 28598, memory_seq_rm [28598, end) +2.03.760.472 I slot create_check: id 0 | task 155 | superseding context checkpoint at n_tokens = 28598 +2.03.842.403 I slot create_check: id 0 | task 155 | created context checkpoint 2 of 32 (pos_min = 28597, pos_max = 28597, n_tokens = 28598, size = 170.923 MiB) +2.04.540.238 I slot operator(): id 0 | task 155 | cached n_tokens = 28854, memory_seq_rm [28854, end) +2.04.543.819 I slot init_sampler: id 0 | task 155 | init sampler, took 3.52 ms, tokens: text = 28858, total = 28858 +2.04.601.242 I slot create_check: id 0 | task 155 | created context checkpoint 3 of 32 (pos_min = 28853, pos_max = 28853, n_tokens = 28854, size = 170.923 MiB) +2.08.628.764 I slot print_timing: id 0 | task 155 | n_gen = 102, tg = 25.70 t/s, tg_3s = 25.96 t/s +2.11.672.792 I slot print_timing: id 0 | task 155 | n_gen = 169, tg = 24.09 t/s, tg_3s = 22.01 t/s +2.14.886.513 I slot print_timing: id 0 | task 155 | n_gen = 235, tg = 22.97 t/s, tg_3s = 20.54 t/s +2.15.804.574 I slot print_timing: id 0 | task 155 | prompt eval time = 962.98 ms / 260 tokens ( 3.70 ms per token, 269.99 tokens per second) +2.15.804.589 I slot print_timing: id 0 | task 155 | eval time = 11105.49 ms / 256 tokens ( 43.55 ms per token, 22.96 tokens per second) +2.15.804.590 I slot print_timing: id 0 | task 155 | total time = 12068.47 ms / 516 tokens +2.15.804.591 I slot print_timing: id 0 | task 155 | graphs reused = 119 +2.15.804.604 I slot print_timing: id 0 | task 155 | draft acceptance = 0.67434 ( 205 accepted / 304 generated), mean len = 5.10 +2.15.804.604 I slot print_timing: id 0 | task 155 | acc per pos = (0.900, 0.820, 0.680, 0.520, 0.480, 0.380, 0.320) +2.15.804.638 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 4 181 178, #gen drafts = 178, #acc drafts = 166, #gen tokens = 1139, #acc tokens = 839, #mean acc len = 5.71, #acc rate/pos = (0.933, 0.865, 0.753, 0.657, 0.573, 0.500, 0.433), dur(b,g,a) = 0.236, 17413.293, 0.076 ms +2.15.805.097 I slot release: id 0 | task 155 | stop processing: n_tokens = 29113, truncated = 0 +2.15.805.122 I srv update_slots: all slots are idle diff --git a/data/raw/ctxlab-20261017/server-depth-q8_0.log b/data/raw/ctxlab-20261017/server-depth-q8_0.log new file mode 100644 index 0000000..5cabf09 --- /dev/null +++ b/data/raw/ctxlab-20261017/server-depth-q8_0.log @@ -0,0 +1,612 @@ +0.00.138.938 I srv llama_server: initializing ... +0.00.138.954 I cmn common_param: common_params_print_info: build 11526 (c85e6c598) with GNU 16.2.0 for Windows AMD64 +0.00.138.955 I cmn common_param: common_params_print_info: verbosity = 4 (adjust with the `-lv N` CLI arg) +0.00.138.955 I cmn common_param: device_info: +0.00.139.816 I cmn common_param: - Vulkan0 : Intel(R) Arc(TM) Pro B60 Graphics (24454 MiB, 23685 MiB free) +0.00.139.821 I cmn common_param: - CPU : AMD Ryzen 7 3700X 8-Core Processor (32656 MiB, 11606 MiB free) +0.00.139.841 I cmn common_param: system_info: n_threads = 8 (n_threads_batch = 8) / 16 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | REPACK = 1 | +0.00.140.251 I srv init: using 15 threads for HTTP server +0.00.140.312 W srv llama_server: security: no API key is set and CORS allows all origins (see https://github.com/ggml-org/llama.cpp/pull/25655) +0.00.154.101 I srv load_model: loading model 'C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf' +0.00.154.102 I srv load_model: local path 'C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf' +0.00.250.662 I llama_model_loader: loaded meta data with 50 key-value pairs and 866 tensors from C:/AI/models/thinkingcap/ThinkingCap-Qwen3.8-27B-Q4_K_M.gguf (version GGUF V3 (latest)) +0.00.250.697 I llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output. +0.00.250.703 I llama_model_loader: - kv 0: general.architecture str = qwen35 +0.00.250.704 I llama_model_loader: - kv 1: general.type str = model +0.00.250.708 I llama_model_loader: - kv 2: general.sampling.top_k i32 = 20 +0.00.250.716 I llama_model_loader: - kv 3: general.sampling.top_p f32 = 0.950000 +0.00.250.717 I llama_model_loader: - kv 4: general.sampling.temp f32 = 1.000000 +0.00.250.718 I llama_model_loader: - kv 5: general.size_label str = 27B +0.00.250.719 I llama_model_loader: - kv 6: general.license str = apache-2.0 +0.00.250.720 I llama_model_loader: - kv 7: general.base_model.count u32 = 1 +0.00.250.721 I llama_model_loader: - kv 8: general.base_model.0.name str = Qwen3.8 27B +0.00.250.722 I llama_model_loader: - kv 9: general.base_model.0.organization str = Qwen +0.00.250.725 I llama_model_loader: - kv 10: general.base_model.0.repo_url str = https://huggingface.co/Qwen/Qwen3.8-27B +0.00.250.734 I llama_model_loader: - kv 11: general.tags arr[str,3] = ["qwen3_8", "token-efficient", "effic... +0.00.250.735 I llama_model_loader: - kv 12: qwen35.block_count u32 = 65 +0.00.250.736 I llama_model_loader: - kv 13: qwen35.context_length u32 = 262144 +0.00.250.737 I llama_model_loader: - kv 14: qwen35.embedding_length u32 = 5120 +0.00.250.738 I llama_model_loader: - kv 15: qwen35.feed_forward_length u32 = 17408 +0.00.250.739 I llama_model_loader: - kv 16: qwen35.attention.head_count u32 = 24 +0.00.250.740 I llama_model_loader: - kv 17: qwen35.attention.head_count_kv u32 = 4 +0.00.250.742 I llama_model_loader: - kv 18: qwen35.rope.dimension_sections arr[i32,4] = [11, 11, 10, 0] +0.00.250.743 I llama_model_loader: - kv 19: qwen35.rope.freq_base f32 = 10000000.000000 +0.00.250.745 I llama_model_loader: - kv 20: qwen35.attention.layer_norm_rms_epsilon f32 = 0.000001 +0.00.250.746 I llama_model_loader: - kv 21: qwen35.attention.key_length u32 = 256 +0.00.250.747 I llama_model_loader: - kv 22: qwen35.attention.value_length u32 = 256 +0.00.250.747 I llama_model_loader: - kv 23: qwen35.nextn_predict_layers u32 = 1 +0.00.250.748 I llama_model_loader: - kv 24: qwen35.ssm.conv_kernel u32 = 4 +0.00.250.749 I llama_model_loader: - kv 25: qwen35.ssm.state_size u32 = 128 +0.00.250.750 I llama_model_loader: - kv 26: qwen35.ssm.group_count u32 = 16 +0.00.250.751 I llama_model_loader: - kv 27: qwen35.ssm.time_step_rank u32 = 48 +0.00.250.752 I llama_model_loader: - kv 28: qwen35.ssm.inner_size u32 = 6144 +0.00.250.758 I llama_model_loader: - kv 29: qwen35.attention.recurrent_layers arr[bool,65] = [true, true, true, false, true, true,... +0.00.250.759 I llama_model_loader: - kv 30: qwen35.full_attention_interval u32 = 4 +0.00.250.760 I llama_model_loader: - kv 31: qwen35.rope.dimension_count u32 = 64 +0.00.250.761 I llama_model_loader: - kv 32: tokenizer.ggml.model str = gpt2 +0.00.250.762 I llama_model_loader: - kv 33: tokenizer.ggml.pre str = qwen35 +0.00.284.134 I llama_model_loader: - kv 34: tokenizer.ggml.tokens arr[str,248320] = ["!", "\"", "#", "$", "%", "&", "'", ... +0.00.289.890 I llama_model_loader: - kv 35: tokenizer.ggml.token_type arr[i32,248320] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... +0.00.323.378 I llama_model_loader: - kv 36: tokenizer.ggml.merges arr[str,247587] = ["Ġ Ġ", "ĠĠ ĠĠ", "i n", "Ġ t",... +0.00.323.384 I llama_model_loader: - kv 37: tokenizer.ggml.eos_token_id u32 = 248046 +0.00.323.385 I llama_model_loader: - kv 38: tokenizer.ggml.padding_token_id u32 = 248044 +0.00.323.386 I llama_model_loader: - kv 39: tokenizer.ggml.bos_token_id u32 = 248044 +0.00.323.387 I llama_model_loader: - kv 40: tokenizer.ggml.add_bos_token bool = false +0.00.323.404 I llama_model_loader: - kv 41: tokenizer.chat_template str = {%- set image_count = namespace(value... +0.00.323.405 I llama_model_loader: - kv 42: general.quantization_version u32 = 2 +0.00.323.406 I llama_model_loader: - kv 43: general.file_type u32 = 15 +0.00.323.408 I llama_model_loader: - kv 44: general.name str = ThinkingCap Qwen3.8 27B +0.00.323.410 I llama_model_loader: - kv 45: general.basename str = ThinkingCap-Qwen3.8 +0.00.323.413 I llama_model_loader: - kv 46: quantize.imatrix.file str = /mnt/storage/caveman/oplatek/Thinking... +0.00.323.416 I llama_model_loader: - kv 47: quantize.imatrix.dataset str = /mnt/storage/caveman/oplatek/gguf-cal... +0.00.323.417 I llama_model_loader: - kv 48: quantize.imatrix.entries_count u32 = 496 +0.00.323.418 I llama_model_loader: - kv 49: quantize.imatrix.chunks_count u32 = 583 +0.00.323.420 I llama_model_loader: - type f32: 456 tensors +0.00.323.420 I llama_model_loader: - type q4_0: 8 tensors +0.00.323.421 I llama_model_loader: - type q8_0: 64 tensors +0.00.323.422 I llama_model_loader: - type q4_K: 257 tensors +0.00.323.422 I llama_model_loader: - type q5_K: 2 tensors +0.00.323.423 I llama_model_loader: - type q6_K: 79 tensors +0.00.323.431 I print_info: file format = GGUF V3 (latest) +0.00.323.433 I print_info: file type = Q4_K - Medium +0.00.323.440 I print_info: file size = 16.23 GiB (5.10 BPW) +0.00.325.268 I llama_prepare_model_devices: using device Vulkan0 (Intel(R) Arc(TM) Pro B60 Graphics) (unknown id) - 23685 MiB free +0.00.521.440 I load: 0 unused tokens +0.00.592.863 I load: printing all EOG tokens: +0.00.592.864 I load: - 248044 ('<|endoftext|>') +0.00.592.865 I load: - 248046 ('<|im_end|>') +0.00.592.865 I load: - 248063 ('<|fim_pad|>') +0.00.592.866 I load: - 248064 ('<|repo_name|>') +0.00.592.866 I load: - 248065 ('<|file_sep|>') +0.00.593.335 I load: special tokens cache size = 33 +0.00.678.532 I load: token to piece cache size = 1.7581 MB +0.00.678.548 I print_info: arch = qwen35 +0.00.678.548 I print_info: vocab_only = 0 +0.00.678.549 I print_info: no_alloc = 0 +0.00.678.549 I print_info: n_ctx_train = 262144 +0.00.678.550 I print_info: n_embd_inp = 5120 +0.00.678.550 I print_info: n_embd = 5120 +0.00.678.551 I print_info: n_embd_out = 5120 +0.00.678.551 I print_info: n_layer = 64 +0.00.678.551 I print_info: n_layer_all = 65 +0.00.678.557 I print_info: n_head = 24 +0.00.678.559 I print_info: n_head_kv = 4 +0.00.678.559 I print_info: n_rot = 64 +0.00.678.559 I print_info: n_swa = 0 +0.00.678.560 I print_info: is_swa_any = 0 +0.00.678.560 I print_info: non_causal_type = 0 +0.00.678.561 I print_info: n_embd_head_k = 256 +0.00.678.561 I print_info: n_embd_head_v = 256 +0.00.678.563 I print_info: n_gqa = 6 +0.00.678.564 I print_info: n_embd_k_gqa = 1024 +0.00.678.566 I print_info: n_embd_v_gqa = 1024 +0.00.678.567 I print_info: f_norm_eps = 0.0e+00 +0.00.678.569 I print_info: f_norm_rms_eps = 1.0e-06 +0.00.678.569 I print_info: f_clamp_kqv = 0.0e+00 +0.00.678.570 I print_info: f_max_alibi_bias = 0.0e+00 +0.00.678.570 I print_info: f_logit_scale = 0.0e+00 +0.00.678.571 I print_info: f_attn_scale = 0.0e+00 +0.00.678.572 I print_info: f_attn_value_scale = 0.0000 +0.00.678.573 I print_info: n_ff = 17408 +0.00.678.574 I print_info: n_expert = 0 +0.00.678.574 I print_info: n_expert_used = 0 +0.00.678.574 I print_info: n_expert_groups = 0 +0.00.678.575 I print_info: n_group_used = 0 +0.00.678.575 I print_info: causal attn = 1 +0.00.678.575 I print_info: pooling type = -1 +0.00.678.576 I print_info: rope type = 40 +0.00.678.576 I print_info: rope scaling = linear +0.00.678.577 I print_info: freq_base_train = 10000000.0 +0.00.678.578 I print_info: freq_scale_train = 1 +0.00.678.578 I print_info: n_ctx_orig_yarn = 262144 +0.00.678.579 I print_info: rope_yarn_log_mul = 0.0000 +0.00.678.579 I print_info: rope_finetuned = unknown +0.00.678.580 I print_info: mrope sections = [11, 11, 10, 0] +0.00.678.580 I print_info: ssm_d_conv = 4 +0.00.678.581 I print_info: ssm_d_inner = 6144 +0.00.678.581 I print_info: ssm_d_state = 128 +0.00.678.581 I print_info: ssm_dt_rank = 48 +0.00.678.582 I print_info: ssm_n_group = 16 +0.00.678.582 I print_info: ssm_dt_b_c_rms = 0 +0.00.678.583 I print_info: model type = 27B +0.00.678.585 I print_info: model params = 27.32 B +0.00.678.586 I print_info: general.name = ThinkingCap Qwen3.8 27B +0.00.678.588 I print_info: vocab type = BPE +0.00.678.589 I print_info: n_vocab = 248320 +0.00.678.589 I print_info: n_merges = 247587 +0.00.678.590 I print_info: BOS token = 248044 '<|endoftext|>' +0.00.678.590 I print_info: EOS token = 248046 '<|im_end|>' +0.00.678.591 I print_info: EOT token = 248046 '<|im_end|>' +0.00.678.591 I print_info: PAD token = 248044 '<|endoftext|>' +0.00.678.592 I print_info: LF token = 198 'Ċ' +0.00.678.592 I print_info: FIM PRE token = 248060 '<|fim_prefix|>' +0.00.678.593 I print_info: FIM SUF token = 248062 '<|fim_suffix|>' +0.00.678.593 I print_info: FIM MID token = 248061 '<|fim_middle|>' +0.00.678.594 I print_info: FIM PAD token = 248063 '<|fim_pad|>' +0.00.678.594 I print_info: FIM REP token = 248064 '<|repo_name|>' +0.00.678.595 I print_info: FIM SEP token = 248065 '<|file_sep|>' +0.00.678.595 I print_info: EOG token = 248044 '<|endoftext|>' +0.00.678.596 I print_info: EOG token = 248046 '<|im_end|>' +0.00.678.596 I print_info: EOG token = 248063 '<|fim_pad|>' +0.00.678.597 I print_info: EOG token = 248064 '<|repo_name|>' +0.00.678.597 I print_info: EOG token = 248065 '<|file_sep|>' +0.00.678.598 I print_info: max token length = 256 +0.00.679.524 I load_tensors: loading model tensors, this can take a while... (load_mode = dio) +0.00.727.379 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring +0.00.727.391 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring +0.00.727.419 W model has unused tensor blk.64.attn_q.weight (size = 35389440 bytes) -- ignoring +0.00.727.429 W model has unused tensor blk.64.attn_k.weight (size = 2949120 bytes) -- ignoring +0.00.727.439 W model has unused tensor blk.64.attn_v.weight (size = 2949120 bytes) -- ignoring +0.00.727.475 W model has unused tensor blk.64.attn_output.weight (size = 17694720 bytes) -- ignoring +0.00.727.485 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring +0.00.727.495 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring +0.00.727.505 W model has unused tensor blk.64.ffn_gate.weight (size = 50135040 bytes) -- ignoring +0.00.727.515 W model has unused tensor blk.64.ffn_down.weight (size = 50135040 bytes) -- ignoring +0.00.727.525 W model has unused tensor blk.64.ffn_up.weight (size = 50135040 bytes) -- ignoring +0.00.727.536 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 29491200 bytes) -- ignoring +0.00.727.547 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring +0.00.727.557 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring +0.00.727.587 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring +0.02.780.855 I load_tensors: offloading output layer to GPU +0.02.780.860 I load_tensors: offloading 64 repeating layers to GPU +0.02.780.861 I load_tensors: offloaded 66/66 layers to GPU +0.02.780.867 I load_tensors: Vulkan0 model buffer size = 15713.94 MiB +0.02.780.868 I load_tensors: Vulkan_Host model buffer size = 682.03 MiB +0.12.277.547 I cmn common_init_: added <|endoftext|> logit bias = -inf +0.12.277.553 I cmn common_init_: added <|im_end|> logit bias = -inf +0.12.277.555 I cmn common_init_: added <|fim_pad|> logit bias = -inf +0.12.277.556 I cmn common_init_: added <|repo_name|> logit bias = -inf +0.12.277.556 I cmn common_init_: added <|file_sep|> logit bias = -inf +0.12.278.379 I llama_context: constructing llama_context +0.12.278.386 I llama_context: n_seq_max = 1 +0.12.278.387 I llama_context: n_ctx = 40960 +0.12.278.388 I llama_context: n_ctx_seq = 40960 +0.12.278.388 I llama_context: n_batch = 2048 +0.12.278.389 I llama_context: n_ubatch = 256 +0.12.278.389 I llama_context: causal_attn = 1 +0.12.278.390 I llama_context: flash_attn = enabled +0.12.278.390 I llama_context: kv_unified = false +0.12.278.393 I llama_context: freq_base = 10000000.0 +0.12.278.394 I llama_context: freq_scale = 1 +0.12.278.395 I llama_context: n_rs_seq = 7 +0.12.278.395 I llama_context: n_outputs_max = 8 +0.12.278.395 I llama_context: n_outputs_max_per_seq = 8 +0.12.278.397 I llama_context: n_ctx_seq (40960) < n_ctx_train (262144) -- the full capacity of the model will not be utilized +0.12.278.933 I llama_context: Vulkan_Host output buffer size = 0.95 MiB +0.12.476.551 I llama_kv_cache: Vulkan0 KV buffer size = 1360.00 MiB +0.12.486.319 I llama_kv_cache: size = 1360.00 MiB ( 40960 cells, 16 layers, 1/1 seqs), K (q8_0): 680.00 MiB, V (q8_0): 680.00 MiB +0.12.486.327 I llama_kv_cache: n_rot_k = 256, n_embd_head_k_all = 256 +0.12.486.328 I llama_kv_cache: n_rot_v = 64, n_embd_head_k_all = 256 +0.12.649.899 I llama_memory_recurrent: Vulkan0 RS buffer size = 1197.00 MiB +0.12.649.911 I llama_memory_recurrent: size = 1197.00 MiB ( 1 cells, 64 layers, 1 seqs 7 rs_seq), R (f32): 45.00 MiB, S (f32): 1152.00 MiB, P (f32): 0.00 MiB +0.12.649.924 I sched_reserve: reserving ... +0.12.652.689 I resolve_fused_ops: resolving fused DeepSeek V4 HC support: +0.12.662.852 I resolve_fused_ops: fused DeepSeek V4 HC pre enabled +0.12.671.299 I resolve_fused_ops: fused DeepSeek V4 HC comb enabled +0.12.679.573 I resolve_fused_ops: fused DeepSeek V4 HC post enabled +0.12.727.370 I sched_reserve: Vulkan0 compute buffer size = 96.28 MiB +0.12.727.377 I sched_reserve: Vulkan_Host compute buffer size = 40.28 MiB +0.12.727.382 I sched_reserve: graph: nodes = 5049, splits = 2, input objects = 4, input tensors = 12 +0.12.727.385 I sched_reserve: reserve took 77.46 ms, sched copies = 1 +0.12.727.656 I cmn init: llama threadpool init, n_threads = 8 +0.12.728.262 I cmn common_init_: warming up the model with an empty run - please wait ... (--no-warmup to disable) +0.12.843.568 I common_speculative_init_result: loading draft model 'C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf' +0.12.936.003 I llama_model_loader: loaded meta data with 48 key-value pairs and 81 tensors from C:/AI/models/qwen3.8-27b/Qwen3.8-27B-DFlash2-Q4_K_M.gguf (version GGUF V3 (latest)) +0.12.936.012 I llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output. +0.12.936.015 I llama_model_loader: - kv 0: general.architecture str = dflash +0.12.936.016 I llama_model_loader: - kv 1: general.type str = model +0.12.936.017 I llama_model_loader: - kv 2: general.name str = Qwen3.8-27B-DFlash2 +0.12.936.018 I llama_model_loader: - kv 3: general.author str = Inco AI +0.12.936.019 I llama_model_loader: - kv 4: general.organization str = z-lab +0.12.936.020 I llama_model_loader: - kv 5: general.finetune str = DFlash2 +0.12.936.021 I llama_model_loader: - kv 6: general.basename str = Qwen3.8-27B +0.12.936.022 I llama_model_loader: - kv 7: general.size_label str = 1.9B +0.12.936.023 I llama_model_loader: - kv 8: general.license str = apache-2.0 +0.12.936.026 I llama_model_loader: - kv 9: general.source.url str = https://huggingface.co/z-lab/Qwen3.8-... +0.12.936.028 I llama_model_loader: - kv 10: general.base_model.count u32 = 1 +0.12.936.029 I llama_model_loader: - kv 11: general.base_model.0.name str = Qwen3.8 27B +0.12.936.029 I llama_model_loader: - kv 12: general.base_model.0.organization str = Qwen +0.12.936.031 I llama_model_loader: - kv 13: general.base_model.0.repo_url str = https://huggingface.co/Qwen/Qwen3.8-27B +0.12.936.040 I llama_model_loader: - kv 14: general.tags arr[str,6] = ["dflash2", "speculative-decoding", "... +0.12.936.041 I llama_model_loader: - kv 15: dflash.block_count u32 = 5 +0.12.936.042 I llama_model_loader: - kv 16: dflash.context_length u32 = 262144 +0.12.936.043 I llama_model_loader: - kv 17: dflash.embedding_length u32 = 5120 +0.12.936.044 I llama_model_loader: - kv 18: dflash.feed_forward_length u32 = 17408 +0.12.936.045 I llama_model_loader: - kv 19: dflash.attention.head_count u32 = 32 +0.12.936.045 I llama_model_loader: - kv 20: dflash.attention.head_count_kv u32 = 8 +0.12.936.047 I llama_model_loader: - kv 21: dflash.attention.causal bool = false +0.12.936.051 I llama_model_loader: - kv 22: dflash.rope.freq_base f32 = 10000000.000000 +0.12.936.053 I llama_model_loader: - kv 23: dflash.attention.layer_norm_rms_epsilon f32 = 0.000001 +0.12.936.053 I llama_model_loader: - kv 24: dflash.attention.key_length u32 = 128 +0.12.936.054 I llama_model_loader: - kv 25: dflash.attention.value_length u32 = 128 +0.12.936.055 I llama_model_loader: - kv 26: dflash.block_size u32 = 8 +0.12.936.056 I llama_model_loader: - kv 27: dflash.conv_kernel_size u32 = 2 +0.12.936.057 I llama_model_loader: - kv 28: dflash.conv_group_size u32 = 16 +0.12.936.058 I llama_model_loader: - kv 29: dflash.selector_rank u32 = 256 +0.12.936.059 I llama_model_loader: - kv 30: dflash.selector_top_k u32 = 16 +0.12.936.061 I llama_model_loader: - kv 31: dflash.target_layers arr[i32,5] = [6, 20, 34, 48, 62] +0.12.936.062 I llama_model_loader: - kv 32: dflash.attention.sliding_window u32 = 2048 +0.12.936.064 I llama_model_loader: - kv 33: dflash.attention.sliding_window_pattern arr[bool,5] = [true, true, true, true, true] +0.12.936.065 I llama_model_loader: - kv 34: tokenizer.ggml.model str = gpt2 +0.12.936.066 I llama_model_loader: - kv 35: tokenizer.ggml.pre str = qwen35 +0.12.970.954 I llama_model_loader: - kv 36: tokenizer.ggml.tokens arr[str,248320] = ["!", "\"", "#", "$", "%", "&", "'", ... +0.12.976.801 I llama_model_loader: - kv 37: tokenizer.ggml.token_type arr[i32,248320] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... +0.13.011.752 I llama_model_loader: - kv 38: tokenizer.ggml.merges arr[str,247587] = ["Ġ Ġ", "ĠĠ ĠĠ", "i n", "Ġ t",... +0.13.011.756 I llama_model_loader: - kv 39: tokenizer.ggml.eos_token_id u32 = 248046 +0.13.011.757 I llama_model_loader: - kv 40: tokenizer.ggml.padding_token_id u32 = 248044 +0.13.011.758 I llama_model_loader: - kv 41: tokenizer.ggml.bos_token_id u32 = 248044 +0.13.011.759 I llama_model_loader: - kv 42: tokenizer.ggml.add_bos_token bool = false +0.13.011.765 I llama_model_loader: - kv 43: tokenizer.chat_template str = {%- set image_count = namespace(value... +0.13.011.766 I llama_model_loader: - kv 44: tokenizer.ggml.mask_token_id u32 = 248070 +0.13.011.767 I llama_model_loader: - kv 45: general.quantization_version u32 = 2 +0.13.011.768 I llama_model_loader: - kv 46: general.file_type u32 = 15 +0.13.011.772 I llama_model_loader: - kv 47: dflash.rope.dimension_sections arr[i32,4] = [64, 0, 0, 0] +0.13.011.773 I llama_model_loader: - type f32: 32 tensors +0.13.011.774 I llama_model_loader: - type q4_K: 45 tensors +0.13.011.775 I llama_model_loader: - type q6_K: 4 tensors +0.13.011.776 I print_info: file format = GGUF V3 (latest) +0.13.011.776 I print_info: file type = Q4_K - Medium +0.13.011.781 I print_info: file size = 1.05 GiB (4.71 BPW) +0.13.013.530 I llama_prepare_model_devices: using device Vulkan0 (Intel(R) Arc(TM) Pro B60 Graphics) (unknown id) - 4703 MiB free +0.13.014.039 I load_arch_hparams: DFlash extract_layers = [6, 20, 34, 48, 62] +0.13.269.328 I load: 0 unused tokens +0.13.352.013 I load: printing all EOG tokens: +0.13.352.015 I load: - 248044 ('<|endoftext|>') +0.13.352.015 I load: - 248046 ('<|im_end|>') +0.13.352.016 I load: - 248063 ('<|fim_pad|>') +0.13.352.017 I load: - 248064 ('<|repo_name|>') +0.13.352.017 I load: - 248065 ('<|file_sep|>') +0.13.352.708 I load: special tokens cache size = 33 +0.13.442.628 I load: token to piece cache size = 1.7581 MB +0.13.442.639 I print_info: arch = dflash +0.13.442.639 I print_info: vocab_only = 0 +0.13.442.640 I print_info: no_alloc = 0 +0.13.442.640 I print_info: n_ctx_train = 262144 +0.13.442.641 I print_info: n_embd_inp = 5120 +0.13.442.641 I print_info: n_embd = 5120 +0.13.442.642 I print_info: n_embd_out = 5120 +0.13.442.642 I print_info: n_layer = 5 +0.13.442.642 I print_info: n_layer_all = 5 +0.13.442.647 I print_info: n_head = 32 +0.13.442.648 I print_info: n_head_kv = 8 +0.13.442.649 I print_info: n_rot = 128 +0.13.442.649 I print_info: n_swa = 2048 +0.13.442.649 I print_info: is_swa_any = 1 +0.13.442.650 I print_info: non_causal_type = 0 +0.13.442.650 I print_info: n_embd_head_k = 128 +0.13.442.651 I print_info: n_embd_head_v = 128 +0.13.442.652 I print_info: n_gqa = 4 +0.13.442.652 I print_info: n_embd_k_gqa = 1024 +0.13.442.653 I print_info: n_embd_v_gqa = 1024 +0.13.442.654 I print_info: f_norm_eps = 0.0e+00 +0.13.442.656 I print_info: f_norm_rms_eps = 1.0e-06 +0.13.442.657 I print_info: f_clamp_kqv = 0.0e+00 +0.13.442.657 I print_info: f_max_alibi_bias = 0.0e+00 +0.13.442.658 I print_info: f_logit_scale = 0.0e+00 +0.13.442.658 I print_info: f_attn_scale = 0.0e+00 +0.13.442.659 I print_info: f_attn_value_scale = 0.0000 +0.13.442.660 I print_info: n_ff = 17408 +0.13.442.660 I print_info: n_expert = 0 +0.13.442.661 I print_info: n_expert_used = 0 +0.13.442.661 I print_info: n_expert_groups = 0 +0.13.442.661 I print_info: n_group_used = 0 +0.13.442.662 I print_info: causal attn = 0 +0.13.442.662 I print_info: pooling type = -1 +0.13.442.662 I print_info: rope type = 8 +0.13.442.663 I print_info: rope scaling = linear +0.13.442.664 I print_info: freq_base_train = 10000000.0 +0.13.442.664 I print_info: freq_scale_train = 1 +0.13.442.665 I print_info: freq_base_swa = 10000000.0 +0.13.442.666 I print_info: freq_scale_swa = 1 +0.13.442.666 I print_info: n_embd_head_k_swa = 128 +0.13.442.667 I print_info: n_embd_head_v_swa = 128 +0.13.442.667 I print_info: n_rot_swa = 128 +0.13.442.667 I print_info: n_ctx_orig_yarn = 262144 +0.13.442.668 I print_info: rope_yarn_log_mul = 0.0000 +0.13.442.668 I print_info: rope_finetuned = unknown +0.13.442.669 I print_info: mrope sections = [64, 0, 0, 0] +0.13.442.670 I print_info: model type = ?B +0.13.442.671 I print_info: model params = 1.92 B +0.13.442.672 I print_info: general.name = Qwen3.8-27B-DFlash2 +0.13.442.672 I print_info: vocab type = BPE +0.13.442.673 I print_info: n_vocab = 248320 +0.13.442.673 I print_info: n_merges = 247587 +0.13.442.674 I print_info: BOS token = 248044 '<|endoftext|>' +0.13.442.674 I print_info: EOS token = 248046 '<|im_end|>' +0.13.442.675 I print_info: EOT token = 248046 '<|im_end|>' +0.13.442.675 I print_info: PAD token = 248044 '<|endoftext|>' +0.13.442.676 I print_info: MASK token = 248070 '<|audio_start|>' +0.13.442.676 I print_info: LF token = 198 'Ċ' +0.13.442.677 I print_info: FIM PRE token = 248060 '<|fim_prefix|>' +0.13.442.677 I print_info: FIM SUF token = 248062 '<|fim_suffix|>' +0.13.442.678 I print_info: FIM MID token = 248061 '<|fim_middle|>' +0.13.442.678 I print_info: FIM PAD token = 248063 '<|fim_pad|>' +0.13.442.679 I print_info: FIM REP token = 248064 '<|repo_name|>' +0.13.442.679 I print_info: FIM SEP token = 248065 '<|file_sep|>' +0.13.442.680 I print_info: EOG token = 248044 '<|endoftext|>' +0.13.442.680 I print_info: EOG token = 248046 '<|im_end|>' +0.13.442.681 I print_info: EOG token = 248063 '<|fim_pad|>' +0.13.442.681 I print_info: EOG token = 248064 '<|repo_name|>' +0.13.442.682 I print_info: EOG token = 248065 '<|file_sep|>' +0.13.442.682 I print_info: max token length = 256 +0.13.443.985 I load_tensors: loading model tensors, this can take a while... (load_mode = dio) +0.13.445.153 I load_arch_tensors: DFlash2 conv kernel = 2, group = 16, selector rank = 256, top-k = 16 +0.13.582.957 I load_tensors: offloading output layer to GPU +0.13.582.958 I load_tensors: offloading 4 repeating layers to GPU +0.13.582.958 I load_tensors: offloaded 6/6 layers to GPU +0.13.582.963 I load_tensors: Vulkan0 model buffer size = 1079.61 MiB +0.14.153.614 I llama_context: constructing llama_context +0.14.153.622 I llama_context: n_seq_max = 1 +0.14.153.623 I llama_context: n_ctx = 40960 +0.14.153.623 I llama_context: n_ctx_seq = 40960 +0.14.153.623 I llama_context: n_batch = 2048 +0.14.153.624 I llama_context: n_ubatch = 256 +0.14.153.624 I llama_context: causal_attn = 0 +0.14.153.626 I llama_context: flash_attn = enabled +0.14.153.626 I llama_context: kv_unified = false +0.14.153.630 I llama_context: freq_base = 10000000.0 +0.14.153.631 I llama_context: freq_scale = 1 +0.14.153.631 I llama_context: n_rs_seq = 0 +0.14.153.632 I llama_context: n_outputs_max = 2048 +0.14.153.632 I llama_context: n_outputs_max_per_seq = 8 +0.14.153.633 I llama_context: n_ctx_seq (40960) < n_ctx_train (262144) -- the full capacity of the model will not be utilized +0.14.153.905 I llama_context: Vulkan_Host output buffer size = 0.95 MiB +0.14.154.221 I llama_kv_cache_iswa: creating non-SWA KV cache, size = 40960 cells +0.14.154.627 I llama_kv_cache: size = 0.00 MiB ( 40960 cells, 0 layers, 1/1 seqs), K (q8_0): 0.00 MiB, V (q8_0): 0.00 MiB +0.14.154.630 I llama_kv_cache: n_rot_k = 0, n_embd_head_k_all = 0 +0.14.154.630 I llama_kv_cache: n_rot_v = 0, n_embd_head_k_all = 0 +0.14.154.634 I llama_kv_cache_iswa: creating SWA KV cache, size = 2304 cells +0.14.157.895 I llama_kv_cache: Vulkan0 KV buffer size = 23.91 MiB +0.14.158.178 I llama_kv_cache: size = 23.91 MiB ( 2304 cells, 5 layers, 1/1 seqs), K (q8_0): 11.95 MiB, V (q8_0): 11.95 MiB +0.14.158.182 I llama_kv_cache: n_rot_k = 128, n_embd_head_k_all = 128 +0.14.158.182 I llama_kv_cache: n_rot_v = 64, n_embd_head_k_all = 128 +0.14.158.202 I sched_reserve: reserving ... +0.14.158.317 I resolve_fused_ops: resolving fused DeepSeek V4 HC support: +0.14.159.808 I resolve_fused_ops: fused DeepSeek V4 HC pre enabled +0.14.160.591 I resolve_fused_ops: fused DeepSeek V4 HC comb enabled +0.14.161.338 I resolve_fused_ops: fused DeepSeek V4 HC post enabled +0.14.200.445 I sched_reserve: Vulkan0 compute buffer size = 277.73 MiB +0.14.200.446 I sched_reserve: Vulkan_Host compute buffer size = 6.21 MiB +0.14.200.449 I sched_reserve: graph (pp bs=256, tg bs=1): nodes = 751 / 531, splits = 2 / 2, input objects = 3 / 3, input tensors = 7 / 7 +0.14.200.450 I sched_reserve: reserve took 42.25 ms, sched copies = 1 +0.14.200.549 I cmn common_conte: the context supports bounded partial sequence removal +0.14.200.550 I srv load_model: initializing, n_slots = 1, n_ctx_slot = 40960, kv_unified = 'false' +0.14.200.913 I common_speculative_impl_draft_dflash: adding speculative implementation 'draft-dflash' +0.14.200.915 I common_speculative_impl_draft_dflash: - n_max=7, n_min=0, p_min=0.50 +0.14.200.915 I common_speculative_impl_draft_dflash: - block_size=8, mask_token_id=248070, n_extract=5, sample_from_anchor=true +0.14.201.404 I sched_reserve: reserving ... +0.14.244.785 I sched_reserve: Vulkan0 compute buffer size = 277.73 MiB +0.14.244.787 I sched_reserve: Vulkan_Host compute buffer size = 6.21 MiB +0.14.244.789 I sched_reserve: graph (pp bs=256, tg bs=1): nodes = 751 / 531, splits = 2 / 2, input objects = 3 / 3, input tensors = 7 / 7 +0.14.244.791 I sched_reserve: reserve took 43.38 ms, sched copies = 1 +0.14.275.185 I srv load_model: speculative decoding context initialized +0.14.275.187 I slot load_model: id 0 | task -1 | new slot, n_ctx = 40960 +0.14.275.341 I srv load_model: prompt cache is enabled, size limit: 2048 MiB +0.14.275.341 I srv load_model: use `--cache-ram 0` to disable the prompt cache +0.14.275.342 I srv load_model: for more info see https://github.com/ggml-org/llama.cpp/pull/16391 +0.14.275.343 I srv load_model: context checkpoints enabled, max = 32, min spacing = 8192 +0.14.275.489 I srv init: idle slots will be saved to prompt cache upon starting a new task +0.14.283.426 I srv init: init: chat template, example_format: '<|im_start|>system +Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer. + +You are a helpful assistant<|im_end|> +<|im_start|>user +Hello<|im_end|> +<|im_start|>assistant + + + + +Hi there<|im_end|> +<|im_start|>user +How are you?<|im_end|> +<|im_start|>assistant + +' +0.14.285.046 I srv init: init: chat template, thinking = 1 +0.14.285.174 I srv init: preserve_reasoning kwarg: true +0.14.285.175 W srv init: chat template supports preserving reasoning, it is enabled by default (may use more tokens, disable via --no-reasoning-preserve) +0.14.285.617 I srv llama_server: model loaded +0.14.285.619 I srv llama_server: listening on http://127.0.0.1:10012 +0.14.286.102 I srv update_slots: all slots are idle +0.19.726.891 I srv server_strea: conv_id= (empty=1) +0.19.739.838 I srv operator(): chat format: peg-native +0.19.741.954 I slot get_availabl: id 0 | task -1 | - skipping, slot is empty +0.19.741.955 I slot get_availabl: id 0 | task -1 | selected slot by LRU, t_last = -1 +0.19.741.955 I srv get_availabl: updating prompt cache +0.19.742.126 I srv load: - looking for better prompt, base f_keep = -1.000, f_sim = 0.000 +0.19.742.128 I srv update: - cache state: 0 prompts, 0.000 MiB (limits: 2048.000 MiB, 40960 tokens, 2147483648 est) +0.19.742.130 I srv get_availabl: prompt cache update took 0.17 ms +0.19.742.835 I cmn common_reaso: activated, budget=4096 tokens +0.19.742.838 I cmn common_reaso: deactivated (natural end) +0.19.743.169 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.19.743.188 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.19.743.192 I slot launch_slot_: id 0 | task 0 | processing task, is_child = 0 +0.19.743.342 I slot operator(): id 0 | task 0 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 3875 +0.19.743.511 I slot operator(): id 0 | task 0 | cached n_tokens = 0, memory_seq_rm [0, end) +0.19.744.825 I sched_reserve: reserving ... +0.19.839.972 I sched_reserve: Vulkan0 compute buffer size = 116.28 MiB +0.19.839.975 I sched_reserve: Vulkan_Host compute buffer size = 40.28 MiB +0.19.839.980 I sched_reserve: graph: nodes = 5049, splits = 2, input objects = 4, input tensors = 12 +0.19.839.983 I sched_reserve: reserve took 95.14 ms, sched copies = 1 +0.24.323.977 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 2048, progress = 0.53, t = 3.81 s / 537.63 tokens per second +0.24.323.981 I slot operator(): id 0 | task 0 | cached n_tokens = 2048, memory_seq_rm [2048, end) +0.28.204.014 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 3615, progress = 0.93, t = 8.02 s / 450.96 tokens per second +0.28.204.018 I slot operator(): id 0 | task 0 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.28.272.341 I slot create_check: id 0 | task 0 | created context checkpoint 1 of 32 (pos_min = 3614, pos_max = 3614, n_tokens = 3615, size = 170.923 MiB) +0.28.919.722 I slot print_timing: id 0 | task 0 | prompt processing, n_tokens = 3871, progress = 1.00, t = 8.58 s / 451.39 tokens per second +0.28.919.725 I slot operator(): id 0 | task 0 | cached n_tokens = 3871, memory_seq_rm [3871, end) +0.28.920.557 I slot init_sampler: id 0 | task 0 | init sampler, took 0.77 ms, tokens: text = 3875, total = 3875 +0.28.984.007 I slot create_check: id 0 | task 0 | created context checkpoint 2 of 32 (pos_min = 3870, pos_max = 3870, n_tokens = 3871, size = 170.923 MiB) +0.32.213.401 I slot print_timing: id 0 | task 0 | n_gen = 100, tg = 32.03 t/s, tg_3s = 32.36 t/s +0.35.242.226 I slot print_timing: id 0 | task 0 | n_gen = 200, tg = 32.52 t/s, tg_3s = 33.02 t/s +0.36.663.692 I slot print_timing: id 0 | task 0 | prompt eval time = 9379.34 ms / 3875 tokens ( 2.42 ms per token, 413.14 tokens per second) +0.36.663.703 I slot print_timing: id 0 | task 0 | eval time = 7540.88 ms / 256 tokens ( 29.57 ms per token, 33.82 tokens per second) +0.36.663.705 I slot print_timing: id 0 | task 0 | total time = 16920.22 ms / 4131 tokens +0.36.663.706 I slot print_timing: id 0 | task 0 | graphs reused = 35 +0.36.663.718 I slot print_timing: id 0 | task 0 | draft acceptance = 0.75887 ( 214 accepted / 282 generated), mean len = 6.22 +0.36.663.719 I slot print_timing: id 0 | task 0 | acc per pos = (0.976, 0.878, 0.780, 0.756, 0.732, 0.610, 0.488) +0.36.664.117 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 1 41 41, #gen drafts = 41, #acc drafts = 40, #gen tokens = 282, #acc tokens = 214, #mean acc len = 6.22, #acc rate/pos = (0.976, 0.878, 0.780, 0.756, 0.732, 0.610, 0.488), dur(b,g,a) = 0.273, 868.102, 0.035 ms +0.36.664.478 I slot release: id 0 | task 0 | stop processing: n_tokens = 4130, truncated = 0 +0.36.664.622 I srv update_slots: all slots are idle +0.38.785.964 I srv server_strea: conv_id= (empty=1) +0.38.792.910 I srv operator(): chat format: peg-native +0.38.793.258 I slot get_availabl: id 0 | task -1 | - checking sim = 0.997 (3864/3875) > 0.100 +0.38.793.260 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 0.997 (> 0.100 thold), f_keep = 0.936 +0.38.793.306 I cmn common_reaso: activated, budget=4096 tokens +0.38.793.307 I cmn common_reaso: deactivated (natural end) +0.38.793.462 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.38.793.473 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.38.793.474 I slot launch_slot_: id 0 | task 46 | processing task, is_child = 0 +0.38.793.480 I slot operator(): id 0 | task 46 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 3875 +0.38.793.484 I slot operator(): id 0 | task 46 | checking checkpoint with [3870, 3870] against 3864... +0.38.793.484 I slot operator(): id 0 | task 46 | checking checkpoint with [3614, 3614] against 3864... +0.38.811.913 I slot operator(): id 0 | task 46 | restored context checkpoint (pos_min = 3614, pos_max = 3614, n_tokens = 3615, n_past = 3615, size = 170.923 MiB) +0.38.811.916 I slot operator(): id 0 | task 46 | erased invalidated context checkpoint (pos_min = 3870, pos_max = 3870, n_tokens = 3871, n_swa = 0, pos_next = 3615, size = 170.923 MiB) +0.38.820.565 I slot operator(): id 0 | task 46 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.38.820.870 I slot create_check: id 0 | task 46 | superseding context checkpoint at n_tokens = 3615 +0.38.899.618 I slot create_check: id 0 | task 46 | created context checkpoint 1 of 32 (pos_min = 3614, pos_max = 3614, n_tokens = 3615, size = 170.923 MiB) +0.39.562.833 I slot operator(): id 0 | task 46 | cached n_tokens = 3871, memory_seq_rm [3871, end) +0.39.563.369 I slot init_sampler: id 0 | task 46 | init sampler, took 0.47 ms, tokens: text = 3875, total = 3875 +0.39.623.984 I slot create_check: id 0 | task 46 | created context checkpoint 2 of 32 (pos_min = 3870, pos_max = 3870, n_tokens = 3871, size = 170.923 MiB) +0.42.954.754 I slot print_timing: id 0 | task 46 | n_gen = 102, tg = 31.42 t/s, tg_3s = 31.73 t/s +0.46.072.970 I slot print_timing: id 0 | task 46 | n_gen = 198, tg = 31.11 t/s, tg_3s = 30.79 t/s +0.48.068.396 I slot print_timing: id 0 | task 46 | prompt eval time = 946.70 ms / 260 tokens ( 3.64 ms per token, 274.64 tokens per second) +0.48.068.402 I slot print_timing: id 0 | task 46 | eval time = 8328.17 ms / 256 tokens ( 32.66 ms per token, 30.62 tokens per second) +0.48.068.403 I slot print_timing: id 0 | task 46 | total time = 9274.88 ms / 516 tokens +0.48.068.404 I slot print_timing: id 0 | task 46 | graphs reused = 67 +0.48.068.414 I slot print_timing: id 0 | task 46 | draft acceptance = 0.73944 ( 210 accepted / 284 generated), mean len = 6.00 +0.48.068.415 I slot print_timing: id 0 | task 46 | acc per pos = (0.929, 0.881, 0.762, 0.738, 0.619, 0.548, 0.524) +0.48.068.437 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 2 85 83, #gen drafts = 83, #acc drafts = 79, #gen tokens = 566, #acc tokens = 424, #mean acc len = 6.11, #acc rate/pos = (0.952, 0.880, 0.771, 0.747, 0.675, 0.578, 0.506), dur(b,g,a) = 0.274, 1781.734, 0.063 ms +0.48.068.522 I slot release: id 0 | task 46 | stop processing: n_tokens = 4130, truncated = 0 +0.48.068.540 I srv update_slots: all slots are idle +0.50.186.265 I srv server_strea: conv_id= (empty=1) +0.50.228.232 I srv operator(): chat format: peg-native +0.50.229.011 I slot get_availabl: id 0 | task -1 | - checking sim = 0.132 (3821/28858) > 0.100 +0.50.229.014 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 0.132 (> 0.100 thold), f_keep = 0.925 +0.50.229.107 I cmn common_reaso: activated, budget=4096 tokens +0.50.229.109 I cmn common_reaso: deactivated (natural end) +0.50.229.368 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +0.50.229.380 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +0.50.229.382 I slot launch_slot_: id 0 | task 94 | processing task, is_child = 0 +0.50.229.389 I slot operator(): id 0 | task 94 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 28858 +0.50.229.393 I slot operator(): id 0 | task 94 | checking checkpoint with [3870, 3870] against 3821... +0.50.229.394 I slot operator(): id 0 | task 94 | checking checkpoint with [3614, 3614] against 3821... +0.50.246.643 I slot operator(): id 0 | task 94 | restored context checkpoint (pos_min = 3614, pos_max = 3614, n_tokens = 3615, n_past = 3615, size = 170.923 MiB) +0.50.246.645 I slot operator(): id 0 | task 94 | erased invalidated context checkpoint (pos_min = 3870, pos_max = 3870, n_tokens = 3871, n_swa = 0, pos_next = 3615, size = 170.923 MiB) +0.50.253.183 I slot operator(): id 0 | task 94 | cached n_tokens = 3615, memory_seq_rm [3615, end) +0.55.799.867 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 2048, progress = 0.20, t = 4.70 s / 435.99 tokens per second +0.55.799.874 I slot operator(): id 0 | task 94 | cached n_tokens = 5663, memory_seq_rm [5663, end) +1.02.939.954 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 4096, progress = 0.27, t = 11.73 s / 349.19 tokens per second +1.02.939.957 I slot operator(): id 0 | task 94 | cached n_tokens = 7711, memory_seq_rm [7711, end) +1.10.070.820 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 6144, progress = 0.34, t = 18.80 s / 326.84 tokens per second +1.10.070.825 I slot operator(): id 0 | task 94 | cached n_tokens = 9759, memory_seq_rm [9759, end) +1.18.016.054 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 8192, progress = 0.41, t = 26.65 s / 307.43 tokens per second +1.18.016.058 I slot operator(): id 0 | task 94 | cached n_tokens = 11807, memory_seq_rm [11807, end) +1.26.793.221 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 10240, progress = 0.48, t = 35.31 s / 289.98 tokens per second +1.26.793.225 I slot operator(): id 0 | task 94 | cached n_tokens = 13855, memory_seq_rm [13855, end) +1.36.415.028 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 12288, progress = 0.55, t = 44.81 s / 274.20 tokens per second +1.36.415.031 I slot operator(): id 0 | task 94 | cached n_tokens = 15903, memory_seq_rm [15903, end) +1.46.914.379 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 14336, progress = 0.62, t = 55.15 s / 259.94 tokens per second +1.46.914.383 I slot operator(): id 0 | task 94 | cached n_tokens = 17951, memory_seq_rm [17951, end) +1.58.313.940 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 16384, progress = 0.69, t = 66.43 s / 246.65 tokens per second +1.58.313.950 I slot operator(): id 0 | task 94 | cached n_tokens = 19999, memory_seq_rm [19999, end) +2.10.379.093 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 18432, progress = 0.76, t = 78.50 s / 234.80 tokens per second +2.10.379.098 I slot operator(): id 0 | task 94 | cached n_tokens = 22047, memory_seq_rm [22047, end) +2.23.268.712 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 20480, progress = 0.83, t = 91.29 s / 224.34 tokens per second +2.23.268.718 I slot operator(): id 0 | task 94 | cached n_tokens = 24095, memory_seq_rm [24095, end) +2.36.959.402 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 22528, progress = 0.91, t = 104.89 s / 214.78 tokens per second +2.36.959.407 I slot operator(): id 0 | task 94 | cached n_tokens = 26143, memory_seq_rm [26143, end) +2.51.462.455 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 24576, progress = 0.98, t = 119.28 s / 206.04 tokens per second +2.51.462.460 I slot operator(): id 0 | task 94 | cached n_tokens = 28191, memory_seq_rm [28191, end) +2.54.681.500 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 24983, progress = 0.99, t = 123.10 s / 202.95 tokens per second +2.54.681.503 I slot operator(): id 0 | task 94 | cached n_tokens = 28598, memory_seq_rm [28598, end) +2.54.738.350 I slot create_check: id 0 | task 94 | created context checkpoint 2 of 32 (pos_min = 28597, pos_max = 28597, n_tokens = 28598, size = 170.923 MiB) +2.56.640.664 I slot print_timing: id 0 | task 94 | prompt processing, n_tokens = 25239, progress = 1.00, t = 124.57 s / 202.61 tokens per second +2.56.640.667 I slot operator(): id 0 | task 94 | cached n_tokens = 28854, memory_seq_rm [28854, end) +2.56.644.303 I slot init_sampler: id 0 | task 94 | init sampler, took 3.58 ms, tokens: text = 28858, total = 28858 +2.56.704.552 I slot create_check: id 0 | task 94 | created context checkpoint 3 of 32 (pos_min = 28853, pos_max = 28853, n_tokens = 28854, size = 170.923 MiB) +3.06.908.506 I slot print_timing: id 0 | task 94 | n_gen = 101, tg = 10.07 t/s, tg_3s = 10.17 t/s +3.10.014.470 I slot print_timing: id 0 | task 94 | n_gen = 138, tg = 10.51 t/s, tg_3s = 11.91 t/s +3.13.470.693 I slot print_timing: id 0 | task 94 | n_gen = 173, tg = 10.43 t/s, tg_3s = 10.13 t/s +3.16.929.515 I slot print_timing: id 0 | task 94 | n_gen = 212, tg = 10.57 t/s, tg_3s = 11.28 t/s +3.20.083.969 I slot print_timing: id 0 | task 94 | n_gen = 253, tg = 10.91 t/s, tg_3s = 13.00 t/s +3.20.313.752 I slot print_timing: id 0 | task 94 | prompt eval time = 126746.66 ms / 25243 tokens ( 5.02 ms per token, 199.16 tokens per second) +3.20.313.759 I slot print_timing: id 0 | task 94 | eval time = 23337.23 ms / 256 tokens ( 91.52 ms per token, 10.93 tokens per second) +3.20.313.759 I slot print_timing: id 0 | task 94 | total time = 150083.89 ms / 25499 tokens +3.20.313.761 I slot print_timing: id 0 | task 94 | graphs reused = 99 +3.20.313.769 I slot print_timing: id 0 | task 94 | draft acceptance = 0.64151 ( 204 accepted / 318 generated), mean len = 5.00 +3.20.313.770 I slot print_timing: id 0 | task 94 | acc per pos = (0.902, 0.824, 0.667, 0.549, 0.451, 0.314, 0.294) +3.20.313.791 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 3 136 134, #gen drafts = 134, #acc drafts = 125, #gen tokens = 884, #acc tokens = 628, #mean acc len = 5.69, #acc rate/pos = (0.933, 0.858, 0.731, 0.672, 0.590, 0.478, 0.425), dur(b,g,a) = 0.275, 2794.107, 0.080 ms +3.20.314.183 I slot release: id 0 | task 94 | stop processing: n_tokens = 29113, truncated = 0 +3.20.314.201 I srv update_slots: all slots are idle +3.22.456.971 I srv server_strea: conv_id= (empty=1) +3.22.502.777 I srv operator(): chat format: peg-native +3.22.503.604 I slot get_availabl: id 0 | task -1 | - checking sim = 1.000 (28847/28858) > 0.100 +3.22.503.606 I slot get_availabl: id 0 | task -1 | selected slot by LCP similarity, f_sim_best = 1.000 (> 0.100 thold), f_keep = 0.991 +3.22.503.683 I cmn common_reaso: activated, budget=4096 tokens +3.22.503.684 I cmn common_reaso: deactivated (natural end) +3.22.503.841 I slot launch_slot_: id 0 | task -1 | sampler chain: logits -> ?penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> min-p -> ?xtc -> temp-ext -> dist +3.22.503.851 I slot launch_slot_: id 0 | task -1 | sampler params: + repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 0.000 + dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64 + top_k = 20, top_p = 0.800, min_p = 0.050, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700 + mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900 +3.22.503.854 I slot launch_slot_: id 0 | task 161 | processing task, is_child = 0 +3.22.503.862 I slot operator(): id 0 | task 161 | new prompt, n_ctx_slot = 40960, n_keep = 0, task.n_tokens = 28858 +3.22.503.874 I slot operator(): id 0 | task 161 | checking checkpoint with [28853, 28853] against 28847... +3.22.503.874 I slot operator(): id 0 | task 161 | checking checkpoint with [28597, 28597] against 28847... +3.22.521.789 I slot operator(): id 0 | task 161 | restored context checkpoint (pos_min = 28597, pos_max = 28597, n_tokens = 28598, n_past = 28598, size = 170.923 MiB) +3.22.521.791 I slot operator(): id 0 | task 161 | erased invalidated context checkpoint (pos_min = 28853, pos_max = 28853, n_tokens = 28854, n_swa = 0, pos_next = 28598, size = 170.923 MiB) +3.22.530.838 I slot operator(): id 0 | task 161 | cached n_tokens = 28598, memory_seq_rm [28598, end) +3.22.531.069 I slot create_check: id 0 | task 161 | superseding context checkpoint at n_tokens = 28598 +3.22.621.554 I slot create_check: id 0 | task 161 | created context checkpoint 2 of 32 (pos_min = 28597, pos_max = 28597, n_tokens = 28598, size = 170.923 MiB) +3.24.545.016 I slot operator(): id 0 | task 161 | cached n_tokens = 28854, memory_seq_rm [28854, end) +3.24.548.615 I slot init_sampler: id 0 | task 161 | init sampler, took 3.54 ms, tokens: text = 28858, total = 28858 +3.24.634.652 I slot create_check: id 0 | task 161 | created context checkpoint 3 of 32 (pos_min = 28853, pos_max = 28853, n_tokens = 28854, size = 170.923 MiB) +3.33.201.078 I slot print_timing: id 0 | task 161 | n_gen = 100, tg = 11.94 t/s, tg_3s = 12.06 t/s +3.36.464.674 I slot print_timing: id 0 | task 161 | n_gen = 144, tg = 12.37 t/s, tg_3s = 13.48 t/s +3.39.881.929 I slot print_timing: id 0 | task 161 | n_gen = 167, tg = 11.09 t/s, tg_3s = 6.73 t/s +3.43.236.444 I slot print_timing: id 0 | task 161 | n_gen = 191, tg = 10.37 t/s, tg_3s = 7.15 t/s +3.46.861.261 I slot print_timing: id 0 | task 161 | n_gen = 230, tg = 10.43 t/s, tg_3s = 10.76 t/s +3.49.210.229 I slot print_timing: id 0 | task 161 | prompt eval time = 2404.04 ms / 260 tokens ( 9.25 ms per token, 108.15 tokens per second) +3.49.210.236 I slot print_timing: id 0 | task 161 | eval time = 24302.16 ms / 256 tokens ( 95.30 ms per token, 10.49 tokens per second) +3.49.210.237 I slot print_timing: id 0 | task 161 | total time = 26706.20 ms / 516 tokens +3.49.210.238 I slot print_timing: id 0 | task 161 | graphs reused = 129 +3.49.210.247 I slot print_timing: id 0 | task 161 | draft acceptance = 0.63522 ( 202 accepted / 318 generated), mean len = 4.81 +3.49.210.247 I slot print_timing: id 0 | task 161 | acc per pos = (0.887, 0.755, 0.623, 0.491, 0.434, 0.321, 0.302) +3.49.210.268 I spec common_specu: statistics draft-dflash: #calls(b,g,a) = 4 189 187, #gen drafts = 187, #acc drafts = 172, #gen tokens = 1202, #acc tokens = 830, #mean acc len = 5.44, #acc rate/pos = (0.920, 0.829, 0.701, 0.620, 0.545, 0.433, 0.390), dur(b,g,a) = 0.276, 3940.466, 0.101 ms +3.49.210.650 I slot release: id 0 | task 161 | stop processing: n_tokens = 29113, truncated = 0 +3.49.210.669 I srv update_slots: all slots are idle From 92a2ea7790588a7bec1a0ddfe5e7f4fb50ecfb42 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:04:06 +1100 Subject: [PATCH 11/16] Lean Codex home (start-up prompt 12,235 -> 3,010 tokens) --- agents/codex-lean/README.md | 23 +++++++ agents/codex-lean/codex-qwen-lean.cmd | 10 +++ agents/codex-lean/config.toml | 78 +++++++++++++++++++++++ agents/codex-lean/instructions-compact.md | 12 ++++ 4 files changed, 123 insertions(+) create mode 100644 agents/codex-lean/README.md create mode 100644 agents/codex-lean/codex-qwen-lean.cmd create mode 100644 agents/codex-lean/config.toml create mode 100644 agents/codex-lean/instructions-compact.md diff --git a/agents/codex-lean/README.md b/agents/codex-lean/README.md new file mode 100644 index 0000000..b050429 --- /dev/null +++ b/agents/codex-lean/README.md @@ -0,0 +1,23 @@ +# Lean Codex home (opt-in) + +Codex sends its whole start-up context with every request: plugins, MCP servers, the global `AGENTS.md` and skills. On a 32–40K local window that is expensive. Pointing `CODEX_HOME` at a separate, minimal home removes it. Your normal `%USERPROFILE%\.codex` stays untouched. + +**Measured on 17 October 2026** with llama-server `/metrics`, asking "Reply OK" in an empty project: + +| Setup | Start-up prompt | First turn | +|---|---:|---:| +| Normal `~/.codex` with the `qwen` profile | 12,235 tokens | 33 s cold | +| This home, stock Codex instructions | 7,150 tokens | — | +| This home with `instructions-compact.md` | **3,010 tokens** | 8 s cold, 1.6 s cached | + +**Not yet measured:** this setup has not been run on the [100-task eval](../../evalsuite/). The compact instructions replace Codex's stock system prompt, so quality could differ. To keep the stock prompt, comment out `model_instructions_file` in `config.toml` (about 4.9K tokens). + +## Install (Windows) + +1. Copy `config.toml` and `instructions-compact.md` to `C:\AI\codex-local\home\`. +2. Put `codex-qwen-lean.cmd` on your `PATH`. It sets `CODEX_HOME`, reads the live window from `qwen window` (the loaded context minus 8K), and compacts at 75% of it. +3. Make sure `LOCAL_QWEN_KEY` is set (the same key llama-swap uses). + +Codex writes six system skills into any new `CODEX_HOME`. `config.toml` switches them off. A short list of `~/.agents/skills` (about 700 tokens) is still injected, because Codex reads that directory from the user profile. + +Known protocol gaps between Codex and llama-server are listed in [docs/CODEX-COMPAT.md](../../docs/CODEX-COMPAT.md). diff --git a/agents/codex-lean/codex-qwen-lean.cmd b/agents/codex-lean/codex-qwen-lean.cmd new file mode 100644 index 0000000..03e2a86 --- /dev/null +++ b/agents/codex-lean/codex-qwen-lean.cmd @@ -0,0 +1,10 @@ +@echo off +rem codex-qwen-lean: Codex on the local Qwen with the lean CODEX_HOME (3K-token base prompt instead of 12K). +rem Window = live server ctx - 8K (qwen window), auto-compact at 75% of it. Nothing in %USERPROFILE%\.codex is touched. +setlocal +set "CODEX_HOME=C:\AI\codex-local\home" +for /f %%w in ('powershell -NoProfile -ExecutionPolicy Bypass -File C:\AI\governor\qwen.ps1 window') do set "WIN=%%w" +if not defined WIN set "WIN=24576" +set /a "COMPACT=WIN*3/4" +codex -c model_context_window=%WIN% -c model_auto_compact_token_limit=%COMPACT% %* +endlocal diff --git a/agents/codex-lean/config.toml b/agents/codex-lean/config.toml new file mode 100644 index 0000000..7c5136e --- /dev/null +++ b/agents/codex-lean/config.toml @@ -0,0 +1,78 @@ +# Lean Codex home for the local Qwen (Arc Pro B60). Deploy to C:\AI\codex-local\home and run Codex with +# CODEX_HOME=C:\AI\codex-local\home (see codex-qwen-lean.cmd). A separate CODEX_HOME is what removes the 26 plugins, +# 7 MCP servers, the 21 KB global AGENTS.md and the ~/.codex/skills tree from every request. +# MEASURED 2026-10-17 (llama-server /metrics, "Reply OK" in an empty project): +# ~/.codex + qwen-lean profile : 12,235 prompt tokens, 33 s wall (cold) +# this home, stock instructions: 7,150 (agents/goals tools off: ~4,900 est. from request bytes) +# this home, compact instructions: 3,010 prompt tokens, 1.6 s when cached <- VERIFIED +model = "qwen3.8-27b:code" # thinking off; the governor's default variant (f16 KV, Intel FA, DFlash2) +model_provider = "qwen-b60" +model_reasoning_effort = "low" +model_reasoning_summary = "none" +hide_agent_reasoning = true +model_verbosity = "low" + +approval_policy = "on-request" +sandbox_mode = "workspace-write" + +# Window: the governor sizes ctx per load (32768-65536, --no-context-shift => overflow is a hard 400). +# codex-qwen-lean.cmd overrides these two with the live value from `qwen window` (ctx - 8192) and 75% of it. +model_context_window = 32768 +model_auto_compact_token_limit = 24000 +tool_output_token_limit = 3000 + +web_search = "disabled" # llama.cpp drops web_search tools +project_doc_max_bytes = 8192 # AGENTS.md cap per file (default 32 KiB) + +# Replaces Codex's 17.3 KB stock system prompt (~4K tokens) with a 1.2 KB one. VERIFIED to take effect (request capture). +# Risk: untested on the eval suite; keep the stock prompt by commenting this line out (prompt then ~4.9K tokens). +model_instructions_file = 'C:\AI\codex-local\home\instructions-compact.md' +include_permissions_instructions = false +include_apps_instructions = false +include_collaboration_mode_instructions = false + +developer_instructions = "Local Qwen. Context is small: read only what you need, keep tool output short, valid JSON tool arguments, one step at a time." + +[agents] +enabled = false # removes the multi_agent_v1 namespace tool (10 KB of schema) - VERIFIED by capture + +[features] +memories = false +multi_agent = false # (INFERRED name; harmless if unknown) +collaboration_modes = false # (INFERRED name) +goals = false # goals tools disappeared together with [agents] enabled=false; name INFERRED +apply_patch_freeform = false + +[tools] +view_image = false # the schema still ships (371 bytes); harmless + +[model_providers.qwen-b60] +name = "Local Qwen on Arc B60" +base_url = "http://127.0.0.1:8090/v1" +env_key = "LOCAL_QWEN_KEY" +wire_api = "responses" +stream_idle_timeout_ms = 900000 +request_max_retries = 1 +stream_max_retries = 1 + +# Codex writes six system skills into any new CODEX_HOME; switch them off (each listing costs tokens). +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\imagegen\SKILL.md' +enabled = false +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\openai-docs\SKILL.md' +enabled = false +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\plugin-creator\SKILL.md' +enabled = false +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\review-agent\SKILL.md' +enabled = false +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\skill-creator\SKILL.md' +enabled = false +[[skills.config]] +path = 'C:\AI\codex-local\home\skills\.system\skill-installer\SKILL.md' +enabled = false +# Still injected: a truncated list of ~/.agents/skills (about 700 tokens). Codex reads that directory from the user +# profile, not CODEX_HOME; moving rarely used skills out of ~/.agents/skills is the only way to drop it. diff --git a/agents/codex-lean/instructions-compact.md b/agents/codex-lean/instructions-compact.md new file mode 100644 index 0000000..2acc4b6 --- /dev/null +++ b/agents/codex-lean/instructions-compact.md @@ -0,0 +1,12 @@ +You are Codex, a coding agent running on a local model with a small context window. Work in the user's repository through the tools you are given. + +Rules: +- Read only the files and lines you need. Keep every tool call's output short (head/tail, grep, line ranges). +- Make the smallest change that completes the task. Do not refactor unrelated code. Do not add dependencies without being asked. +- Edit files with `apply_patch` through the shell tool, in small hunks: {"cmd":"apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: path/to/file.py\n@@ def example():\n- pass\n+ return 123\n*** End Patch\nEOF"}. Never use applypatch or apply-patch. Do not re-read a file after a successful patch. +- Verify every change by running the relevant test, build or lint command and reading its output. Never claim something works without running it. +- For tasks of more than three steps, write a short numbered plan first and tick items off as you go. +- Facts come from files and tool output, never from memory. If unsure, say so and write [CONFIRM: ...]. +- Call tools with valid JSON arguments, one step at a time. Wait for the result before the next call. +- Final answer: plain text, concise, no reasoning text. State what changed, what was verified and what is left. +- If the same approach fails twice, stop and report what you tried, what failed and what you need. From 6dae392da681500b769e702e132789729ea5e40f Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:14:29 +1100 Subject: [PATCH 12/16] Review fixes: fail-closed slot gate, calib fingerprint, base variant tracked --- governor/README.md | 2 +- governor/governor.ps1 | 13 +++++++++---- governor/launch.ps1 | 5 ++++- governor/slotlib.ps1 | 4 +++- governor/test_ctx.ps1 | 5 +++++ 5 files changed, 22 insertions(+), 7 deletions(-) diff --git a/governor/README.md b/governor/README.md index 1f75be9..fec9a84 100644 --- a/governor/README.md +++ b/governor/README.md @@ -18,7 +18,7 @@ The governor keeps the local Qwen server sized to what the PC is doing. It picks ```powershell powershell -NoProfile -ExecutionPolicy Bypass -File governor\test_governor.ps1 # 111 passed, 0 failed -powershell -NoProfile -ExecutionPolicy Bypass -File governor\test_ctx.ps1 # 7/7 +powershell -NoProfile -ExecutionPolicy Bypass -File governor\test_ctx.ps1 # 11/11 python -m pytest governor -q # 53 passed ``` diff --git a/governor/governor.ps1 b/governor/governor.ps1 index b8b064c..603094e 100644 --- a/governor/governor.ps1 +++ b/governor/governor.ps1 @@ -20,8 +20,8 @@ $ErrorActionPreference = 'Continue' $dir = 'C:\AI\governor' $swap = 'http://127.0.0.1:8090' $model = 'qwen3.8-27b' # default variant (prewarm target) -$ids = @('qwen3.8-27b', 'qwen3.8-27b-turbo', 'qwen3.8-27b-long', 'qwen3.8-27b-big') # governed 27B variants -$ports = @{ 'qwen3.8-27b' = 10001; 'qwen3.8-27b-turbo' = 10003; 'qwen3.8-27b-long' = 10004; 'qwen3.8-27b-big' = 10005 } +$ids = @('qwen3.8-27b', 'qwen3.8-27b-turbo', 'qwen3.8-27b-long', 'qwen3.8-27b-big', 'qwen3.8-27b-base') # governed 27B variants +$ports = @{ 'qwen3.8-27b' = 10001; 'qwen3.8-27b-turbo' = 10003; 'qwen3.8-27b-long' = 10004; 'qwen3.8-27b-big' = 10005; 'qwen3.8-27b-base' = 10006 } $script:curId = $model; $script:curPort = 10001 $task = 'Local Qwen (llama-swap)' $script:vramTotalGib = 23.88 # Arc Pro B60 heap 0 (vulkaninfo); overridden by profiles.json vram.total_gib @@ -352,7 +352,12 @@ $script:baseline = $null; $script:baseStable = 0; $script:baseStarted = $null $script:refitPrevCtx = $null; $script:refitOthers = $null; $script:refitBlocked = $false function VariantOf($id) { return (Try1 { $cfg.variants.PSObject.Properties | ForEach-Object { $_.Value } | Where-Object { $_.id -eq $id } | Select-Object -First 1 } $null) } function CalibRead { $c = ReadJsonFile "$dir\calib.json"; if ($null -eq $c) { return [pscustomobject]@{} }; return $c } -function CalibEntry($id) { $c = CalibRead; $pr = $c.PSObject.Properties[$id]; if ($pr) { return $pr.Value }; return $null } +# A learned overhead is only valid for the model file and engine it was measured with: entries carry a fingerprint +# (model path | file size | engine exe) and are ignored when it differs or is missing (launch.ps1 applies the same rule). +function CalibFingerprint($vv) { $sz = ''; try { $sz = [string](Get-Item -LiteralPath ([string]$vv.model) -ErrorAction Stop).Length } catch {}; return ('{0}|{1}|{2}' -f [string]$vv.model, $sz, [string]$cfg.exe) } +function CalibEntry($id) { $c = CalibRead; $pr = $c.PSObject.Properties[$id]; if (-not $pr) { return $null } + $vv = VariantOf $id; if ($vv -and ([string]$pr.Value.fingerprint -ne (CalibFingerprint $vv))) { return $null } + return $pr.Value } function CalibWrite($id, $entry) { try { $c = CalibRead @@ -641,7 +646,7 @@ while ($true) { $prev = $null; $pe = CalibEntry $script:curId; if ($pe) { $prev = Try1 { [double]$pe.overhead_gib } $null } $cal = GovCalibrate $prev $s.vram_llama_gib $vv.base_gib $m.n_ctx $vv.kv_kib_per_token $alpha $maxO $n = 1; if ($pe) { $n = (Try1 { [int]$pe.samples } 0) + 1 } - CalibWrite $script:curId ([ordered]@{ overhead_gib = $cal.overhead; last_delta_gib = $cal.delta; predicted_gib = $cal.predicted; measured_gib = $s.vram_llama_gib; ctx = [int]$m.n_ctx; others_gib = $s.vram_others_gib; free_gib = $s.vram_free_gib; samples = $n; updated = $now.ToString('s') }) + CalibWrite $script:curId ([ordered]@{ fingerprint = (CalibFingerprint $vv); overhead_gib = $cal.overhead; last_delta_gib = $cal.delta; predicted_gib = $cal.predicted; measured_gib = $s.vram_llama_gib; ctx = [int]$m.n_ctx; others_gib = $s.vram_others_gib; free_gib = $s.vram_free_gib; samples = $n; updated = $now.ToString('s') }) } $calTxt = ''; if ($cal) { $calTxt = (' predicted={0} measured={1} delta={2:+0.00;-0.00} overhead->{3}' -f $cal.predicted, $s.vram_llama_gib, $cal.delta, $cal.overhead) } Log ("BASELINE ctx={0} others={1} free={2} llama={3}{4}" -f $m.n_ctx, $s.vram_others_gib, $s.vram_free_gib, $s.vram_llama_gib, $calTxt) diff --git a/governor/launch.ps1 b/governor/launch.ps1 index 3b33b8a..00fdd71 100644 --- a/governor/launch.ps1 +++ b/governor/launch.ps1 @@ -77,8 +77,11 @@ else { # learned footprint the base_gib/kv model misses (governor writes calib.json at each post-launch baseline); never negative $overhead = 0.0; $calEnabled = $true; try { if ($cfg.calibration.enabled -is [bool]) { $calEnabled = $cfg.calibration.enabled } } catch {} $maxOver = 1.5; try { if ($cfg.calibration.max_overhead_gib) { $maxOver = [double]$cfg.calibration.max_overhead_gib } } catch {} + # an entry only counts for the model file + engine it was learned with (same fingerprint rule as governor.ps1 CalibEntry) + $fpSize = ''; try { $fpSize = [string](Get-Item -LiteralPath ([string]$v.model) -ErrorAction Stop).Length } catch {} + $fp = '{0}|{1}|{2}' -f [string]$v.model, $fpSize, [string]$cfg.exe if ($calEnabled) { try { $cal = Get-Content "$dir\calib.json" -Raw -ErrorAction Stop | ConvertFrom-Json; $ce = $cal.PSObject.Properties[$v.id] - if ($ce -and ($null -ne $ce.Value.overhead_gib)) { $overhead = [math]::Round([math]::Max(0.0, [math]::Min($maxOver, [double]$ce.Value.overhead_gib)), 2) } } catch {} } + if ($ce -and ($null -ne $ce.Value.overhead_gib) -and ([string]$ce.Value.fingerprint -eq $fp)) { $overhead = [math]::Round([math]::Max(0.0, [math]::Min($maxOver, [double]$ce.Value.overhead_gib)), 2) } } catch {} } $targetGiB = $cfg.vram.total_gib - $p.free_margin_gib - $others $kib = ($targetGiB - $v.base_gib - $overhead) * 1MB # GiB->KiB = *1MB $ctx = 0; if ($kib -gt 0) { $ctx = [int]([math]::Floor($kib / $kvKiB / 4096) * 4096) } diff --git a/governor/slotlib.ps1 b/governor/slotlib.ps1 index 03a4e22..5a2d8c5 100644 --- a/governor/slotlib.ps1 +++ b/governor/slotlib.ps1 @@ -358,7 +358,9 @@ function SlotSave($s, $id, $port, $modelPath, $ctx, $variant = $null) { SlotLog "SAVE $($meta.n_tokens) tokens, $gib GiB in $ms ms ($id)" } # a request may have arrived during the (multi-second) save: re-read the slot before letting the caller unload - $g2 = SlotUnloadGate (SlotGetSlot $base) + $slot2 = SlotGetSlot $base + if ($null -eq $slot2) { SlotLog 'unload postponed: /slots unreadable after the slot save (state unknown, failing closed)'; return $false } + $g2 = SlotUnloadGate $slot2 if (-not $g2.ok) { SlotLog "unload postponed: a request started during the slot save ($($g2.reason))"; return $false } return $true } catch { diff --git a/governor/test_ctx.ps1 b/governor/test_ctx.ps1 index 0d2deeb..80dbb27 100644 --- a/governor/test_ctx.ps1 +++ b/governor/test_ctx.ps1 @@ -8,6 +8,11 @@ Check 'launch.ps1 waits only for OurServers' (($l -match 'function OurServers') Check 'BALANCED margin 2.5 (18 Oct shared-memory finding)' ($p.profiles.BALANCED.free_margin_gib -eq 2.5) Check 'default variant keeps f16 KV' ($p.variants.default.ctk -eq 'f16' -and $p.variants.default.ctv -eq 'f16') Check 'default keeps drafter + -ub 256' ((($p.variants.default.extra_args) -join ' ') -match 'draft-dflash.*-ub 256') +Check 'launch.ps1 only uses calib entries with a matching model/engine fingerprint' ($l -match 'fingerprint -eq \$fp') +Check 'governor writes and checks the calib fingerprint' (($g -match 'fingerprint = \(CalibFingerprint') -and ($g -match 'function CalibFingerprint')) +Check 'base variant is governed (ids + port 10006)' (($g -match "'qwen3.8-27b-base'") -and ($g -match "'qwen3.8-27b-base' = 10006")) +$sl = Get-Content "$Dir\slotlib.ps1" -Raw +Check 'slot save fails closed when /slots is unreadable after the save' ($sl -match 'failing closed') # behavioural: ProcIds must drop a llama-server.exe outside C:\AI\llama.cpp (simulate with a fake Get-Process) $ast = [System.Management.Automation.Language.Parser]::ParseInput($g, [ref]$null, [ref]$null) $fn = $ast.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'ProcIds' }, $true) From 719b744e4e5e4f8110be615f51e38cf01f380ebe Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:14:59 +1100 Subject: [PATCH 13/16] llama-swap: register qwen3.8-27b-base --- llama-swap/config.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/llama-swap/config.yaml b/llama-swap/config.yaml index 878189b..3806b89 100644 --- a/llama-swap/config.yaml +++ b/llama-swap/config.yaml @@ -72,6 +72,13 @@ models: ttl: 3600 aliases: ["qwen-long", "long"] + "qwen3.8-27b-base": + name: "Qwen3.8 27B BASE - the original UD-Q4_K_M quant (pre-ThinkingCap default), DFlash2, vision; kept for A/B comparison" + cmd: powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:/AI/governor/launch.ps1 -Variant base + proxy: http://127.0.0.1:10006 + ttl: 3600 + aliases: ["qwen-base", "base"] + "qwen3.6-35b-a3b": name: "Qwen3.6 35B-A3B fast (text only, 128k ctx)" cmd: >- From eece5ac20e8e72aea2e9b6182de853638c33d89a Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:15:26 +1100 Subject: [PATCH 14/16] Lean Codex wrapper: per-user TEMP/TMP for the sandbox --- agents/codex-lean/codex-qwen-lean.cmd | 3 +++ 1 file changed, 3 insertions(+) diff --git a/agents/codex-lean/codex-qwen-lean.cmd b/agents/codex-lean/codex-qwen-lean.cmd index 03e2a86..7befdf4 100644 --- a/agents/codex-lean/codex-qwen-lean.cmd +++ b/agents/codex-lean/codex-qwen-lean.cmd @@ -2,6 +2,9 @@ rem codex-qwen-lean: Codex on the local Qwen with the lean CODEX_HOME (3K-token base prompt instead of 12K). rem Window = live server ctx - 8K (qwen window), auto-compact at 75% of it. Nothing in %USERPROFILE%\.codex is touched. setlocal +rem Codex Windows sandbox cannot grant itself access to C:\Temp (admin-owned) - use the per-user temp folder +set "TEMP=%LOCALAPPDATA%\Temp" +set "TMP=%LOCALAPPDATA%\Temp" set "CODEX_HOME=C:\AI\codex-local\home" for /f %%w in ('powershell -NoProfile -ExecutionPolicy Bypass -File C:\AI\governor\qwen.ps1 window') do set "WIN=%%w" if not defined WIN set "WIN=24576" From 175e3ee11c3d4efbde01b7169cbeda92779d1dff Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:15:54 +1100 Subject: [PATCH 15/16] Field report: updated test counts --- docs/FIELD-REPORT-20261018.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/FIELD-REPORT-20261018.md b/docs/FIELD-REPORT-20261018.md index 2fe4108..8113f3b 100644 --- a/docs/FIELD-REPORT-20261018.md +++ b/docs/FIELD-REPORT-20261018.md @@ -69,7 +69,7 @@ The only honest route to a smaller KV cache is engine work, not a flag: a valid ## 4. What changed in this repo -- [governor/](../governor/) is now **v4.3**. It has null-safe sensing, pressure hysteresis, no unload while a request is in flight, KV slot save/restore, power-plan hysteresis, footprint calibration, and a process-path filter so Ollama's bundled `llama-server.exe` is never counted as the model. Tests: `test_governor.ps1` 111/0, pytest 53/0, `test_ctx.ps1` 7/7. +- [governor/](../governor/) is now **v4.3**. It has null-safe sensing, pressure hysteresis, no unload while a request is in flight, KV slot save/restore, power-plan hysteresis, footprint calibration, and a process-path filter so Ollama's bundled `llama-server.exe` is never counted as the model. Tests: `test_governor.ps1` 111/0, pytest 53/0, `test_ctx.ps1` 11/11. - `governor/profiles.json`: the MAX and BALANCED `free_margin_gib` is **2.5** (was 1.35), and `auto.others_vram_max_gib` is 2.5. - [agents/codex-lean/](../agents/codex-lean/README.md): an opt-in Codex home that cuts Codex's start-up prompt from 12,235 to 3,010 tokens (measured). The first cold turn went from 33 s to 8 s. - [CODEX-COMPAT.md](CODEX-COMPAT.md): which OpenAI request features this llama-server honours, ignores or drops, from 22 request shapes against the live server. From a81076cf9e57a1b99188ac493654405296495c14 Mon Sep 17 00:00:00 2001 From: ELIE DAGHER Date: Sun, 18 Oct 2026 03:16:23 +1100 Subject: [PATCH 16/16] Changelog: review fixes --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80b7879..e3acc55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ Imported selectively from three maintainer hand-off archives (Claude and Codex s **Governor** - v3 → **v4.3** ([governor/README.md](governor/README.md)): null-safe sensing, pressure hysteresis, never unloads mid-request, KV slot save/restore (`slotlib.ps1`), power-plan hysteresis, footprint calibration, and Ollama's bundled `llama-server.exe` is no longer counted as the model. Fixes the published v3 loop crash (`needLog` uninitialised) when the governor starts with no model loaded. - `profiles.json`: MAX/BALANCED `free_margin_gib` 1.35 → 2.5 and `auto.others_vram_max_gib` 2.5. ThinkingCap is the default variant, with `--spec-draft-p-min 0.5` and `--slot-save-path`. -- Tests: `test_governor.ps1` 111/0, `test_ctx.ps1` 7/7 (its function extraction now uses the PowerShell AST), and pytest `govpolicy`/`slotpolicy` 53/0. +- Review fixes (Codex review on PR #5): a slot save now fails closed when `/slots` is unreadable afterwards; calibration entries carry a model-file + engine fingerprint and are ignored when it changes; the preserved `qwen3.8-27b-base` variant is registered in `llama-swap/config.yaml` and tracked by the governor; the lean Codex wrapper redirects `TEMP`/`TMP` like `codex-qwen.cmd`. +- Tests: `test_governor.ps1` 111/0, `test_ctx.ps1` 11/11 (its function extraction now uses the PowerShell AST), and pytest `govpolicy`/`slotpolicy` 53/0. **Agents and docs** - [agents/codex-lean/](agents/codex-lean/README.md): an opt-in `CODEX_HOME` that cuts Codex's start-up prompt from 12,235 to 3,010 tokens (measured). Not yet run on the 100-task eval.