From 92fe769a0a7877b20e84f3cadb376c9fff1f8225 Mon Sep 17 00:00:00 2001 From: Lumpiasty Date: Mon, 23 Nov 2026 13:53:59 +0100 Subject: [PATCH] docs: FORK.md, runbook and AGENTS.md pointer for the slimmed branch (F1, F3, F15, #32777 carry and the bench harness removed) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PZz44SLQvTXMyWGio6t9DZ --- AGENTS.md | 2 + FORK.md | 1900 +++++++++++++++++++++++++++++++++++ docs/fork-rebase-runbook.md | 867 ++++++++++++++++ 3 files changed, 2769 insertions(+) create mode 100644 FORK.md create mode 100644 docs/fork-rebase-runbook.md diff --git a/AGENTS.md b/AGENTS.md index 36390a6b4..d2bab997e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # Instructions for llama.cpp +> **Private fork: read [FORK.md](FORK.md) and [docs/fork-rebase-runbook.md](docs/fork-rebase-runbook.md) before any work.** + > [!IMPORTANT] > > AI-generated code is allowed. What is **not** allowed is submitting code you do not understand. You are 100% responsible for every line, however it was produced. diff --git a/FORK.md b/FORK.md new file mode 100644 index 000000000..1d0e6f5f3 --- /dev/null +++ b/FORK.md @@ -0,0 +1,1900 @@ +# FORK.md - the RX 580 llama.cpp fork + +Maintainer documentation for this private fork. Read it before you rebase, change, or deploy +anything. The rebase and deploy procedure is in [docs/fork-rebase-runbook.md](docs/fork-rebase-runbook.md), +which also holds the operations reference (pod access, files, recovery). + +Status at the time of writing (2026-11-23, after the slimming run): + +- Production runs branch `fable5/vram-ondemand-rebase-20261123` on upstream `5bacb7c86`: 10 code + and script commits, one per feature (section 2), plus the documentation commits. It was rebuilt + on 2026-11-23 from the previous production branch by dropping the features without a measured + benefit (F1 routing-ids readback skip, F3 concat fast path and one-tile gate, F15 AVX2 NVFP4 + kernel, the #32777 `--fit` carry, the `scripts/rx580-bench` harness; section 2, "Removed on + 2026-11-23") and squashing the 74 earlier commits. Deployed commit, + validation and measurements: section 2, "Audit". `system_fingerprint` is `b-` and changes with each rebase or carry. +- Rollback: pointer `/root/DEPLOY-ROLLBACK-commit-18.txt` = `ec3bf13f6`, the previous production + commit (branch `fable5/vram-ondemand-rebase-20261122`, kept untouched; build copy + `/root/arms/build-ec3bf13f6`, config unchanged by this deploy). Next free pointer 19. Older + pointers and their config backups: runbook section 9. +- Older branches kept as safety nets: `fable5/vram-ondemand-rebase-20261122` (production + 2026-11-23 01:47 to the slimming deploy), `-20261121` (upstream `e6d624b9a`), `-20261024` + (upstream `3f03b1772`). Their commit hashes appear in the squashed commit messages ("was + "), so `git show ` still finds an original commit and its measurements. +- The fork commits are `git log --oneline 5bacb7c86..HEAD` (count them rather than trusting a + number written here). The commit messages are detailed and are the primary record of each + mechanism and measurement; read them with `git show`. Hashes change on every rebase; find a + commit again by its subject line, which ends with the feature tag `(Fn)`. +- Production environment since 2026-11-23: Mesa 26.3.1 with the RADV transfer queue (section 5); + standalone tools need its three variables exported to match production. +- Commit trailers (owner's convention): this fork is private and never contributes upstream. + Agent-written commits end with `Co-Authored-By: Claude ` (some + older ones say `Assisted-by: Claude`). AGENTS.md asks agents for `Assisted-by:` instead of + `Co-authored-by:` and forbids AI-written commit messages and PR descriptions; those are upstream + llama.cpp's contribution rules and do not apply to commits that stay in this fork. Anything meant + for upstream must be written by the owner under those rules. + +## Contents + +1. Purpose and target +2. Commit map, removed features and the 2026-11-23 audit +3. Features + - F1 MoE routing-ids readback skip (removed 2026-11-23) + - F2 GCN flash-attention mask_opt gate (and the shmem-staging note) + - F3 Vulkan concat fast path and one-tile gate (removed 2026-11-23) + - F4 On-demand device residency (library side) + - F5 On-demand mmproj (multimodal encoder) + - F6 Cross-process VRAM arbiter (server side) + - F7 Server shutdown path + - F8 Cold-teardown guards + - F9 Validation script (the benchmark harness was removed on 2026-11-23) + - F10 Page-cache drop after a copying load + - F11 Disk prompt cache (save slots on shutdown, restore after a restart) + - F12 Temporary upstream carries (open upstream PRs, drop when merged) + - F13 Per-pass views of host weights in looped layers (inkling2_loop) + - F14 User-message batch-break merge (one ubatch per short turn) +4. Dead ends +5. Configuration that matters +6. Measurement methodology and traps +7. Known gaps and open risks + +--- + +## 1. Purpose and target + +The fork exists to serve large MoE models well on one specific machine: + +- **GPU:** AMD RX 580 8 GB (Polaris, GCN gfx803), RADV Vulkan driver. llama.cpp reports + `fp16: 0` (RADV does not expose `shaderFloat16` on GFX8), no int-dot, no matrix cores, wave64. + PCIe 3.0 x16. The system Mesa 25.0.7 RADV exposes no transfer-only queue family on this card; + Mesa 26.3.1 (built in `/opt/mesa-26.3.1`) with `RADV_EXPERIMENTAL=transfer_queue` exposes two (the + SDMA engines), and production uses that since 2026-11-23 (section 5). +- **Host:** Ryzen 5 3600 (6c/12t), 62 GB RAM, a Talos Kubernetes node shared with about 60 other pods + (CPU contention matters for decode numbers, see section 6). The GPU runs at a fixed 120 W power cap. +- **Primary model:** Qwen3.6-35B-A3B (unsloth UD-Q4_K_XL, 20.8 GiB), a hybrid MoE: 40 layers, 30 of + them gated delta-net (recurrent), 10 full attention, head_dim 256, 256 experts with 8 used. All + experts live in host RAM (`--n-cpu-moe 40`); only the backbone, KV, recurrent state and compute + buffers sit in VRAM. +- **Serving:** llama-swap under supervisord keeps several llama-server processes loaded at once + (the 35B main models, a Qwen3.5-4B "task" model OpenWebUI calls for titles and tags, gemma-4-26B + multimodal, others). They cannot all fit in 8 GB, so they time-share the GPU through the fork's + VRAM arbiter (F4-F7) without restarting processes, which would throw away the RAM-only prompt cache. +- **Priority:** prefill (prompt processing) speed first, decode second. Agentic use pushes large tool + results through the model, so long-context prefill is what users wait on. + +What the fork adds, in short: + +- one Polaris prefill change (F2, flash-attention mask_opt at head size 256), exact; F1 and F3, + the other two speed features, were removed on 2026-11-23 (section 2); +- on-demand release/restore of everything a model holds in VRAM, plus a cross-process arbiter that + hands the GPU from one llama-server to another in well under a second for small models (F4-F8); +- a disk prompt cache (F11), a page-cache drop after a copying load (F10), a prompt-batch change + for short turns (F14), and Inkling-2-Mini support pieces (F12 carry, F13); +- a post-rebase validation script (F9). + +## 2. Commit map, removed features and the 2026-11-23 audit + +One commit per feature, oldest first, on upstream `5bacb7c86` (branch +`fable5/vram-ondemand-rebase-20261123`). The squashed commits keep every original commit message +below a `---- (was )` line. The VRAM time-sharing commits of the old history +mixed library and server hunks; they are split by path here (library, mtmd, server), so each of the +three commits builds on the previous one. + +| commit | subject | feature | files, +/- lines | +|---|---|---|---| +| f9e7af6e7 | ggml-vulkan: enable flash-attn mask_opt for GCN head size 256, note why shmem staging stays off | F2 | 1, +7 -1 | +| 7065a3430 | llama, ggml: release and restore everything a context holds in VRAM on demand | F4, F8 | 21, +667 -18 | +| 08a1743c5 | mtmd: release/restore the encoder weights from VRAM on demand | F5 | 4, +106 | +| fed49aea5 | server: cross-process VRAM arbiter, sleep/wake, on-demand mmproj and shutdown paths | F5, F6, F7 | 4, +497 -18 | +| 4085868a0 | llama: drop the model file's page cache after a copying load | F10 | 4, +40 | +| 46c6b03a4 | server: disk prompt cache, save slots on shutdown and restore after a restart | F11 | 18, +760 -15 | +| ea2f53728 | upstream-carry #32740: ggml: compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan | F12 | 32, +505 -145 | +| 3f9b79b45 | llama: inkling2_loop - per-pass views of host weights for the later loop passes | F13 | 5, +120 -1 | +| 25d6e1e9b | server: merge user-message batch breaks when the rest of the prompt fits in one ubatch, keep the first-user-message break | F14 | 1, +35 -1 | +| a1eb757ea | scripts: fork-validate.sh, post-rebase validation of the fork | F9 | 1, +1034 | + +Then the documentation commits (FORK.md, the runbook, the AGENTS.md pointer). The README's fork +section was removed on 2026-11-23 (README.md changes upstream all the time, so it was a conflict at +every rebase for no code; this file and AGENTS.md carry the pointer). Commit map of the previous +production branch (74 commits): `git log --oneline 5bacb7c86..fable5/vram-ondemand-rebase-20261122`. + +### Removed on 2026-11-23 + +Dropped because their measured benefit was noise or negative on today's base. Each one is a short +row in section 4 (dead ends), so it is not retried without a new reason. + +- **F15, AVX2 NVFP4 x Q8_0 dot product** (`af815458c` on `-20261122`; branch `fable5/nvfp4-avx2` + keeps it). The kernel was 1.13x faster per row in isolation, but Inkling's decode is DRAM-bound + at 6 threads: production command line, B N N B, decode 6.34 -> 6.39 t/s (+0.8%, noise; window of + 2026-11-23). 102 lines in an upstream hot file (`ggml-cpu/arch/x86/quants.c`) for nothing + measurable. +- **F3's own concat tiled-transpose fast path** (`ggml_vk_concat_transpose_fastpath`, about 110 + lines, `3df719e1e` / `5e429d4a9` / `e085c347d` on the old branches). Upstream #30591 added its own + tiled concat (`concat_transpose.comp`); with a scratch knob that skipped only the fork's path, + Qwen 35B pp2048 was 292.3 t/s with upstream's path alone against 286.2 with the fork's, 254.9 with + neither, and pp2048 @ d16384 208.9 against 207.7 (window of 2026-11-23). +- **F3's one-tile gate on upstream's tiled concat** and its `GGML_VK_CONCAT_FASTPATH` knob + (`cf2790794` on `-20261122`, 22 lines in `ggml-vulkan.cpp`) with `fork-validate.sh --concat`. + Gate off against on, tg256 @ d4096: Qwen 35B 16.57 -> 17.48 t/s (+5.5%); Qwen3.5-4B 43.15 -> 42.99 (-0.4%, noise); Inkling: the concat kernels cost about 0.3 ms + more per token without the gate (0.2% of a token at 6.5 t/s, perf logger), decode tg256 @ d4096 median 6.40 -> 6.58 t/s (+2.8%, noise; 9 samples each). + Section 3, F3. +- **F1, routing-ids readback skip** (`2ca30e5f3`, knob `67007a7be` on `-20261122`, 44 lines in + `llama-context.cpp`) with `fork-validate.sh --moe-exact`. Off against on: Qwen 35B pp2048 +4.5%, + pp2048 @ d16384 +3.9%, Inkling pp2048 @ d8192 +4.7% (faster without it). Section 3, F1. +- **#32777 carry, loop-aware `--fit`** (`6c895a491` on `-20261122`). Measured against the manual + k=4 `-ot` placement for Inkling: fit kept about 2.3 loop layers on the GPU instead of 4, prefill + -3%, decode -12% (F12 window result of 2026-11-23, kept below in F12); production never used it. + The `--fit-target` of the small models is upstream's own fit and was not affected. +- **The `scripts/rx580-bench/` benchmark harness** (F9, 6 files, about 940 lines; owner decision). + Not a code feature: unused since 2026-09-09, superseded by `fork-validate.sh --perf` and + llama-bench window scripts. Its methodology is in the runbook, section 11; its code stays on + `-20261122` and older branches. + +### Audit (2026-11-23) + +Every remaining feature and knob: is there a current measurement that it helps on today's base, is +production using it, how big is it, and what it costs at a rebase. "Conflict risk" is the chance an +upstream change in the same lines breaks the pick: high where upstream reworks the area often. + +| feature | benefit on today's base (measurement, date) | production use | size (files, +/-) | conflict risk | decision | +|---|---|---|---|---|---| +| F1 routing-ids readback skip | negative: off is faster, Qwen 35B pp2048 308.8 -> 322.6 (+4.5%), d16384 221.7 -> 230.4 (+3.9%), Inkling pp2048 d8192 110.6 -> 115.8 (+4.7%) (`LLAMA_MOE_IDS_SKIP=0` A/B, one window, 2026-11-23) | was default on | 1, +34 -10 | medium | removed on 2026-11-23 | +| F2 GCN mask_opt at head size 256 | Qwen 35B pp2048 d16384 204.4 -> 221.7 (+8.5%), d0 306.3 -> 308.8 (+0.8%) (ablation build with F2 reverted, C X X C, 2026-11-23) | yes: the 35B (head size 256) | 1, +7 -1 | medium: the same line as #32740's `!bias` (F12) | keep | +| F3 one-tile gate on upstream's tiled concat | negative: gate off is faster at decode, Qwen 35B tg256 d4096 16.57 -> 17.48 (+5.5%); Qwen3.5-4B -0.4% (noise); Inkling concat +0.3 ms per token (0.2%), decode +2.8% (noise) (2026-11-23) | was on for every delta-net / short-conv model | 1, +21 -1 | low | removed on 2026-11-23 | +| F4, F8 device release/restore, teardown guards | the arbiter's precondition: a cold 4B holds 724 MB instead of 3327 MB, a cold gemma-26B 51 MB; the RAM prompt cache survives a task-model call (21.9 s re-prefill -> 225 ms) | yes: `LLAMA_SLEEP_VRAM_ONLY`, `LLAMA_SLEEP_EVICT_KV` | 21, +667 -18 | high: model load paths, every memory type, the MoE cache | keep | +| F5 on-demand mmproj | the encoder (about 0.6-0.8 GiB) is in VRAM only while it encodes | yes: `LLAMA_MMPROJ_ONDEMAND=1` | 4 + part of the server commit, +106 | medium: the mtmd refactors (#31865) | keep | +| F6, F7 arbiter, sleep/wake, shutdown | several models share the card without restarts; handoff median 635.5 ms on the slimmed build, the same as production (`a-handoff-latency`, 2026-11-23); the shutdown fixes are past production incidents | yes | 4, +497 -18 | high: `server-context.cpp`, `server-queue.cpp` | keep | +| F10 page-cache drop | node page cache stays at 4.2-5.3 GB after a 35B load instead of growing by about 20 GB (2026-10-25; the pod was OOM-killed under that pressure before) | yes: every `-lm none` load | 4, +40 | low | keep | +| F11 disk prompt cache | an 18.8K-token chat after a restart: turn 2 in 4.7 s instead of an 84.6 s re-prefill (2026-11-21) | yes: `--cache-disk-path` on the 35B, gemma and Inkling macros | 18, +760 -15 | high: `server-slot-sched`, `server-context` | keep | +| F12 carry of #32740 | Inkling at ctx 65536: compute buffer 7 GiB instead of 15.8 GiB, prefill 32.7 -> 46.8 t/s (2026-11-22) | yes: Inkling | 32, +505 -145 | high once upstream merges the GGML contract (F12) | keep while Inkling is served; owner decision on the split PR pending (F12) | +| F13 per-pass host-weight views | Inkling 13.9K-token prefill 96.6 t/s against 45.8 with upstream's #32807 alone (2026-11-23); `LLAMA_LOOP_FULL_COPY=0` +76% in 32-63-token ubatches | yes: Inkling, with `LLAMA_LOOP_FULL_COPY=0` | 5, +120 -1 | medium: `inkling2-loop.cpp`, `load_tensors` returns | keep | +| F14 user-message batch-break merge | 35B TTFT -2.1 to -3.7 s on turns of 10-150 tokens (2026-11-22); refinement items 5-7 passed (2026-11-23) | yes: default on | 1, +35 -1 | high: upstream reworks the `update_slots` batch loop often | keep | +| F9 `fork-validate.sh` | validated every deploy since 2026-10-25 | validation only | 1 script | none (own files) | keep | +| F9 `scripts/rx580-bench/` harness | last run 2026-09-09 (`/root/bench/results.txt`); superseded by `fork-validate.sh --perf` and ad-hoc llama-bench scripts | no | 6 files, about 940 lines | none (own directory) | removed on 2026-11-23 (owner decision); its methodology moved to the runbook, section 11 | +| README.md fork section | none (a pointer, now in AGENTS.md and this file) | - | +26 in an upstream file | a conflict at almost every rebase | removed on 2026-11-23 | + +Knobs (all read once from the environment): + +| knob | production | what it is for | decision | +|---|---|---|---| +| `LLAMA_SLEEP_VRAM_ONLY`, `LLAMA_SLEEP_EVICT_KV`, `LLAMA_MMPROJ_ONDEMAND`, `LLAMA_VRAM_ARENA` | all set (supervisord) | turn F4-F6 on | keep as opt-in: unset, a fork build behaves like upstream, which keeps `test-backend-ops`, llama-bench and the small tools upstream-identical | +| `LLAMA_LOOP_FULL_COPY=0` | set on both Inkling entries | skip upstream's #32807 guard, which F13 makes redundant | keep as an env knob, not a default: skipping the guard is only correct with the views on (`LLAMA_LOOP_HOST_VIEWS` unset), and the default keeps upstream's behaviour | +| `LLAMA_LOOP_HOST_VIEWS=0` | unset | upstream's shared tensors (A/B, LoRA on Inkling) | keep (one `getenv`, needed for the F13 A/Bs) | +| `LLAMA_USERSTART_MERGE=0` | unset | upstream's batch breaks (for a RAG client) | keep | +| `GGML_CUDA_REGISTER_HOST` | not in the environment any more | the pinning era | gone; section 5 no longer mentions it | + +--- + +## 3. Features + +Every feature section uses the same headings: What and why; Where; How it works; Invariants that +must hold; Failure modes and incidents; Rebase hazards; Validation. + +### F1. MoE routing-ids readback skip (removed on 2026-11-23) + +Removed: switching it off was faster, not slower, on today's base. When a ubatch's routing ids +reached `4 * n_expert` entries (128 tokens on the 35B, 64 on Inkling), `llama_context::sched_copy_experts` +skipped the ids readback and its pipeline flush and uploaded every expert of the layer. Measured +2026-11-23 (Mesa 26.3.1 + transfer queue, one window, `LLAMA_MOE_IDS_SKIP=0` against the default, +arms C X K K X C / P C K K C P): Qwen 35B pp2048 308.8 -> 322.6 t/s (+4.5%), pp2048 @ d16384 221.7 +-> 230.4 (+3.9%); Inkling pp2048 @ d8192 110.6 -> 115.8 (+4.7%). Decode never reached the threshold. +Mechanism not measured: the skip saved a pipeline flush per layer, which seems not to cost much +any more, while it uploaded every expert where the readback path uploads only the selected ones. Exactness was never the problem +(`fork-validate.sh --moe-exact`, 39 skips, identical output, last run 2026-11-23). The code is in +`2ca30e5f3` and `67007a7be` (knob) on `-20261122`; +dead-end row in section 4. With it gone, Inkling ubatches of 64+ tokens take the readback path too, +which F13's per-pass views keep correct (the same path the 32-63-token window always took). + +### F2. GCN flash-attention mask_opt gate (and the shmem-staging note) + +**What and why.** `mask_opt` skips fully-masked causal blocks and drops the per-block mask load+add +on fully-visible blocks. Upstream disables it on AMD GCN for head sizes <= 256. On Polaris attention +at depth is compute-bound on the softmax path (exp runs at about 1/4 VALU rate, no matrix cores), so +skipping that work is a real win. Measured on Qwen3.5-35B-A3B (head_dim 256): pp2048 +1% at depth 0, ++7.8% at 16k (176 -> 190), +12.3% at 32k (136 -> 153), growing with depth. Perplexity bit-identical +(5.1668 on and off). + +**Where.** `ggml/src/ggml-vulkan/ggml-vulkan.cpp`, `ggml_vk_flash_attn`, the `use_mask_opt` +condition. Commit fb6a8a076. The shmem-staging note is a comment in `get_fa_tuning_params_scalar` +(commit ff2a96d2d, no behaviour change). + +**How it works.** The GCN clause `HSK > 256 || HSV > 256` becomes `HSK >= 256 || HSV >= 256`. The +existing large-mask conditions (`nem1 >= 32`, `nem0 * nem1 > 32768`, +`nem0 >= block_cols * 16`) keep it off for decode. + +**Invariants that must hold.** +- Only GCN with head size >= 256 is affected. Do not lower the threshold: relaxing it below 256 was + -18.5% at 16k on Laguna (head_dim 128). +- Upstream's `!use_sparse` term must stay in the condition (sparse flash-attention came in with + upstream `fc82583e6`). +- `shmem_staging` stays NVIDIA-only. Measured on GCN at head size 128: -6.7% at 16k, -7.4% at 32k. + The `kvsh` stride of `D/4+1` dwords is 4 mod 32, an 8-way LDS bank conflict on wave64 (the `+1` + padding is tuned for warp32), and the extra shared memory cuts occupancy. If anyone retries it, + fix the padding to +2/+3 first. + +**Failure modes and incidents.** A `-X theirs` resolution in a trial rebase silently dropped +`!use_sparse` from the condition. No production incident. + +**Rebase hazards.** Any upstream rewrite of `use_mask_opt`, of the FA tuning parameters, or of +architecture detection (`vk_device_architecture::AMD_GCN`). Upstream `733f57a99` added a path that +copies strided f16/bf16 K/V into `prealloc_x` scratch for flash-attention on AMD non-RDNA4 (so GCN +is included) when `neq1 >= 256`; measured at d32768 it adds about 68 MiB of VRAM and no visible +long-context prefill loss, but it has no env toggle, so its speed effect could not be isolated. + +**Validation.** `fork-validate.sh --ops` (FLASH_ATTN_EXT, 5332 cases on Vulkan0) and `--perf` +(pp2048 at depth 16k and 32k is where this feature shows). + +### F3. Vulkan concat one-tile gate (removed on 2026-11-23) + +Removed with its `GGML_VK_CONCAT_FASTPATH` knob and `fork-validate.sh --concat`: upstream's tiled +concat (#30591, `concat_transpose.comp`, selected by `ggml_vk_concat_is_transposed`) is now faster +than the generic kernel at decode too. The fork first had its own tiled-transpose fast path +(2026-09; dropped on 2026-11-23, section 2, "Removed on 2026-11-23") and then a gate that kept +concats below one 32x32 tile (`src1->ne[0] < 32`: decode and small drafts on delta-net / short-conv +models) on the generic kernel, because a tiled concat at decode once cost -17% tg256 on the 35B (the +fork's old two-dispatch path with a barrier, 30 times per token). Measured 2026-11-23 with +upstream's one-dispatch path, gate off against on (llama-bench tg256 @ d4096, arms C X X C, X = +gate off and F2 reverted, F2 being off at decode anyway): Qwen 35B 16.57 -> 17.48 t/s (+5.5%). +The other delta-net / short-conv models in production, gate (candidate C) against no gate (S), same +window and driver: Qwen3.5-4B tg256 @ d4096 43.11, 43.19 t/s (C) against 42.95, 43.03 (S), arms C S +S C, -0.4%. Inkling-2-Mini (production `-ot` placement, `LLAMA_LOOP_FULL_COPY=0`): with +`GGML_VK_PERF_LOGGER` over tg32 both builds run 18084 CONCAT nodes, 82.6 us per graph with the +gate (generic kernel, 5.6 us per node) and 90.5 us without (tiled, 6.1 us per node), about 0.3 ms +more per token, 0.2% of a 154 ms token; llama-bench tg256 @ d4096, arms S C C S S C with 3 samples each: median 6.40 t/s with the gate, 6.58 without (+2.8%, inside the noise; samples 5.8-7.8). Prefill is not affected (ubatches >= 32 take the tiled path either way). +What remains worth knowing: delta-net layers (`build_conv_state`) and Inkling's short conv concat +the conv state with a transposed source; if upstream ever adds a `ggml_cont` there, the tiled path +stops being selected and prefill loses about 13% (254.9 vs 292.3 at pp2048, measured 2026-11-23), +which only a perf A/B shows now. The code is `cf2790794` on `-20261122` (gate and knob); +dead-end row in section 4. + +### F4. On-demand device residency (library side) + +**What and why.** Several always-loaded models must share 8 GB. Co-residence is impossible (the 35B +at `--n-cpu-moe 40` uses most of the card; the 4B task model needs about 2.5-3.3 GB). Restarting a +process to free VRAM throws away the RAM-only prompt cache: on Laguna a repeat turn went from a +21,960 ms re-prefill to 225 ms once the process stayed alive across a task-model call. So a model +must be able to drop everything it holds in VRAM and get it back without a reload. + +Measured footprints: +- 4B: warm 3327 MB, weights released 724 MB, restored and correct. +- 4B at 32k ctx: cold weights-only 1750 MB (KV stays), cold with KV evicted 726 MB. +- gemma-26B: warm 7147 MB, cold with weights+KV but scheduler kept 718 MB, cold with the scheduler + freed too 51 MB. +- A cold 4B before the encoder work held 644 MB that turned out to be its mmproj (F5). +- Re-warm cost: about 0.6 s per cold-to-warm switch weights-only (tiny prompt: 1.98 s cold vs 1.40 s + warm); 2-3 s with KV eviction (it adds the KV D2H/H2D and a scheduler reserve). + +**Where.** +- `src/llama-model.cpp`/`.h`: `llama_model::release_device_weights(keep_shadow)`, + `restore_device_weights()`, `weights_resident()`; per-buffer metadata + `llama_model::impl::weight_release` (`weight_release_slot`), filled in `load_tensors` and + `load_tensors_hadamard`. +- `src/llama-memory.h`: `llama_memory_i::release_device_buffers(keep_shadow)` / + `restore_device_buffers()` (default no-op). Implemented in `src/llama-kv-cache.cpp` + (`llama_kv_cache`) and `src/llama-memory-recurrent.cpp`; `llama_memory_hybrid` and + `llama_kv_cache_iswa` delegate to their children. +- `src/llama-moe-cache.cpp`/`.h`: `llama_moe_cache::release_device()`, `restore_device()`, + `resident()`, `impl::invalidate()`. +- `ggml/include/ggml-backend.h`, `ggml/src/ggml-backend-impl.h`, `ggml/src/ggml-backend.cpp`: + optional `ggml_backend_i::free_scratch` and `ggml_backend_free_scratch()`; Vulkan implementation + `ggml_backend_vk_free_scratch` in `ggml-vulkan.cpp`. +- `src/llama-context.cpp`/`.h`: `llama_context::release_device(evict_kv)`, `restore_device()`, + `discard_device()`, `device_resident()`, members `kv_device_evicted`, `device_discarded`; the + auto-restore at the top of `llama_context::decode`. +- `include/llama.h`: `llama_context_release_device(ctx, evict_kv)`, `llama_context_restore_device`, + `llama_context_discard_device`, `llama_context_weights_resident`. +- `tools/mtmd/clip.cpp`/`.h`, `tools/mtmd/mtmd.cpp`/`.h`: `clip_release_device`, + `clip_restore_device`, `clip_weights_resident`, `mtmd_release_device`, `mtmd_restore_device`. +- Commits 481be8b28, 17165fe2a, bf2c1a699, 9857a45f0, 9b555f1aa, ad27d4921, 0a0f3ab6d, 7ac2014a8, + 6c480f7e7 (discard). + +**How it works.** Tensor metadata (`ggml_context` structs) is durable; device buffers are ephemeral. + +- Weights: on release, for each releasable buffer, capture a host shadow once (weights are + read-only), free the buffer, null every tensor's `buffer`/`data`. On restore, + `ggml_backend_alloc_ctx_tensors_from_buft` reallocates an identical layout (re-pointing the + tensors), the shadow is uploaded, usage is set to WEIGHTS. Only single-buffer, alloc-path, non-host + buffers are releasable: the host-pointer path (mmap or lazy-mapped), `no_alloc` dummy buffers and + host (`Vulkan_Host`, i.e. pinned RAM) buffers stay as they are. +- KV and recurrent state: same pattern, but the shadow is re-captured on every release (the data is + read-write) and dropped after restore. +- Scheduler: with `evict_kv`, `sched.reset()` frees the worst-case compute buffer and + `sched_need_reserve = true`; restore calls `sched_reserve()` (which goes through `sched_new()`, + re-registering the expert-copy callback and upstream's realloc callback). +- Backend scratch: with `evict_kv`, `ggml_backend_free_scratch()` on each backend. On Vulkan this + discards the pending compute context, synchronizes, destroys `prealloc_x`, `prealloc_y`, + `prealloc_split_k`, `prealloc_add_rms_partials`, `sync_staging`, and zeroes their sizes and the + `prealloc_y_last_*` tracking. They are reallocated lazily on the next compute. Other backends leave + the hook null (no-op). +- MoE cache (`--moe-cache-mib`, upstream #29887): released in both modes. The banks are freed and the + cache is emptied, not shadowed: every SLRU is rebuilt fresh, its `slot_map[il]` pointers are + re-pointed at the host slot-map tensors, and the host slot maps are cleared to 0xff (every slot + -1). On restore the banks are reallocated (which also re-inits their views), cleared to 0 and + marked WEIGHTS; the cache refills from the host experts. +- Multimodal encoder: `clip_release_device` / `clip_restore_device` use the weights pattern (shadow + once); no-op for a CPU-backed encoder. `mtmd_*` wrap the vision and audio contexts. +- `llama_context::release_device(evict_kv)`: synchronize, release weights, release MoE cache, and if + `evict_kv`: release memory buffers, free sched, free scratch. + `restore_device()`: weights, MoE cache, memory buffers, `sched_reserve()` if needed, then + `ggml_backend_sched_synchronize` so uploads finish before any compute. + `discard_device()`: like `release_device(true)` with `keep_shadow = false` everywhere (no host + copies), sets `device_discarded`; used only before exit. +- `decode()` calls `restore_device()` if `!device_resident()`, as a safety net. The server restores + explicitly on wake (F6), because some KV access happens before decode. + +**Invariants that must hold.** +- Shadows are stored compactly in stable tensor-iteration order, skipping view tensors + (`view_src != NULL`), and restored with the same iteration. Never index a shadow by + `t->data - base`. +- `weight_release` stays parallel to `pimpl->ctxs_bufs`: every push to `ctxs_bufs` needs a matching + push to `weight_release` (non-releasable slots use `emplace_back()`). +- The caller synchronizes before any release; `release_device` does this itself. +- Restore order: weights, MoE cache, KV/recurrent, scheduler reserve, scheduler synchronize. The MoE + cache banks must be back before the scheduler is rebuilt. +- After a MoE-cache release no slot map may point at an expert: banks come back zeroed, so a stale + slot map silently reads zero weights. +- Every iterator over `ctxs_bufs` (model, KV cache, recurrent) must tolerate a null buffer, and every + use of `sched` must tolerate null while cold with `evict_kv` (see F8). +- `device_resident()` covers weights and MoE cache; it gates the early returns, the decode + auto-restore and `llama_context_weights_resident()`. +- `restore_device()` after `discard_device()` aborts (`GGML_ASSERT(!device_discarded)`). +- Greedy output is byte-identical across any number of release/restore cycles, and the prompt cache + survives (`timings.prompt_n` drops on a repeated prompt after a cycle). + +**Failure modes and incidents.** +- The first shadow implementation indexed by `t->data - base` and produced garbage after restore + (layout and padding differ). Fixed by the compact iteration-order shadow. +- Restoring KV lazily at decode crashed iSWA models (gemma) with + `GGML_ASSERT(buf != NULL && "tensor buffer not set")`: `update_slots()` creates an SWA checkpoint + that reads the KV via `ggml_backend_tensor_get` before decode. Fixed by restoring on wake (2feb6aeb2). +- The recurrent state was left resident (default no-op), 201 MB on the 4B, until 9857a45f0. +- A model with weights on the CPU device (`-dev none` / `-ngl 0`) segfaulted (exit 139) in + `release_device_weights()` the first time the arbiter put it to sleep: CPU_REPACK buffers are not + host buffers, so `load_tensors` marked them releasable, and the shadow capture called their NULL + `get_tensor`. It also crashes production `2fc9f9c35`, but no production arbiter model has CPU-device + weights. Fixed in f24c3582c: only buffers on a non-CPU device are releasable. Found by the + `--diskcache` check (F11), whose arbiter cases run CPU only. +- The scheduler's compute buffer (about 700 MiB on gemma-26B) and the Vulkan prealloc buffers stayed + resident in a cold model until bf2c1a699 / ad27d4921. +- The MoE cache was not released at all before 7ac2014a8. Reallocating its banks without + invalidating would have produced silent wrong weights. +- In the 20261024 rebase `moe_cache_slru::init()` turned out to reset only the probation segment + (`head[1]`, `tail[1]` and `n_protected` survive), so re-running it on a used cache corrupts the + lists. `invalidate()` now assigns a fresh `moe_cache_slru()` before `init()`. + +**Rebase hazards.** +- New push sites into `ctxs_bufs` (upstream's `load_tensors_hadamard()` added two in the 20261024 + rebase; without matching `weight_release` entries `release_device_weights()` reads past the end). +- Changes to buffer creation in `load_tensors` (the `host_ptr_path` condition, `ctx_bufs`/`buf_ptrs` + bookkeeping; upstream replaced `ctx_buf_maps.emplace_back(ctx, buf_map)` with + `ctx_bufs.emplace_back(ctx, std::move(buf_ptrs))` in the 20261024 rebase). +- The `llama_memory_i` interface. New memory types that do not override `release_device_buffers` + keep their KV resident under `evict_kv`; at the time of writing that is `llama_kv_cache_msa`, + `_dsa`, `_dsa_iswa`, `_dsv4` and `llama_memory_hybrid_iswa`. +- MoE-cache internals (`groups`, `slru`, `slot_map`, `buf_host`, `devices`). Upstream `33d6135cb` + changed LRU to SLRU (`g.lru` -> `g.slru`); the pick applied cleanly and did not compile. +- `llama_context` members next to ours (upstream `n_reallocs_same/diff`, `copy_experts_info`), + `sched_reserve()` semantics, and the `decode()` signature (now `decode(const llama_batch_ext &)`). +- `ggml_backend_i` layout (`free_scratch` must stay the last member after `graph_optimize`; other + backends rely on zero-init) and the Vulkan context's prealloc field set (compare with + `ggml_vk_cleanup`). + +**Validation.** `fork-validate.sh --arbiter`: `b-greedy-identical` (15 cycles each side equal to a +no-handoff reference), `b-kv-survives` (prompt_n drops after evict/restore, output identical), +`c-image-after-restore`. `--moecache MODEL` (needs a cache large enough to hit; 256 MiB on gemma-26B +had 0 hits and proves nothing, 2048 MiB had 6651 hits). `--arbiter` `v-vram-release` / +`v-vram-restore` check that VRAM really drops: a baseline of `mem_info_vram_used` before any scratch +server, then server A warm and alone, forced cold by a fake waiter on want.lock: the card-wide delta +must drop by >= 70% of what A added and come back after the next request. Production's own share is +re-read from the DRM fdinfo of every process the script did not start; if it moved by > 64 MiB the +check SKIPs. First run (2026-10-25, 0.8B with mmproj, ctx 8192, `LLAMA_SLEEP_EVICT_KV=1`): warm ++546 MiB, cold +4 MiB, restored +546 MiB. + +### F5. On-demand mmproj (multimodal encoder) + +**What and why.** A multimodal model's vision encoder sat in VRAM on every text request. With +`LLAMA_MMPROJ_ONDEMAND=1` the encoder lives in RAM and enters VRAM only for an encode. Measured on the +35B: warm text-only VRAM 6321 -> 5459 MB (about 860 MB freed for KV and compute), image answered +correctly, text after the image correct. + +**Where.** `tools/server/server-context.cpp`: `encode_mtmd_chunk` (upstream `9871df591` split the +encode out of `process_mtmd_chunk`; `encode_mtmd_chunk` is called from `process_mtmd_chunk` and +directly from the batched-embedding path in the slot update, so the restore covers both), the +`mtmd_release_device(mctx)` after `mtmd_init_from_file` in `load_model`, `vram_go_cold`, +`vram_share_exit`. Library side in F4. Commits 0a0f3ab6d, 5e99ac198. + +**How it works.** After load the encoder is released (shadow captured). Before +`mtmd_batch_encode`, `mtmd_restore_device(mctx)`; if that fails (out of VRAM) and on-demand is set, it +releases the LLM backbone weights only (`llama_context_release_device(ctx_tgt, false)`: read-only +shadow, so a cheap free with no D2H, KV and prompt cache untouched) and retries. After the encode it +releases the encoder FIRST, then restores the weights, so the peak stays within VRAM. + +**Invariants that must hold.** +- Free the encoder before re-uploading the weights. +- The donor is the weights, never the KV (the KV is read-write and would need a D2H every time). +- `vram_ensure_warm()` does not restore the encoder; only the encode path does. + +**Failure modes and incidents.** Before this, a cold text model with an auto-downloaded mmproj +(`-hf` pulls one when the repo ships it) held 644 MB that no release path touched. The text-only 4B +task model now runs with `--no-mmproj`, which is the right fix for any model that never sees images. + +**Rebase hazards.** Renames or restructuring of `encode_mtmd_chunk` and the mtmd init block in +`load_model`; `clip_ctx` fields (`buf`, `ctx_data`, `sched`, `no_alloc`). + +**Validation.** `fork-validate.sh --arbiter` case `c-image-after-restore` (server A runs with +`--mmproj` and `LLAMA_MMPROJ_ONDEMAND=1`; a 128x128 red PPM must be answered "red" after A was cold, +and text right after must equal the reference). Post-deploy: one image request to gemma-26B. + +### F6. Cross-process VRAM arbiter (server side) + +**What and why.** Several llama-server processes under llama-swap share one GPU: exactly one is warm +(holds its device buffers) at a time, and a cold one warms on demand. Handoff measured off production: +60 alternating handoffs between two small-model servers, 0 stranded, median 0.309 s. In production 4 handoffs between +the 35B and the 4B had a median of 4.357 s, most of it the 35B's own prefill. The last +`fork-validate.sh` run before the 20261024 deploy: 30 handoffs, median 680 ms, max 1231 ms (the +2026-10-25 run of the same build read 1050 ms, max 1562 ms: handoff latency moves with node load, +which is why it is now A/B'd against the reference in one session). + +**Where.** `tools/server/server-context.cpp`: `vram_arena_open`, `vram_acquire_for_load`, +`vram_share_init`, `vram_should_yield`, `vram_want_acquire`, `vram_want_release`, `vram_take_token`, +`vram_ensure_warm`, `vram_go_cold`, `vram_share_exit`, `vram_share_shutdown`, the VRAM-only branch of +`handle_sleeping_state`, the `vram_ensure_warm()` call before decode in the slot update path, and +`server_res_generator` (`bypass_sleep`). `tools/server/server-queue.cpp`/`.h`: `on_should_yield`, +`start_loop` (`should_sleep`, idle tick, post-wake grace), `wait_until_no_sleep`, `is_stopping`. +Commits 481be8b28, 958257cd6, b9df854de, 2feb6aeb2, 878d1338f. + +**How it works.** +- Enabled by `LLAMA_SLEEP_VRAM_ONLY` (any value). The arena directory is `LLAMA_VRAM_ARENA` (default + `/dev/shm/llama-vram`) with two files. +- `token.lock`: `flock(LOCK_EX)` is the baton. Rule: a process has device buffers iff it holds it. +- `want.lock`: a waiter holds it `LOCK_SH` while waiting and drops it once it owns the token. The + holder probes it with `flock(LOCK_EX | LOCK_NB)` on a SECOND fd: failure means somebody is waiting. + The probe needs its own open file description, because flock on the waiter's own fd would convert + that lock instead of conflicting with it. The kernel drops a dead waiter's lock, so nothing goes stale. +- Load: `load_model()` calls `vram_acquire_for_load()` before `common_init_from_params()`, so the + current holder releases before this model uploads anything. The loaded model stays warm holding the + token and serves its first request without a re-warm. +- Yield: `vram_share_init()` registers `vram_should_yield` with `queue_tasks.on_should_yield`. + `start_loop()`'s `should_sleep()` calls it on the loop thread, under `mutex_tasks`, only when the + task queue is empty and `update_slots` has returned. While the callback is set the idle wait ticks + every 10 ms instead of 1 s. After a wake the server holds the GPU for at least 100 ms + (`yield_grace_ms`). Sleep runs the sleeping callbacks; in VRAM-only mode `handle_sleeping_state(true)` + calls `vram_go_cold()` (release device, also the encoder; then `flock(LOCK_UN)`) instead of + upstream's full unload. +- Wake: a request calls `wait_until_no_sleep()`. `handle_sleeping_state(false)` calls + `vram_ensure_warm()`: take the token (register on want.lock, then poll `token.lock` with + `LOCK_EX | LOCK_NB` every 2 ms, aborting when `queue_tasks.is_stopping()`), restore ctx_tgt and + ctx_dft, and only then set `vram_cold = false`. The decode path calls `vram_ensure_warm()` again + (no-op when warm) and throws "server is shutting down" if it returns false. +- `server_res_generator` no longer bypasses the wake path when `--sleep-idle-seconds` is unset if + `LLAMA_SLEEP_VRAM_ONLY` is set, because the arbiter can put a server to sleep without idle-sleep. +- Queue fixes: `wait_until_no_sleep()` loops `while (sleeping && !stopping)` and re-asserts + `req_stop_sleeping` each time (with `notify_all`); the sleep wait also wakes on a non-empty task + queue; the idle `wait_for` only leaves the loop on a real task or termination. + +**Invariants that must hold.** +- Resident iff holding `token.lock`; `vram_cold == false` means both. `vram_ensure_warm()` sets + `vram_cold = false` only AFTER the restore. What that order protects today, reasoned from the code: + the only thing that gives the token away is `vram_should_yield()`, called from `should_sleep()` on + the loop thread. `vram_ensure_warm()` also runs only on the loop thread, synchronously: from the + wake callback (`handle_sleeping_state(false)`, called inside `start_loop()` with `mutex_tasks` + held) and before decode in the slot update path (outside `yield_to_queue()`). So `should_sleep()` + cannot run between the token acquire and the end of the restore, whichever order the two lines + are in. The measured failure (attempt 1 below: handoffs of 11m20s and 3m57s) happened under the + retired doorbell design, where a separate warden thread read the cold flag to decide whether to + honour or discard rings, so an early `false` let it accept stale rings during the restore. Under + the inline want-lock probe the order is defensive: it keeps the flag's meaning exact for any future + reader off the loop thread, and keeps a release out of a half-restored model if the restore or the + probe ever moves (for example into `yield_to_queue()`). Either way, do not change it without an A/B + of ordinary handoff latency (`fork-validate.sh --arbiter`, `a-handoff-latency`). +- `vram_acquire_for_load()` sets `vram_cold = false` as soon as it holds the token, before the upload. + Nothing reads the flag during the load today (the loop is not running yet and `on_should_yield` is + only registered in `vram_share_init()`, which sets it again), so the early set is redundant now. + It records "holding the token" at the moment it becomes true, because the opposite error is the + dangerous one: a model that is warm and holds the token while `vram_cold` says cold never yields + (`vram_should_yield()` returns false for a cold model), which strands every waiter, and its next + wake would try to restore weights that were never released. +- Release only happens from the idle branch of `start_loop()`, on the loop thread, never inside + `yield_to_queue()` or while a slot is generating: a holder finishes its current generation before + it yields, and a waiter has no timeout (decoding without the token risks an OOM that kills both). +- The yield decision reads live kernel state at the point of use. Do not route it through a flag set + by another thread (see attempts 3-4 below). +- Every exit from `vram_take_token()` drops want.lock, or the holder yields forever. +- The probe fd is separate from the waiter fd. +- `flock` calls retry on EINTR: the server's signal handlers are installed without SA_RESTART. +- Restore on wake, before `update_slots()`, so KV eviction is safe for SWA checkpoints. +- Every model that can be warm on the GPU at the same time must use the same arena. A non-arbiter + process (a benchmark, a manually started server) can OOM the warm model. In production the env is + set for all of llama-swap, so all its children participate. + +**Failure modes and incidents.** +- Wake-path hang (958257cd6): with no `--sleep-idle-seconds`, `bypass_sleep` skipped + `wait_until_no_sleep()`, so a server slept by the arbiter never woke and requests hung. +- Load-time OOM (b9df854de): weights were uploaded before the arbiter was active; loading gemma while + the 4B held VRAM could exceed 8 GB. After the fix the peak was 7771 MB. +- The doorbell design (replaced by 878d1338f) was edge-triggered: a waiter wrote + `/doorbell/` and the holder's warden thread turned the inotify event into a yield flag. + Rings were lost in three windows: while the holder restored (it advertised cold and discarded + foreign rings), while the holder loaded (the inotify watch did not exist yet, and the kernel does + not queue events for a missing watch), and when a cold waiter consumed a third process's ring. + Every loss was permanent: `flock(LOCK_EX)` had no timeout and production had no idle-sleep. The + blocked flock held `mutex_tasks`, so the whole server stopped answering while `/health` still + returned 200, and llama-swap never restarted it. Doorbell files also accumulated as litter (37 by + the second day). +- Failed fix attempt 1 (doorbell design): moving `vram_cold = false` before the restore made the + holder's warden honour stale rings and hand the token back 2-5 s after taking it without serving. + Handoffs took 11m20s and 3m57s against 5 s and 20 s before. Rolled back. See the first invariant + for what this means under the current design. +- Failed fix attempt 2: a re-ring loop (`LOCK_NB` + re-ring every ~1 s). Queued rings from an already + satisfied waiter caused spurious releases; one handoff hung over 11 minutes against a 3.0-7.7 s + baseline. Lesson: a ring carries no notion of "still wanted"; the mechanism had to become + level-triggered. +- Failed attempts 3-4: want.lock was sound (mutual exclusion, kill -9 safety, load-window coverage), + but the warden thread still delivered its decision as a flag. `start_loop()` holds `mutex_tasks` + from `should_sleep()` through the callbacks to the wait, so the warden's `request_yield()` was always + admitted after the flag had been consumed, latching a release for the next wake (a server woke and + re-slept 138 ms later without serving). It also exposed the upstream lost wakeup in + `wait_until_no_sleep()`. Result: 0.494 s median, 1/60 stranded. The fix deleted the warden and + `request_yield`/`yield_requested` and probes inline in `should_sleep()`. +- Measured deviations that are required: the 10 ms idle tick (about 0.2% of one core per warm + server); a waiter that polls rather than retrying on a coarse grid (a 200 ms retry grid cost 0.503 s + against 0.336 s, because the holder only releases after the waiter asks); the 100 ms post-wake + grace (without it a permanent waiter caused a livelock: one request took 23.15 s over 138 + sleep/wake cycles). +- Process lesson from attempts 1-2: validate an ordinary handoff latency A/B, not only the + pathological case. Two production deploys were burned before that rule existed. +- Lost diagnostic: the old periodic "still waiting for the GPU token after N s" warning is gone; a + stuck token now shows one `VRAM arbiter: waiting for the GPU token` line and then silence. Check + `/proc/locks` (see the runbook). + +**Rebase hazards.** This is the most fragile area, because it sits inside upstream's server loop. +- `server_queue::start_loop`, `wait_until_no_sleep`, `process_new_tasks`, `yield_to_queue` and the + sleeping-callback vector. Upstream refactored sleep (`947fd9bb2`) and made decode run inside + `yield_to_queue` (`22b8e310b`); re-check after any such change that a release still cannot run + under a live graph. +- `handle_sleeping_state`, `load_model` ordering, the slot update path where decode happens, + `server_res_generator`'s `bypass_sleep`, renames in `server-context.cpp`. +- Anything that touches the KV in `update_slots()` before decode. + +**Validation.** `fork-validate.sh --arbiter` with two real servers on a scratch arena: +`a-handoffs` (30 alternating, 0 stranded, 0 non-200, the server that answered holds `token.lock`), +`a-handoff-latency` (fresh server pairs of `--build` and `--ref` in the same session, blocks +ref, cand, cand, ref x 16 handoffs; FAIL if the candidate median exceeds the reference median by more +than max(25%, 200 ms); first run 2026-10-25, reb1024 against itself beside production: 1050.5 vs +1082.5 ms), `v-vram-*` (F4), `b-*`, `c-*`, `g-kill9-waiter` (kill -9 a waiter registered on want.lock while the holder streams: +want.lock readers drop to 0, the holder keeps the token, no extra sleeps), plus the shutdown cases in +F7 and a log scan for asserts and Vulkan errors. In production, `/proc/locks` must show the warm +model holding WRITE on `token.lock`. + +### F7. Server shutdown path + +**What and why.** llama-swap evicts models with SIGTERM, so shutdown happens all the time, often +while the arbiter is mid-release or mid-wait. Two bugs made shutdown keep the GPU token and stall +every other model. + +**Where.** `tools/server/server.cpp`: `signal_handler`, `shutdown_pipe`, `struct shutdown_thread`, +`sig_thread` in `llama_server`. `tools/server/server-context.cpp`: `server_context::start_loop` (calls +`vram_share_exit()` after the loop returns), `server_context::terminate` (terminates the result queue +first), `vram_share_exit`, the destructor's `vram_share_shutdown()`. `tools/server/server-queue.cpp`: +`server_queue::terminate` (sets atomic `stopping` before taking the mutex), `process_new_tasks`, +`server_response::recv_with_timeout`, `server_response::terminate`, +`server_response_reader::next`. Commits 11044b35e, 6c480f7e7. + +**How it works.** +- The signal handler only writes the signal number to a self-pipe (async-signal-safe); a dedicated + thread reads it and runs `shutdown_handler`. The pipe fds are `FD_CLOEXEC`. If `pipe()` fails the old + direct call is used. The thread object is declared after the server objects, so it is joined (a 0 + byte unblocks it) before they are destroyed. A second signal still calls `exit(1)`. +- `terminate()` sets `stopping` (atomic) before locking `mutex_tasks`, then stops the result queue so + HTTP handlers waiting for results get "server is shutting down" (HTTP 503, or an SSE error event); + `recv_with_timeout` checks `!running` before waiting and returns null. +- A token wait polls with `LOCK_NB` every 2 ms and aborts on `is_stopping()`; the aborted wake stays + cold, skips the restore, and the loop exits before `update_slots`. +- After `start_loop()` returns, `vram_share_exit()` frees all device buffers with + `llama_context_discard_device()` (no host shadows), releases the encoder, and only then unlocks + `token.lock`. +- What llama-swap (v239 on the pod) does when a child exits on its own (crash, OOM kill, external + signal), verified 2026-10-25 with a scratch llama-swap instance and a CPU-only child, for both + `kill -9` and an external SIGTERM: it logs + `[WARN] group: running exited: [] upstream exited unexpectedly`, does not restart it + eagerly (no new process in the 2 s after the kill), and starts a new process on the next request + for that model (new PID, health check, HTTP 200). The production log since the last pod restart has + no such event. Consequences: the dead process's RAM prompt cache is gone, the request that triggers + the restart pays a full model load (about 26 s for the 35B with `-lm none`; the first 35B request + after the 2026-10-25 deploy took 34 s including load and answer), and under the arbiter + the new process takes the token through `vram_acquire_for_load()` like any load. A process that + wedges instead of exiting (the incidents below) is never restarted: `/health` keeps answering. + +**Invariants that must hold.** +- Nothing that takes `mutex_tasks` runs in signal context. +- The token is released only after this process's VRAM is free (the next model may start uploading + the moment the lock drops). +- A shutting-down server never restores weights. +- SIGTERM in any state exits 0 within about 2 s and frees the token. With the disk prompt cache (F11) + the exit also writes each slot's state: about 1 s more per GB of state, after the token is free. + +**Failure modes and incidents.** +- SIGTERM self-deadlock (production incident, gemma-26B): the signal landed on the loop thread inside + a sleeping callback (under `mutex_tasks`, during a release); the handler's `terminate()` locked + `mutex_tasks` again on the same thread. The process wedged holding `token.lock`, every other model + queued behind it, and only SIGKILL worked. Reproduced 6/6 off production; 8/8 clean with the fix. + The first suspicion (the multimodal path) was wrong. gdb on the wedged process showed the main + thread in `futex(mutex_tasks)` with the `yield_to_queue` worker idle. +- Token kept on shutdown: with a request in flight the HTTP handler waited forever for results, main + blocked joining it, and the token was released only in the destructor after that join; with a + token wait in progress the blocking flock held `mutex_tasks`; and the old destructor unlocked the + token BEFORE `destroy()`, so the next model could upload into still-occupied VRAM. +- After the fix: off production SIGTERM mid-generation or mid-wait exits in about 0.2 s with exit 0 + and frees the token in 5-70 ms; in production about 0.7-1 s. + +**Rebase hazards.** `server.cpp`'s signal setup and `llama_server` object lifetimes; +`server_response` and `server_response_reader` (upstream `4e201388c` switched `recv_with_timeout` to a +fixed deadline: keep the order "check `!running`, return null, then `wait_until(lock, deadline)`"); +`server_context::start_loop`/`terminate`. Router mode (`server-models.cpp`, +`server_models_sse_client::next`) only checks `should_stop()` and can spin at shutdown now that +`recv_with_timeout` returns null at once; llama-swap does not use router mode. + +**Validation.** `fork-validate.sh --arbiter`: `d-term-in-release` (gdb breakpoint on +`llama_context_release_device`, then SIGTERM: exit 0 within 2.5 s, the other server gets HTTP 200 and +the token), `e-term-waiting` (exit 0 within 1.5 s, never took the token), `f-term-streaming` +(exit 0, SSE error event, token free within 2.5 s), `h-shutdown-warm`, `h-shutdown-cold`. Last run +(2026-10-25, 2fc9f9c35, `d` by log polling): 750 ms, 225 ms, 126 ms (token free in 23 ms), +108/159/159 ms. Post-deploy: a forced llama-swap eviction +must log `VRAM arbiter: loop stopped, device memory freed, releasing the GPU token` and exit by itself. + +### F8. Cold-teardown guards + +**What and why.** A cold model has null buffers in its `ctxs_bufs` and, with `evict_kv`, a null +scheduler. Upstream code never had to consider either state. + +**Where.** `src/llama-context.cpp`: `llama_context::~llama_context` (`sched &&` in the +compute-buffer size check), `llama_context::memory_breakdown` (`if (sched)` around the compute part; +upstream's `if (moe_cache)` breakdown block stays outside it). Null-buffer skips in +`llama_model::memory_breakdown`, `llama_kv_cache::{clear, memory_breakdown, total_size}`, +`llama_memory_recurrent::{clear, memory_breakdown, total_size}`. Commits 8d80f0673, ad27d4921, 53f907771. + +**How it works.** Guards at the call sites. The asserts in ggml (`GGML_ASSERT(buffer)`, +`GGML_ASSERT(sched)`) are correct and stay; every other caller reserves the scheduler first. + +**Invariants that must hold.** A server shut down while cold exits 0. Any new upstream code that +iterates `ctxs_bufs` or calls into `sched` on a path reachable while cold (shutdown, memory +breakdown, stats) needs the same guard. + +**Failure modes and incidents.** +- `GGML_ASSERT(buffer)` on shutdown of a cold model (seen 7 times in production logs) from + memory-breakdown/size/clear on released buffers. +- `GGML_ASSERT(sched)` in `memory_breakdown` for a cold `evict_kv` model being torn down. +- `GGML_ASSERT(sched)` in the destructor's size check: every cold shutdown exited 134 instead of 0, so + under llama-swap an ordinary stop looked like a crashed child, left a backtrace in the log, and the + rest of the destructor never ran. Repro: arbiter env on, one request, force a yield with + `flock -s /want.lock -c 'sleep 6'`, then SIGINT while cold. + +**Rebase hazards.** New iteration over `ctxs_bufs`, new `sched` users in teardown or breakdown +paths. Watch item: `llama_kv_cache::update()` takes `lctx->get_sched()`, which can be null; it is +safe today only because its single caller runs after `sched_reserve()`. + +**Validation.** `fork-validate.sh --arbiter`: `h-shutdown-cold` (exit 0 while the other server holds +the token) and `log-scan`; `--moecache` `shutdown`. + +### F9. Validation script + +**What and why.** The measurement method on this box had to be rediscovered several times (section +6; the rules are in the runbook, section 11). The validation script encodes the checks that each past incident +required, so a rebase can be validated by someone with no context. + +**Where.** `scripts/fork-validate.sh`. Commit a1eb757ea (squashed from 11 script commits). The +fork also carried a benchmark harness, `scripts/rx580-bench/` (corpus prefill through llama-server +plus a llama-bench sweep, 6 files, about 940 lines); it was last run on 2026-09-09 +(`/root/bench/results.txt`), the windows since then used `fork-validate.sh --perf` and ad-hoc +llama-bench scripts in `/root/arms/`, and it was removed on 2026-11-23 (owner decision). Its +methodology moved to the runbook, section 11; the code is on the older branches. + +**How it works.** +- `fork-validate.sh --build CAND --ref REF [--ops] [--arbiter] [--perf] [--moecache MODEL] + [--diskcache]`: runs on the pod, PASS/FAIL/SKIP per check, nonzero exit on any FAIL. Uses a + scratch dir under /tmp, a scratch arena (refuses `/dev/shm/llama-vram*`), ports 8091-8093, unsets + inherited `GGML_*`/`LLAMA_*` env except `GGML_VK_ASYNC_USE_TRANSFER_QUEUE` (production's driver + setting since 2026-11-23: export it with `VK_ICD_FILENAMES` and `RADV_EXPERIMENTAL`, section 5, to + validate on production's Mesa), kills only PIDs it started (PID-reuse safe). Default with no check + flag is `--ops --arbiter`. `--perf-report TSV` re-aggregates a saved `perf.tsv` offline. + See the header of the script for what each check proves. +- Which phase needs what: `--ops` runs beside production; `--arbiter` too only if 1536 MiB + of VRAM is free (it FAILs at once otherwise; with gemma-26B warm only about 1.2 GiB is, so it often runs + in the swapdown window, about 2 minutes); `--perf` and `--moecache` need llama-swap stopped (the + first refuses otherwise; `--moecache` does not check, but loads a MoE model and must not share + the card either). `--diskcache` runs beside production (CPU only); its GPU leg SKIPs below 1536 MiB + of free VRAM. + +**Reference values** (Qwen3.6-35B-A3B UD-Q4_K_XL, production config, `--perf` on 2026-10-24, +production `6c480f7e7` and the previous production `5751c977b`): pp2048 about 274-286 t/s, +pp2048@d16384 about 201-206, pp2048@d32768 about 158-160, tg256@d4096 about 17.8. On 2026-10-25 +(medians, `6c480f7e7` / `2fc9f9c35`): pp2048 274.5/273.8, d16384 200.5/200.4, d32768 157.6/157.6, +tg256@d4096 16.8/16.7. The corpus +reference values of the removed harness are in the runbook, section 11. A fresh run far outside these +means something else is wrong (another GPU user, thermal state, a bad build) before it means a +regression or a win. + +**Invariants that must hold.** Never benchmark with llama-swap running (`--perf` +refuses, and any other llama process blocks it). `--perf` gates prefill at -5% per depth on the +MEDIAN of all repetition samples of each build (never a mean: CPU contention produces single +catastrophic samples), and peak VRAM at 95% of the card; decode is reported, not gated (CPU-bound and +noisy here). + +**Failure modes and incidents.** Upstream #28334 removed `--mmap`/`--no-mmap`/`--mlock` and +llama-bench's `-mmp`: the server refused to start and llama-bench silently produced no rows until +54a7f534b switched to `-lm none`. The perf and MoE-cache checks leave tens of GB of model files in page +cache charged to the pod; that was the likely trigger of a pod OOM kill during the first 20261024 +deploy (see the runbook). That pod restart also emptied `/tmp` (every earlier `fork-validate.*` +scratch dir with its raw samples is gone) and removed gdb, which is not in the pod image; `--arbiter` +case `d-term-in-release` then falls back to polling the log. 2026-11-23: removing `--moe-exact` +also removed two helpers that other checks call (`gpu_exclusive` of `--perf`, the prose prompt of +`--diskcache`, now `prose_prompt`). bash only prints `command not found` for a missing function, so +`--perf` returned before any test without a FAIL, and `--diskcache` failed on a 30-token first +turn, below the 256-token minimum that is saved; fixed in the F9 commit. After removing a check, grep the script +for every function the removed section defined. + +**Rebase hazards.** CLI flag renames in `common/arg.cpp` and `tools/llama-bench`; log line texts the +script greps for (`server entering sleeping state`, +`no longer waiting for the GPU token`, `released .* MiB of MoE cache`, `MoE cache size =`, +`llama_moe_cache: .* hits =`, `N/M tests passed`, +`Backend Vulkan0: OK`, `disk cache: restored`, `disk cache: copied`/`saved`, `prompts of this model`, +`size limit, removing`, `disk cache: failed to write`); llama-bench's jsonl fields (`n_prompt`, `n_gen`, `n_depth`, `samples_ts`) and +markdown layout; the DRM fdinfo keys `drm-client-id` / `drm-memory-vram`. + +**Validation.** Known gaps of the script: peak VRAM is recorded per arm, not per test. The first +candidate arm has now twice shown an unexplained spike of about 1.6 GiB over the other arms +(2026-10-25: ref 5476, cand 7062, cand 5767, ref 5476 MiB); the cause is open (per-test peaks would +locate it), and it stays far below the 95% gate. The SIGTERM-in-release breakpoint is at function +entry, not after the host-shadow capture. The `v-vram-release` SKIP path (production moving during +the measurement) has not been exercised. The median-gated `--perf` first ran on the GPU on 2026-10-25 (runbook section 6). The `--concat` +and `--moe-exact` checks were removed on 2026-11-23 with F3 and F1. + +### F10. Page-cache drop after a copying load + +**What and why.** With `-lm none` the loader read()s the GGUF into its own buffers, but the kernel +keeps the file in page cache afterwards, charged to the pod's cgroup: about 20 GB after a 35B load. +The pod is BestEffort on a shared node, and on 2026-10-24 the Talos OOM controller killed it right +after a model load under exactly that pressure (MemFree < 1 GB, file cache about 20 GB). Once the +data is copied those pages are pure waste, so the loader advises the kernel to drop them. + +**Where.** `src/llama-mmap.h`/`.cpp`: `llama_file::drop_cache(offset, len)`. +`src/llama-model-loader.cpp`, `llama_model_loader::load_all_data`: the per-tensor drop at the end +of the copy (non-mapping) branch and the whole-file drop in the final cleanup +(`size_done >= size_data`). `tools/mtmd/clip.cpp`, `clip_model_loader::load_tensors`: whole-file drop +after the tensor reads. Commit cce0ac1f0. + +**How it works.** +- `drop_cache()` is `posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED)` under `#ifdef __linux__` + (no-op elsewhere); `len` 0 means to the end of the file. Errors are logged at debug level only. +- `load_all_data()` drops each tensor's range right after it is read (all three copy paths: straight + into a host buffer, the async pinned-upload chunks, the staging buffer), so the cache never grows + past about one tensor during the load. The final cleanup drops every file whole, which catches the + GGUF metadata and the partial pages at tensor edges that a range drop leaves. +- Both run only when `mappings.empty()`, i.e. the loader holds no mapping of any of its files: not + `mmap`, `mmap+mlock` or `auto`, and no lazy tensors (`-lzm`; with lazy tensors `init_mappings()` + maps every file even under `-lm none`). Split GGUFs are covered (every entry of `files`). +- clip.cpp always copies the encoder through an ifstream (no mmap path exists), so it opens the + file again after the reads and drops it whole, unless `no_alloc`. +- Choice: per-tensor plus a final drop rather than a post-load drop only, because the per-tensor + drop also removes the peak during the load (the incident window: anon and file cache grow together) + for three extra lines. It costs about 0.27 s more than a post-load-only drop on the test model + below. Direct IO (`-lm dio`, upstream's) was measured as the alternative and is not better (section 4). + +**Invariants that must hold.** +- Never drop for a file this loader maps: a mapped page would just be faulted back in (the kernel + also skips pages that are mapped into a process, so a violation costs refaults, not correctness). +- Drop only after the bytes are in our own buffers. Nothing in the fork re-reads the GGUF after + load: the VRAM release/restore (F4) uses host shadows, not the file. +- The drop is a hint: a failure must not fail the load. + +**Failure modes and incidents.** None. Deployed 2026-10-25 (`2fc9f9c35`); on a 35B GPU load in +production the node page cache stayed at 4.2-5.3 GB instead of growing by about 20 GB. Costs to know +about: +- Load time rises by the synchronous page freeing that reclaim would otherwise do later: +0.95 s on a + 5.9 s load of 3.4 GiB (gemma-4-E2B plus mmproj). Unmeasured on the 35B; by size it would be a few + seconds on a 26 s load. +- A reload of the same model can no longer hit a warm page cache (a warm-cache reload of the test + model took 4.6 s against 5.9 s cold). Under llama-swap a reload happens only after an eviction or + a crash. +- `TENSOR_DUPLICATED` tensors read the same range twice; the second read now comes from disk (small + tensors only). + +**Rebase hazards.** The structure of `load_all_data()` (the `from_mapping` branch and its three copy +paths, the final cleanup block), `init_mappings()` creating mappings for lazy tensors, new load modes +in `llama_load_mode` (any new mode that maps must leave `mappings` non-empty), and the tensor-read +loop in clip.cpp `load_tensors`. + +**Validation.** Not in `fork-validate.sh`. By hand on the pod with a scratch llama-server on a +scratch port, CPU only (`-dev none -ngl 0 --no-mmproj-offload`, no VRAM), cold cache (evict the test +files with python `os.posix_fadvise(..., DONTNEED)` first): page residency of the model and mmproj +files by `mincore` before and after the load (must be 0 after with `-lm none`, unchanged with +`-lm mmap`), the pod cgroup's `file`/`anon` in +`/sys/fs/cgroup/kubepods/besteffort/pod/memory.stat`, host `MemFree`, load time, and a greedy +request. First run (2026-10-25, gemma-4-E2B UD-Q4_K_XL 2.5 GiB + mmproj BF16 0.9 GiB, production +6c480f7e7 and the candidate with the drops disabled as controls, 4 rotated rounds): + +| | drops off (control) | post-load only | per-tensor + final (committed) | +|---|---|---|---| +| model / mmproj resident after load | 2431-2444 / 940 MiB | 0 / 0 | 0 / 0 | +| peak model residency during load | 2.1-2.5 GiB | 2.1-2.4 GiB | 1.2-1.5 GiB (largest tensor) | +| pod cgroup `file` after load | +3.37 GiB | +0 | +0 | +| host MemFree after load | 0.6 GB | 2.5 GB | 2.5-2.8 GB | +| load time (median, production 5.85 s) | 5.87 s | 6.56 s | 6.82 s | + +Anon was +3.75 GiB in every arm. Host MemAvailable cannot show the win: it counts clean page cache as +available. Greedy output byte-identical in all arms. `-lm mmap` control: the model file stays fully +resident and mapped (2498 MiB, `file_mapped` +2.5 GiB) after load and after a request, and only the +copied mmproj is dropped. `-lzm on` control: no drop (the file is mapped), 1252 MiB of copied +tensors stay cached. The GPU upload path and a 35B load were first exercised by the 2026-10-25 +deploy (page cache result above); the load-time cost on the 35B was not isolated (the first 35B +request took 34 s including load and answer). + +### F11. Disk prompt cache (save slots on shutdown, restore after a restart) + +**What and why.** Only one large model fits in RAM. Switching models in OpenWebUI makes llama-swap +SIGTERM the previous one, and switching back re-prefills the whole conversation, because the RAM +prompt cache died with the process (F4's reason for the arbiter). A 30k-token chat costs about 150 s +on the 35B at about 200 t/s. With `--cache-disk-path DIR`, each slot with a prompt is saved to DIR on +shutdown. After the restart, a request whose prompt starts with a saved prompt is restored from the +file, so only the suffix is processed. Measured on Qwen3.5-0.8B CPU only: a 12k-token turn 2 went +from a 72 s prefill to 1.2 s, of which the read took 307 ms and the restore 18 ms. Off by default. +Upstream PR #28092 (`--cache-disk`) was the reference for ideas, not ported (1700 lines). It +livelocked the kernel on AMD + Vulkan by DMA-ing GPU state into a MAP_SHARED mmap'd file, and it never +saved the slot in use on shutdown, which is the main case here. + +**Where.** +- `tools/server/server-task.h`/`.cpp`: `server_prompt_disk_entry`, `server_prompt_disk_cache` + (`n_reuse`, `find`, `has`, `load`, `save`, `remove`); file IO helpers `disk_cache_io`, + `disk_cache_open`. +- `tools/server/server-context.cpp`: `DISK_CACHE_MIN_TOKENS`, `disk_cache_key`, + `disk_cache_collect`, `disk_cache_flush`, `disk_cache_load`; the init in `load_model` after the RAM + cache; the `disk_cache_load` call at the end of `get_available_slot`; `server_context::start_loop` + (collect, `vram_share_exit`, flush). +- `common/arg.cpp`, `common/common.h`: `--cache-disk-path` (`cache_disk_path`), `--cache-disk-size` + (`cache_disk_mib`, default 4096, 0 = no limit). +- Library (cold save): `llama_context_restore_memory_host()` (`include/llama.h`, + `llama_context::restore_memory_host`); `llama_memory_i::restore_device_buffers(bool to_host)` in + `llama-memory.h`, `llama-kv-cache`, `llama-memory-recurrent`, `-hybrid`, `-kv-cache-iswa`; the helper + `llama_memory_wrap_host()` in `llama-memory.cpp`. +- Commits dd851fd0c, 2874dcb10, 2c6c517ba (and f24c3582c, F4). + +**How it works.** +- Save, after `start_loop()`'s loop returns. First `disk_cache_collect()` copies the state of every + slot with at least 256 text tokens to host memory (`llama_state_seq_get_data_ext`, flags NONE) + while the device buffers still exist. Then `vram_share_exit()` frees the VRAM and releases the GPU + token as before. Then `disk_cache_flush()` writes the files. The token release therefore waits + only for the device-to-host copy, never for disk IO. +- A slot is skipped when its KV does not cover its token list (`seq_pos_max + 1 != n_tokens`: the last + batch was not decoded, a shutdown during a token wait), when it holds media, and when the same + token list is already on disk. +- Cold server: with `LLAMA_SLEEP_EVICT_KV` the KV and recurrent state live only in host shadows (F4) + and their tensors have no buffer. `llama_context_restore_memory_host()` wraps each shadow as a + CPU_Mapped buffer (`ggml_backend_cpu_buffer_from_ptr`) and points the tensors into it, so there is + no copy, no allocation and no device use. It sets `device_discarded`. Without evict_kv the KV is still + in VRAM and is read directly. +- File, `/-.lpcd`: a 48-byte header (magic `LPCD`, version, key hash, + n_tokens, n_ckpt, payload size, payload hash), then 8-byte padded sections: tokens, checkpoint table, + state size, state, the state of each checkpoint. The hash is FNV-1a over the 64-bit words of the + payload. Write: plain fwrite to `.tmp`, fdatasync, `POSIX_FADV_DONTNEED`, rename. Read: plain fread, + then DONTNEED. There is no mmap anywhere. +- Index: at startup, from the headers, tokens and checkpoint tables of the files of this key. A bad + magic, a file size that differs from the header, or an inconsistent table means the file is removed. + Other keys and other versions are counted and left alone. A `.tmp` older than 1 h is removed. +- Key: the build commit, the model path + size + mtime, LoRA adapters and control vectors, n_ctx, + n_ctx_seq, n_seq_max, n_ubatch, kv_unified, swa_full, K/V types, flash-attn type, and the RoPE/YaRN + parameters. +- Restore: at the end of `get_available_slot()`, after the RAM cache, only while warm, with + `cache_prompt` on and no media tokens. The file that reuses the most of the new prompt is loaded if + it reuses at least 256 more tokens than the slot holds. The slot's prompt goes to the RAM cache + first. Then the slot is cleared and the state is set; a failure clears the slot and removes the file. +- Reusable means one of two things. Either the saved token list is an exact prefix of the new prompt, + or, for a recurrent or SWA model, a saved checkpoint at or below the common prefix can be used. A + plain-KV model can be cut back to any prefix. Exact prefix alone would almost never fire: the Qwen + template rewrites the previous assistant turn (the reasoning is dropped), so the saved list is not a + prefix of the next OpenWebUI turn. Checkpoints are exact snapshots, and `update_slots()` rolls back + to one exactly as it does for the RAM cache; the recurrent state itself is never cut back. + Restored checkpoints get `id_task = -1`, so one that fails to load means a re-prefill, not an abort. +- Size limit: before a write, the least recently used `*.lpcd` files of every model in DIR are removed + until the new file fits. A restore updates the file's mtime. Entries the new prompt extends are + removed after the write and do not count against the limit. A write also needs its size + 1 GiB + free on the file system, so the cache never fills the PVC. +- Disabled with speculative decoding, with a warning: the draft state is not saved. + +**Invariants that must hold.** +- Never restore while cold or without the GPU token (`disk_cache_load` returns when `vram_cold`). + `get_available_slot()` runs on the loop thread after the wake, like the RAM cache's `prompt_save`. +- Copy the state before `vram_share_exit()` (it discards the device buffers) and write after it (the + token is not held for disk IO). +- Never serve a file that fails the size or hash check. Never mmap the file: a DMA into a shared + mapping is what livelocked upstream's version on AMD. +- A write is atomic (tmp + rename), and any IO error leaves the server serving and the exit clean. +- The key must cover everything that changes the state layout or the KV values. Add a new + state-changing parameter to `disk_cache_key()`. +- `llama_context_restore_memory_host()` is for exit only; the wrapped buffers point into the shadows, + which must outlive them (both are members of the same memory object). + +**Failure modes and incidents.** +- Production incident (2026-10-25, deploy of cb48bf224 with `--cache-disk-path`, rolled back): the first + request to the 35B aborted in `disk_cache_load()`. `server_tokens::get_tokens()` has + `GGML_ASSERT(!has_mtmd)`, and `has_mtmd` is true whenever an mmproj is loaded, even for text-only + prompts. Production's 35B and gemma-26B always load one (`-hf` pulls it; there is no + `--no-mmproj`). `disk_cache_collect()` and `save()` had the same call, so the shutdown save would + have aborted too. Every test had used `--no-mmproj` (`q35.py` and `--diskcache`), which hid it. + Fixed: the feature takes the token list from `get_text_tokens()`, and a prompt is text-only when + that list is as long as `size()` (`disk_cache_text`). A text-only prompt is cached with an mmproj + loaded. A prompt with media is never saved or restored. When the slot itself holds media, its reuse + estimate is `get_common_prefix()`. Lesson (runbook section 6): test with production's exact command line. +- The first run of the cold case crashed (exit 139). The crash was in the CPU-only release itself + (CPU_REPACK, F4), not in the save. +- The first version of the cold save copied the shadow into a new CPU buffer: a second copy of the full + KV allocation at exit (about 2.7 GB for the 35B at ctx 131072) on a node that has had an + OOM-controller kill. Replaced by the in-place wrap. The 32-byte alignment that + `cpu_buffer_from_ptr` asserts is met by rounding the base down; those leading bytes are never read. +- Writes to `/tmp` (node overlay) stalled once: 5.8 s for 64.5 MiB, against 171 ms normally. +- Costs to know about. llama-swap v239 waits for the old process to exit before it starts the next + model, and SIGKILLs a child still there 30 s after SIGTERM (measured 2026-10-25 with a scratch + llama-swap and dummy upstreams: term to exit 4.0 s, next start 2 ms later; a child that ignored SIGTERM + was replaced at +30.0 s). So the exit write adds directly to a model switch: about 1 s per GB on the + `/root` PVC (0.66 GB/s with fdatasync). A save cut off by the SIGKILL leaves only a `.tmp`. +- Only slots are saved. A conversation that sits only in the RAM cache when the process stops is lost. +- Every deploy empties the cache (the key holds the build commit), and so does any change to the + model file or the flags in the key. + +**Rebase hazards.** +- `server_context::start_loop` and `vram_share_exit` ordering (F7); `get_available_slot` and the RAM + cache (`prompt_save`, `prompt_load`, `server_prompt_cache_state`); `server_prompt` and + `common_prompt_checkpoint` fields (new fields must be saved, or the format version bumped). +- The checkpoint rollback in `update_slots` (`pos_min_thold`, `TAG_PROMPT_LOGITS`), which decides how + much of a restored file is reused. +- The llama state format (`state_write`/`state_read` of the memory types). The key holds the build + commit, so a format change cannot load an old file; it only empties the cache. +- `llama_memory_i::restore_device_buffers` and the shadow layout of F4 (`device_buffer_shadow`): + `llama_memory_wrap_host` relies on the compact iteration-order shadow. +- Flag names in `common/arg.cpp`. + +**Validation.** `fork-validate.sh --diskcache` (2c6c517ba), beside production. The model is the small +hybrid, CPU only (`-dev none -ngl 0`), with chat requests and greedy decoding, and a reference server +that never restarts. Cases: `restore`, `restore-arbiter` and `restore-cold` (turn 1, SIGTERM, restart, +turn 2 restored; prompt_n equal to the reference; identical answer), `no-prefix`, `key-ctx`, +`key-ctk`, `key-model`, `corrupt` (truncated and byte-flipped), `lru`, `write-error` (RLIMIT_FSIZE, +SIGXFSZ ignored), `restore-mmproj` (the same restore with the 0.8B's mmproj loaded), +`mmproj-image`, `log-scan`, and `gpu-warm`/`gpu-cold` when 1536 MiB of VRAM is free. +`mmproj-image` sends an image (answered "red", not restored), then the text chat (restored, identical), +then an image again, and SIGTERMs with media in the slot (no state copied, exit 0). First run +(2026-10-25, beside production, candidate build of this branch): 11 PASS, 0 FAIL, 1 SKIP (GPU: 1219 +MiB free). After the mmproj fix (beside production, 5.3 GB VRAM free): 15 PASS, 0 FAIL, 0 SKIP. + +| case (Qwen3.5-0.8B, CPU) | state + checkpoints | copy | write | exit (no cache: 125 ms) | read + restore | turn 2 vs full prefill | +|---|---|---|---|---|---|---| +| 573-token chat | 64.5 MiB, 2 ckpt | 18 ms | 171 ms | 314 ms (token free 56 ms vs 28) | 166 + 3 ms | prompt_n 58 of 596, 462 vs 2913 ms | +| 2.9k tokens | 92 MiB | 37 ms | 170 ms | 376 ms | 157 + 6 ms | 35 tokens, 408 ms | +| 12k tokens | 200.7 MiB | 110 ms | 350 ms | 641 ms, peak RSS +162 MiB | 307 + 18 ms | 35 tokens, 1.2 s vs 72 s | + +Swapdown window (2026-10-25, started by the owner, `/root/arms/diskcache-window.sh`): +`--diskcache --arbiter` 29 PASS, 0 FAIL, GPU legs included. + +35B (`q35.py`, the production 35B flags but WITH `--no-mmproj`, unlike production, which hid the +incident above; `--cache-disk-path` on a scratch dir, arbiter env, an 18760-token pan-tadeusz chat; +log `/root/arms/diskcache-test/q35.log`). `q35.py` now uses the exact production entry (`-hf`, so +the mmproj loads, nothing extra). That run (`/root/arms/diskcache-window3.sh`, about 8 minutes under +swapdown, which also covers the same-reuse-point identity and an image request on the 35B) was run +2026-11-21 on adc2aa3ec (log `/root/arms/diskcache-test/q35-mm.log`) and passed all legs: 18.8k-token +chat, prefill 84.6 s -> 4.7 s for turn 2 after the restart with identical output; save 557 MB in +1.0 s, token free 0.34 s, peak RSS +430 MB; cold save identity; image answered and not saved. The +table below is the earlier `--no-mmproj` run: + +| leg | result | +|---|---| +| turn 1 prefill (reference and candidate) | 18760 tokens in 83.4 s (224.8 t/s), outputs identical | +| warm save on SIGTERM (a) | 556.5 MiB (2 checkpoints), copy 323 ms, write 960 ms; token free in 328 ms (6 ms without the cache), exit 1952 ms (607 ms without), peak RSS +430 MiB | +| restore after the restart (b) | read 860 ms, restore 114 ms; turn 2 prompt_n 27 of 18850 in 3.0 s (the reference that never restarted: 27 in 2.0 s); output identical | +| cold save on SIGTERM (b, KV in the host shadow) | 746.7 MiB (5 checkpoints), copy 310 ms, write 1403 ms, exit 2928 ms, peak RSS +432 MiB: the in-place wrap adds no copy | +| restore of the cold save (c, turn 2 sent again) | read 1189 ms, restore 75 ms, prompt_n 4; output differs from the reference's turn 2 (see below) | + +Two anomalies in leg c, both explained: +- Output != reference: c sent turn 2 again, so the saved list (turn 2 + 63 generated tokens) extends + the new prompt. `update_slots()` then rolls back to the checkpoint at the prompt end minus 4 and + processes 4 tokens, while the reference processed turn 2 from turn 1's state (27 tokens). These are + different reuse points, not the same computation. The controlled test on Qwen3.5-0.8B + (`/root/arms/diskcache-test/cmp.py`) compares the same reuse point. Server X never restarts and + runs turn 1, turn 2, then turn 2 again. Server Z runs turn 2 again after a disk restore, a forced + cold save and a second restore. Z == X, text and top-3 logprobs bit-identical, on CPU and on the + GPU (`-ngl 99`); turn 2 and turn 2 again also agree there. The same check on the 35B needs the GPU + to itself: `/root/arms/diskcache-window3.sh` (production command line, reference "turn 2 again" against + leg c; about 8 minutes under swapdown). It ran 2026-11-21 and passed (same-reuse-point identity: + identical output), so the difference above is the reuse point. It supersedes + `diskcache-window2.sh`, whose `cmp.py` runs with `--no-mmproj`. +- Exit peak RSS +3055 MiB and token free in 1881 ms (leg a: +430 MiB / 328 ms): a test harness bug. + The driver's fake waiter was `flock -s want.lock sleep 120`; killing flock left `sleep` holding + want.lock (flock(1) keeps the lock fd open in its child). So c had a permanent waiter, slept right + after its load and again right after its request (log 0.37.50). That ordinary arbiter release + recaptures the full KV allocation as a host shadow, about 2.6 GB at ctx 131072 (F4), and the SIGTERM + arrived during it. The cache's own save then ran as a cold save (copy 305 ms, no extra copy). The + driver now holds the lock in the process it kills, like `fork-validate.sh` does. + +Configuration (applied in production 2026-11-21): `--cache-disk-path /root/prompt-cache +--cache-disk-size 4096` appended to the `moe_offload_args` and `moe_offload_gemma` macros in +`/root/config.yaml` (backup `/root/config.yaml.bak-diskcache-20261121`). The directory is created on +first start. Verified in production: a 35B 4.6k-token chat was saved on eviction (278.6 MiB, copy +126 ms, write 495 ms), restored after the reload (read 416 ms, restore 33 ms), and turn 2 prefilled +only 32 tokens; a gemma image request with the flags on works and is not cached. `/root` had 11-13 GB free on 2026-10-25, and the 1 GiB free-space floor still +applies. Models only pick up the flags when they restart. + +### F12. Temporary upstream carries (open upstream PRs, drop when merged) + +**What and why.** Open upstream PRs carried unchanged until upstream merges them. Each carry is one +commit whose subject starts with `upstream-carry #:`; the author is the PR author, and the body +names the PR URL and the PR head that was carried. List them with +`git log --oneline --grep '^upstream-carry' origin/master..HEAD`. They are not fork features: never +edit them in place, re-fetch the PR instead. + +Carried since 2026-11-22 (both on upstream `e6d624b9a`, for Inkling-2-Mini, section 5): +- #32735 `vulkan : support non-contiguous src in SCALE` (head `0ea4ffd00`): the Vulkan backend runs + SCALE on a non-contiguous source instead of rejecting it. +- #32740 `ggml: compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan` (head + `808fd1c4e`, four PR commits squashed): Inkling's per-query bias table (`[n_bins, n_head, + n_tokens]` plus an I32 bin index per key) is applied inside the flash-attention kernel. Before it, + the graph gathered the bias into a dense per-head mask (`n_kv x n_tokens x n_head`, F32, added to + the KQ mask and cast to F16) and passed that to FA, and the Inkling layers could not use the + `kv_rows` cell lists (dense masks only). Vulkan + binds the table and the indices in the two mask_opt descriptor slots, so `use_mask_opt` gets + `!bias` (F2). Vulkan supports it only for F16 K/V, head size 64 or 128, with subgroup shuffle and + vote (RX 580 RADV has both; Inkling is f16 KV, head size 128). + +State after the 2026-11-22 rebase onto `5bacb7c86` (branch `fable5/vram-ondemand-rebase-20261122`): +- #32735: merged upstream as `8a97fa98a`, patch identical to the carried head. Carry dropped. +- #32740: still open, but the PR was split on maintainer request (one backend per PR). Its head + `8c6f0c0ca` (8 commits) is now only the GGML contract: `ggml_flash_attn_ext_add_indexed_bias`, + a CPU reference (the CPU backend now accepts indexed bias) and test-backend-ops cases (the + standalone `test-flash-attn-indexed-bias` is gone). `be0bf1fbd` removed the Vulkan support + (supports_op returns false for `src[5]` or indexed bias), `9cd195304` moved the CUDA/HIP kernels + and the Inkling graph changes (`llama-graph.cpp`, `llama-kv-cache.cpp`, `inkling2.cpp`) out of + it. No open PR carries the Vulkan part (Metal is #32808). The contract also changed in wording: + the bias is added "in F32" (before: "before its F16 rounding"); the API and the `src[6]`/`src[7]` + layout are the same. **Decision: the carry of head `808fd1c4e` is kept unchanged.** Carrying the + new head would remove the Vulkan kernel and the graph use, so Inkling would fall back to the + dense mask: compute buffer about 15.8 GiB at ctx 65536 instead of 7 GiB, and the k=4 placement of + F13 would no longer fit. Owner: decide whether to keep carrying `808fd1c4e` until a Vulkan + follow-up PR appears, or to port the Vulkan part onto the new contract. Once the contract merges + upstream, the carry will conflict with it in `ggml.h`, `ggml.c`, `ggml-cpu/ops.cpp` and every + backend's supports_op, and has to be reduced to the Vulkan and graph parts by hand. +- #32777 `fit : prioritize looped MoE layers in device memory` (head `01945dcb0`) was carried on + `-20261122` only and dropped on 2026-11-23 (section 2, "Removed on 2026-11-23"). Its result, + for the record (window of 2026-11-23, log `/root/arms/overnight2/done/35-fit.log`): with the + mmproj margin emulated by `--fit-target 1850` (`llama-fit-params` rejects `--mmproj` and + `--jinja`), fit placed loop layers 6, 7 and the up experts of 8 on the GPU (k of about 2.3, + ranking right, stopping early because its margin is larger than the 868 MiB that k=4 leaves). + Server at ctx 65536: 13.9K-token prefill 93.4 t/s against 96.6 with k=4; llama-bench K F F K: + pp2048 @ d8192 102.57 / 99.58 / 99.52 / 102.34, tg256 @ d4096 6.95 / 5.67 / 6.28 / 6.65 (fit -3% + prefill, -12% decode). If the PR merges upstream, the k=4 `-ot` line in the config still + overrides fit (fit refuses to run with a user `-ot`). + +Measured on the RX 580 (2026-11-21, the previous PR head: `1fa93f902`, `d29f9d489`, `ff91e4f84`, +without `808fd1c4e`; base `3bf6b55b3` vs base + both PRs; logs `/root/arms/pr-out/` on the pod): +- Inkling pp2048 at ub1024: 91.6 -> 110.5 t/s. pp2048 at depth 16384 (ub512): 48.4 -> 73.0 t/s. +- Inkling compute buffers at ctx 131072, ub512: Vulkan0 12918 -> 7173 MiB, Vulkan_Host + 12729 -> 398 MiB. At ctx 65536 the base build already reserved 15866 MiB of Vulkan0 compute (more + than the card; the driver places the excess in GTT). With the carry: 6981 MiB. +- No regression elsewhere: Qwen 35B pp2048 286.5 -> 287.9, pp2048 at 16k 208.0 -> 208.5; + gemma-26B 249.4 both. +- test-backend-ops on Vulkan0: SCALE 15/15, FLASH_ATTN_EXT 5693/5693. +`808fd1c4e` (the PR head since 2026-11-22) changes the table layout from `[n_head, n_bins, n_tokens]` +to `[n_bins, n_head, n_tokens]`, which removes one permute+cont from the Inkling graph. + +Measured with the carried head (2026-11-22, candidate `3621025e8` vs production `3bf6b55b3`, +production's Inkling command line with the nothink sampling, GPU to itself; driver +`/root/arms/carry1122-ink-direct.py`, logs `/root/arms/carry1122-p2.log`, `-p3.log`): + +| build, args | 8.2K-token prefill | 13.9K | 28.4K | process VRAM / GTT after load | +|---|---|---|---|---| +| production, ub512, ctx 65536 | 32.7 t/s | 31.6 | 29.5 | 7209 / 28113 MiB | +| carry, ub1024, ctx 131072 | 43.7 | 42.5 | 42.5 | 7983 / 21835 MiB | +| carry, ub1024, ctx 65536 | 46.8 | 46.9 | 46.0 | 7368 / 19629 MiB | + +- Device memory wanted (`-lv 4` breakdown): production ub512/65536 19424 MiB (compute 15866); carry + ub1024/131072 13388 MiB (model 1266, context 4419, compute 7702), host compute 798 MiB. Everything + above the 8 GB card lands in GTT (system RAM over PCIe): about 5.2 GB at 131072. That costs about + 8% prefill against 65536, so production runs ub1024 with ctx 65536 (section 5) until the loop-layer + experts move into VRAM, which needs that headroom. +- Answers: a ~160-token first request on a fresh server (upstream #32778, all-'?' output) was + correct on every build. Pan Tadeusz fragments of 8.2K and 13.9K tokens gave coherent, correct + summaries on every build (upstream #32755 did not reproduce). The nothink entry + (`--reasoning-effort none --reasoning-budget 0`) returns repeated + `<|message_model|><|content_thinking|><|end_message|>` as content, with no tool call, for an image + request, a tool call and a 28.4K-token weather log ("which station is in Record 5?"). This happens + on every build, production `3bf6b55b3` with ub512 included, with and without + `GGML_OP_OFFLOAD_MIN_BATCH=64`, so the carry did not cause it. The think entry gets all three + right on both builds (image "Red", `get_weather({"city":"Warsaw"})`, 28.4K log "65" at 45.9 t/s + in production). Short text prompts work on the nothink entry. +- Nothink fix (2026-11-22, config only): the cause was `--reasoning-budget 0`. With effort `none` + and no budget the model still writes a short reasoning block (100-550 characters) and then + answers; a budget of 0 cut that block off at once and the model looped on the chat-structure + tokens. The macro is now `--temp 1.0 --top-p 1.0 --top-k 0 --min-p 0.0 --reasoning-effort none`. + Verified on production `3621025e8` (pod driver `/root/arms/overnight/nothink.py`, logs + `nothink1.log`, `nothink2.log` there): short question, Polish poem, image ("Red"), tool call + (`get_weather({"city":"Warsaw"})`) and a 29.4K-token Pan Tadeusz prompt (correct, 46.0 t/s) all + OK. Effort `minimal` and a budget of 256 also work; the budget of 0 fails on all but the short + question. + +**Rebase hazards.** +- At each rebase, check every carry first (runbook section 1): merged upstream -> drop the carry + commit; still open -> compare `git diff ` and re-carry the current + head if it moved; closed unmerged -> decide with the owner (Inkling's prefill and memory depend on + #32740, section 5). +- #32740 conflicts with F2 on `use_mask_opt` in `ggml_vk_flash_attn`. The resolution: upstream's + `!use_sparse`, the PR's `!bias &&`, the fork's GCN `HSK >= 256 || HSV >= 256` and its comment. + When the PR is merged and the carry dropped, the same line conflicts again when F2 is re-applied + on top; resolve it the same way. +- #32740 changes `llama_kv_cache::set_input_relative_pos` (new `rows` argument) and the + supports_op of every backend; a fork change in those places must follow it. + +**Validation.** `test-backend-ops -b Vulkan0 -o SCALE` and `-o FLASH_ATTN_EXT` (check the case +count), and the PR's own test `tests/test-flash-attn-indexed-bias` (build target +`test-flash-attn-indexed-bias`; it runs every device, prints one line per case it ran and skips +unsupported cases silently, so count the `Vulkan0:` lines: 16 f16 cases on the RX 580, max error +about 1e-4. The 4 Q4_0 K/V cases run on no backend here, and the CPU backend rejects indexed bias +(the graph then uses the dense mask), so it prints no CPU lines). +Then an Inkling request through llama-swap. + +### F13. Per-pass views of host weights in looped layers (inkling2_loop) + +Branch `fable5/inkling-loop-views` (on top of the F12 carries), fast-forwarded into the production +branch on 2026-11-22 (deploy and results below). + +Since F1 was removed (2026-11-23), every ubatch of 32+ tokens takes `sched_copy_experts`' routing +readback and uploads only the selected experts per pass; the mentions of F1 below describe the +conditions of the measurements made before that. The per-pass views are what keep this path correct +with `LLAMA_LOOP_FULL_COPY=0` (the path the 32-63-token window always took). + +**What and why.** `inkling2_loop` (Inkling-2-Mini) runs the core layers 6..17 three times; the 48 +cache slots are 24 physical layers plus 2 x 12 repeats. `post_arch_tensors` makes every repeat slot +share the tensors of its physical layer (`layers[il] = layers[phys]`). With the experts in host +memory (`--n-cpu-moe 24`, `-ot exps=CPU`), `ggml_backend_sched` makes one device copy per (host +tensor, backend) per graph, hashed by tensor pointer, at the first split that reads it, and keeps it +allocated until the last reader (`ggml_backend_sched_split_graph`, pass 5 and the graph_copy input +nodes). Two consequences: +- Memory: the expert copies of all 12 loop layers are alive at the same time (about 547 MiB per + layer on UD-Q4_K_XL, 6.5 GiB in total). That is most of the ~7 GiB Vulkan0 compute buffer in the + F12 measurements. +- Correctness (upstream issue #32755, "GGGG" output): the copy callback (`sched_copy_experts`, + F1) runs once, for the first reader. When it reads the routing ids back (ubatches below the F1 + skip threshold of `4 * n_expert` ids, and at or above the Vulkan MUL_MAT_ID offload batch of 32 + tokens: 32-63 tokens on Inkling-2-Mini), it uploads only the experts pass 0 selected. Passes 1 and + 2 reuse that copy and read stale VRAM for every other expert. Ubatches of 64+ tokens are correct + (F1 uploads every expert), ubatches below 32 run MUL_MAT_ID on the CPU (no copy). + +**Where.** `src/llama-model.h` (`llama_model::post_load_tensors`, a new optional hook), +`src/llama-model.cpp` (`llama_model_base::load_tensors` calls it on the no_alloc return and after +`load_tensors_hadamard()`), `src/models/models.h` and `src/models/inkling2-loop.cpp` +(`llama_model_inkling2_loop::post_load_tensors`, member `ctx_visits`). Commit 312c29c2b. + +**How it works.** After the weights are loaded, for every slot of pass 1 and 2 (`il >= n_phys`), each +tensor pointer in its `llama_layer` (walked as an array of pointers, as `llama_context::opt_init` +does) that sits in a host buffer (`ggml_backend_buffer_is_host`) is replaced with +`ggml_view_tensor` of it, named `.visit`, initialized with `ggml_backend_view_init` +(same buffer and data). On the no_alloc pass (memory fit) only `view->buffer` is set to the dummy +buffer, so the scheduler still sees a WEIGHTS buffer. The view is a leaf (op NONE, `view_src` set), +so the scheduler hashes it separately: each pass gets its own copy, freed after the last reader of +that pass, and the copy callback sees the MUL_MAT_ID of that pass and its ids (`st.ids` differs, so +F1 recomputes the expert set). The pointer-keyed weight maps of `llama_model` (`w_scales`, +`prec_policy.prec_acc`/`prec_src1`, `hdmd.rot`) get entries for the views. The views live in +`ctx_visits`, a context of the model outside `ctxs_bufs`. The startup log prints +`post_load_tensors: N views of host weights for the loop passes after the first (X MiB, not copied)`. + +Knob: `LLAMA_LOOP_HOST_VIEWS=0` keeps the shared tensors (the upstream behaviour), read once at load. +Default on. + +**Invariants that must hold.** +- Only host buffers get views. Device weights stay shared (used in place, no copy, so no problem), + and so do CPU extra buffers (CPU_REPACK is not a host buffer; its ops run on the CPU in place). +- F4: views point only at host buffers, which `release_device_weights` never releases, and they + are not in `ctxs_bufs`, so the shadows, `weight_release`, `memory_breakdown`, `n_tensors()` and + `tensors_by_name` do not see them. A device weight is released and restored in place, and the + loop slots keep pointing at the same tensor. +- The routing readback is per copy and keys on the ids tensor of the first node of the split, so + it stays per pass. +- `llama_layer` must hold only `ggml_tensor *` members (a `static_assert` checks the size only). + +**Cost.** Pass 1 and 2 now upload their own experts: per ubatch the host-to-device expert traffic +goes from 24 to 48 layer uploads (about +13 GiB per full ubatch on UD-Q4_K_XL). Measured where the +old layout still fits in VRAM (llama-bench pp2048 at depth 0, `-ncmoe 24`, B C C B in one window): +views 107.10 / 107.53 t/s, off 110.80 / 111.53, so -3.5%. Decode is unaffected (single-token +MUL_MAT_ID runs on the CPU). In the server at 16k-65k context the old layout does not fit (7 GiB of +compute buffer), spills into GTT, and the views win about 1.6x at prefill (Measured, below). The +freed ~6 GiB of VRAM can hold experts instead: an expert tensor of a loop layer kept on the GPU +saves 3 uploads per ubatch and 3 CPU expert passes per token, a non-loop one saves 1, so loop layers +are the first to move to the GPU (`-ot` with the loop layers left out of the CPU pattern; placement +guide below). + +**Measured (2026-11-22, pod, GPU to itself, build `b13c41355` = 312c29c2b + docs; drivers and logs in +`/root/arms/overnight/`: `f13.py`, `cmp.py`, `kld48.sh`, `fit.py`, `sweep.sh`, `STATUS.md`).** +- Memory, server with the production command line at ctx 16384, `-lv 4`: Vulkan0 compute buffer + 1426 MiB with views, 7030 MiB without. Process VRAM after load: views 4179 MiB, off 7727, A + (loop experts on the GPU, no views) 7879 (A wants 10089 MiB and spills). +- Prefill, server, 7224-token raw prompt at ctx 16384: views 92.4 t/s, off 57.0, A 46.5 (production + at ctx 65536 without views: about 46). +- Correctness. First-token top-5 logprobs (`f13.py`, `n_probs 5`, knob 32 so the 32-63 window is + live): with the tail at or above 64 or below 32 tokens (N = 20, 100, 7368) views on and off are + identical (max difference 0.000); in the window (N = 40, 63, 1072, 7224) they differ (0.04-0.16). + That test cannot say which arm is right: arm A differs from both by up to 0.15 even at the + controls (different placement, different kernels), and at 32-63 tokens x 8 experts pass 0's + union already covers most of the 128 experts, so the stale copy is mostly correct data. The + decisive test is `kld48.sh`: `llama-perplexity -c 48 -b 48 -ub 48`, 30 chunks of Pan Tadeusz, so + every chunk is one 48-token ubatch, KL divergence against a base with views on and knob 64 (the + tail MUL_MAT_ID on the CPU, correct by construction): + + | arm | mean KLD | max KLD | same top token | RMS dp | + |---|---|---|---|---| + | views on, knob 32 (tail on the GPU) | 0.00314 | 0.087 | 97.4% | 1.35% | + | views off, knob 32 (tail on the GPU) | 0.03163 | 0.347 | 92.2% | 3.71% | + | views off, knob 64 | 0.00000 | - | 100% | 0.00% | + + Views on is at the GPU-vs-CPU kernel noise level; views off is 10x worse (the #32755 mechanism, + reproduced). So with F13 the `GGML_OP_OFFLOAD_MIN_BATCH=64` workaround is no longer needed. + +**Placement guide (UD-Q4_K_XL, views on).** k = number of loop layers (6, 7, ...) whose experts stay +on the GPU: `-ot 'blk[.]()[.]ffn_.*_exps=CPU'` instead of `--n-cpu-moe 24` +(`/root/arms/overnight/mkot.py` and `cfgedit.py` write the pattern; `[.]` avoids backslashes in the +YAML and in llama-swap's argument splitting). Each loop layer's experts take 547 MiB. Fit, from the +`-lv 4` breakdown of a server with the production command line (mmproj on demand, so not loaded): + +| ctx | k | Vulkan0 self (model + context + compute) | free | verdict | +|---|---|---|---|---| +| 32768 | 0 | 4136 (1266 + 1347 + 1522) | 3982 | fits | +| 32768 | 6 | 7416 | 699 | fits | +| 32768 | 7 | 7963 | 15 | too tight | +| 65536 | 4 | 7246 (3453 + 2371 + 1421) | 868 | fits, chosen | +| 65536 | 5 | 7793 | 128 | too tight for the mmproj | +| 65536 | 6 | - | - | spills (GTT about 900 MiB above expectation) | +| 131072 | 0 | 7784 (1266 + 4419 + 2098) | 134 | fits (before F13 it overcommitted 5.2 GB) | +| 131072 | 2 | - | - | spills (about 1.2 GB) | + +fdinfo `drm-memory-gtt` is not the spill test: it includes the pinned host weights +(Vulkan_Host). Compare GTT(k) with GTT(0) - k x 547 MiB, or read the breakdown. + +Speed, llama-bench, one invocation per metric (`sweep.sh`, `-fa 1 -t 6 -b 1024 -ub 1024`, knob 64, +pp r1, tg r2): + +| k | pp2048 @ d8192 | pp2048 @ d16384 | tg256 @ d4096 | +|---|---|---|---| +| 0 | 97.53 | 89.62 | 5.57 | +| 4 | 102.19 | 93.90 | 6.45 | +| 6 | 104.43 | 95.27 | 6.72 | +| 7 | 105.90 | 96.90 | 7.25 | + +Decode gains most (+16% at k=4, +30% at k=7): every loop layer on the GPU removes 3 of the 48 CPU +expert passes per token. Prefill gains only 5-9%: at depth the attention and the remaining uploads +dominate. + +**Quants (2026-11-22, not adopted).** Unsloth's Mainline_Support UD-Q3_K_XL (13.6 GB) and UD-IQ3_XXS +(11.7 GB) are in `/root/models/inkling/`. Quality: `llama-perplexity -c 2048 --chunks 4`, KL +divergence against UD-Q4_K_XL logits (`kld.sh`), on a fixed Pan Tadeusz chunk +(`/root/bench/entext/pt-chunk.txt`, characters 20000-100000) and wikitext-2 test: + +| text | quant | PPL (Q4_K_XL) | PPL ratio | mean KLD | same top token | +|---|---|---|---|---|---| +| Pan Tadeusz | Q3_K_XL | 11.45 (11.30) | +1.4% | 0.0241 | 92.5% | +| Pan Tadeusz | IQ3_XXS | 11.52 (11.30) | +1.9% | 0.0421 | 90.1% | +| wikitext-2 | Q3_K_XL | 6.251 (6.230) | +0.3% | 0.0097 | 95.6% | +| wikitext-2 | IQ3_XXS | 6.307 (6.230) | +1.2% | 0.0214 | 94.2% | + +Fit at ctx 65536: UD-Q3_K_XL keeps the loop-layer experts at 547 MiB each (like Q4), so k=5 (867 +MiB free); UD-IQ3_XXS has 390 MiB per layer, k=7 (952 MiB free). Speed (separate invocations, so +within the ~7% cross-run noise for prefill): Q3_K_XL k=4 105.23 / 6.83, k=6 107.31 / 7.48; +IQ3_XXS k=4 105.59 / 6.44, k=7 108.48 / 7.86 (pp2048 @ d8192 / tg256 @ d4096; Q4_K_XL k=4 +102.19 / 6.45). The best case, IQ3_XXS at k=7, is +6% prefill and +22% decode (about 7.9 instead +of 6.5 t/s) for a Polish KLD of 0.042; IQ3_XXS's CPU dot product is slower per byte (at k=4 it +decodes no faster than Q4). Not worth the quality loss for the owner's Polish use. + +**Production (deployed 2026-11-22, `b13c41355`, ctx 65536, k=4, no knob).** Through llama-swap +(`/root/arms/overnight/post.py`, log `post.log`): Pan Tadeusz 9312 tokens 81.6 t/s prefill, +7958 +tokens 89.3 t/s, +17255 tokens (28K total) 78.0 t/s, decode 5.9-6.0 t/s, answers correct (before: +about 46 t/s prefill). Think and nothink entries answer text, an image ("Red") and a tool call. A +tiny request after the 4B task model held the GPU takes 1.3-2.4 s longer than a warm one (the +arbiter restores 3.4 GiB of device weights). Disk cache save/restore works on Inkling (1329 tokens, +410 MiB). The first request on a fresh process is slow (162 tokens 11.7 t/s prefill, 2.6 t/s decode) +since the pipelines are compiled on first use (`--no-warmup`). + +**Profile (2026-11-22, `perf record` + `gpu_busy_percent`, `prof.sh`, results in +`/root/arms/overnight/prof/`).** Inkling k=4 prefill (pp2048 @ d4096, 107 t/s): GPU busy 77%, CPU +time mostly `ggml_vk_wait_for_fence` (43%) and the kernel (11%, the uploads): GPU-bound. Decode +(7.3 t/s): GPU busy 58%, CPU in the OpenMP barrier spin (libgomp 36%) and +`ggml_vec_dot_nvfp4_q8_0` (21%): the UD-Q4_K_XL experts are NVFP4, and that CPU dot product is the +decode hotspot. Qwen3.6-35B for comparison: prefill 263 t/s at GPU busy 52%, decode 13.8 t/s at +35%, `vec_dot_q4_K_q8_K` 10%. `GGML_VK_PERF_LOGGER=1` aborts at the second split +(`GGML_ASSERT(ctx->compute_ctx.expired())`, ggml-vulkan.cpp:15692), so it gives per-op GPU times +only for the first split; not investigated. + +**Failure modes and known limits.** +- LoRA adapters look weights up by name (`llama_adapter_lora::get_weight`), so they do not apply to + passes 1 and 2 with views on. Not used here; set `LLAMA_LOOP_HOST_VIEWS=0` for a LoRA on Inkling. +- `--moe-cache-mib`: the cache binds expert tensors per slot (`llama_moe_cache_layer_experts` of + `model.layers[il]`), so with views each loop slot gets its own binding and slot map and caches the + same experts separately (before, the three slots collided on one binding key). Should not crash; + not tested. The MoE cache is off in production. +- Model saving is not supported for `inkling2_loop` (`llama_arch_supports_save`), so duplicate data + in a saved file cannot happen. + +**Upstream #32807 (in `5bacb7c86`, branch `-20261122`).** Upstream's fix for #32755: in +`sched_copy_experts`, after the first-node check and before F1's logic, `if (arch == +LLM_ARCH_INKLING2_LOOP) return false;`, so the scheduler copies every expert of a shared host +weight (a TODO points at per-pass copies; the scheduler-side alternative #32809, "copy host experts +again for each split that reads them", was closed unmerged). That fixes correctness but keeps one +device copy per (host tensor, backend) per graph, alive until the last pass: the 6.5 GiB of held +copies and the ~7 GiB compute buffer stay. So F13 is still needed for memory; for correctness +it is now redundant with upstream's guard. +- With both, each pass uploads its own copy (F13) and every copy is a whole tensor (the guard): + in the 32-63-token window the readback path, which would upload only the selected experts, no + longer runs. Ubatches of 64+ tokens are unchanged (F1 copies every expert anyway), below 32 the + experts run on the CPU. +- Knob (fork, commit "env knob LLAMA_LOOP_FULL_COPY=0"): `LLAMA_LOOP_FULL_COPY=0` skips upstream's + guard. Only correct with the views on: with `LLAMA_LOOP_HOST_VIEWS=0` it brings #32755 back. +- On this branch, "upstream's fix alone" is `LLAMA_LOOP_HOST_VIEWS=0` (shared tensors plus the + guard), "F13 plus upstream" is the default, "F13 alone" is `LLAMA_LOOP_FULL_COPY=0`. + +Window A/B to run (GPU to itself, candidate build, Inkling production command line): +1. Memory: process VRAM/GTT after load and the `-lv 4` breakdown at ctx 65536 with production's + k=4 `-ot`, default vs `LLAMA_LOOP_HOST_VIEWS=0`. Expected: upstream-only spills (compute about + 7 GiB, as before F13); F13 fits with about 0.8 GiB free. +2. Correctness: `/root/arms/overnight/kld48.sh` (48-token ubatches, KLD against the knob-64 base) + for default, `LLAMA_LOOP_HOST_VIEWS=0` and `LLAMA_LOOP_FULL_COPY=0`. Expected: all three at the + GPU-vs-CPU noise level (mean KLD about 0.003); before #32807 views off gave 0.032. +3. Speed: llama-bench pp2048 @ d8192 and tg256 @ d4096 (`sweep.sh` settings) and a 48-token-tail + server prompt (the window where the guard costs uploads), default vs `LLAMA_LOOP_FULL_COPY=0`, + arms interleaved in one invocation (section 6). Keep the guard unless the knob wins clearly. + Then decide whether F13 stays (expected: yes, for memory). + +**Window A/B result (2026-11-23, pod, GPU to itself, candidate build `27c23d20f`; window scripts +`/root/arms/overnight2/win2.sh`, logs `/root/arms/overnight2/done/20-win2.log`, `kld48/`).** +Decision: F13 stays, and production sets `LLAMA_LOOP_FULL_COPY=0` on both Inkling entries. +1. Memory, production's Inkling command line at ctx 65536, k=4 `-ot`, `-lv 4`: + + | arm | Vulkan0 self (model + context + compute) | process VRAM / GTT after load | 13.9K-token prefill | + |---|---|---|---| + | default (F13 + guard) | 7246 (3453 + 2371 + 1421) | 7293 / 13797 MiB | 96.6 t/s | + | `LLAMA_LOOP_HOST_VIEWS=0` (upstream's fix only) | 10956 (3453 + 2371 + 5131) | 7729 / 17077 MiB (spills) | 45.8 t/s | + + The default logs `post_load_tensors: 64 views of host weights for the loop passes after the + first (8748.02 MiB, not copied)`. Upstream's guard alone fixes the output but keeps the held + copies: 2.1x slower prefill at depth. +2. Correctness, `kld48.sh` on the candidate (knob 32, 30 chunks, KLD against the knob-64 base): all + three arms (default, `LLAMA_LOOP_HOST_VIEWS=0`, `LLAMA_LOOP_FULL_COPY=0`) give the same numbers to + the last digit: mean KLD 0.003137, max 0.0874, same top token 97.39%, RMS dp 1.348% (the views-on + result of 2026-11-22). Each arm computes with correct expert data; they differ only in how much + is uploaded. +3. Speed, llama-bench k=4 `-ot`, `-fa 1 -t 6 -b 1024 -ub 1024`, arms D F F D (D default, F + `LLAMA_LOOP_FULL_COPY=0`), one invocation per metric per arm: + + | metric | D | F | F | D | + |---|---|---|---|---| + | pp2048 @ d8192 | 102.49 | 102.13 | 102.15 | 102.09 | + | pp48 @ d1024 (r3) | 15.86 | 27.91 | 27.78 | 15.78 | + | tg256 @ d4096 | 6.73 | 6.64 | 6.61 | 6.57 | + + The guard costs 43% of the throughput in the 32-63-token window (+76% with the knob): it uploads + whole expert tensors where F1's readback path uploads only the selected experts. Larger ubatches + and decode are unchanged. + +**How to drop it.** If upstream fixes #32755 (for example per-reader copies or a copy-callback call for +every reader in the scheduler, or real per-pass tensors in the loader), revert 312c29c2b; the hook has +no other user. Check that upstream's fix also bounds the copy lifetime, otherwise the 6.5 GiB comes back. + +**Rebase hazards.** `post_arch_tensors` and the loop slot layout in `inkling2-loop.cpp`; +`llama_model_base::load_tensors` returns (a new return path must call the hook); new pointer-keyed +weight maps in `llama_model` (they need a view entry like `w_scales`); non-pointer members in +`llama_layer`; scheduler changes to how host weights are copied (`hv_tensor_copies`, +`ggml_backend_sched_is_host_weight`). + +**Validation (pod, GPU to itself in a swapdown window).** Build `llama-server` and `llama-bench` +from this branch in a scratch worktree (runbook section 5). Use the Inkling command line from +`inkling_args` in `/root/config.yaml` (with `--mmproj`) and change only the context to 16384 (so +arm A fits) and the placement: +- A, reference: replace `--n-cpu-moe 24` with `-ot 'blk\.([0-5]|1[89]|2[0-3])\.ffn_.*_exps=CPU'` + (loop experts on the GPU, no copies for the loop; the views log line must not appear). +- B, views on: `--n-cpu-moe 24`; the log line must show the views. +- C, views off: B with `LLAMA_LOOP_HOST_VIEWS=0`. + +For each arm send raw token prompts (`/tokenize` a long text, cut to N tokens, `/completion` with the +token array, `temperature 0, top_k 1, seed 42, cache_prompt false, n_predict 32, n_probs 5`) at +N = 40, 63, 1072, 6176, 7224 (tail 32-63 at ub1024), controls N = 100, 7368 (tail >= 64) and 20. +Expected: +- B == A in the first token's top-5 probabilities for every N >= 32 (prefill MUL_MAT_ID runs on the + GPU in both arms with the same data). The generated text may drift later, since decode MUL_MAT_ID + runs on the GPU in A and on the CPU in B. +- B == C byte-identical for the controls (tail >= 64 or < 32). +- C differs from A at the 32-63 tails (the bug); if it does not, the bug was not reproduced and + B's result proves nothing. +- Vulkan0 compute buffer (startup log): B about 6 GiB below C. A's model buffer carries the loop + experts instead. +Then `llama-bench -lm none -ngl 99 -ncmoe 24 -fa 1 -t 6 -b 1024 -ub 1024 -p 2048 -n 0 -r 3`, with and +without `LLAMA_LOOP_HOST_VIEWS=0`, interleaved B C C B, medians (section 6), for the prefill cost +above. After a deploy: an Inkling text request, an image request, and the same text request after a +task-model call (arbiter handoff, F4), identical at temperature 0. + +--- + +### F14. User-message batch-break merge (one ubatch per short turn) + +Branch `fable5/userstart-split` (rebased onto the F13 production tip `166ec22e2`), fast-forwarded into +the production branch on 2026-11-22 (deploy and results below). Knob: `LLAMA_USERSTART_MERGE=0`. + +**What and why.** Upstream ends a prompt batch right before a user message so that a context +checkpoint lands there (#22929 for the last user message, #24176 for every user message, #25420 +limited the earlier ones to `--checkpoint-min-step`). On a hybrid/recurrent model the recurrent state +cannot be cut back, so a checkpoint is the only way to reuse a prefix; the one at the last user +message is what a later request uses when it diverges inside that message (the user edits it, or the +client injected per-request context into it, RAG/web search). Ordinary turns do not need it: Qwen's +template drops the previous answer's reasoning, which moves the divergence to just after +`<|im_start|>assistant\n`, below the end-minus-4 checkpoint (#20288), and that one is what turn N+1 +restores. The cost on this hardware: a turn processes `[previous answer | new user message + generation +prompt]`. With the break that is two ubatches instead of one, and with every expert on the host each +ubatch of >= 32 tokens (`GGML_OP_OFFLOAD_MIN_BATCH`) uploads the experts again: about 64-96% of them at 32-127 tokens +(routing readback; until 2026-11-23 F1 uploaded all of them from 128 tokens), about 2.8 s per full upload on +the 35B. The break also fires at the first user message of a fresh prompt (no checkpoints yet), +which splits off the system prompt. Tool results count as user messages (Qwen opens them with +`<|im_start|>user`, the detected delimiter). + +**Where.** `tools/server/server-context.cpp`, `update_slots`, the prompt-batch loop: +`merge_user_starts` before the loop and the `!merge_user_starts` term of the user-start break. +Commit 510aa6e09. On branch `-20261122` the refinement adds `first_user_pos` before the loop, and the +user-start break checks `merge_user_starts` first (merged: break only at `first_user_pos`). + +**How it works.** When the rest of the prompt from the current batch start fits in one ubatch +(`task.n_tokens() - prompt.n_tokens() <= n_ubatch`) and no media chunk was processed in this +iteration, the user-start break is skipped. The batch then runs to the end-minus-4 break: one ubatch +plus the 4-token tail, as for a prompt without user messages. Checkpoints left: the batch start +(the near-prompt-end rule; the batch ends at prompt end minus 4, so it always applies; it supersedes +the restored checkpoint at the same position, with the current task id, so the next request still +has it) and the prompt end minus 4. Lost: the one at the last user message. A later request that +diverges inside that message restores the batch-start checkpoint instead and re-processes the +previous answer too, less than one ubatch, in the same single ubatch, so no extra upload. Prompts +whose rest is longer than one ubatch keep the upstream breaks (there the break does not save the +whole of a ubatch, and the fallback would not be bounded). `LLAMA_USERSTART_MERGE=0` restores the +upstream behaviour everywhere. + +**Refinement: the system-prompt checkpoint (owner's wish, commit "F14 - keep the batch break at the +first user message", branch `-20261122`, not deployed).** The merged path keeps one user-start +break: the one at the first user message, which is the end of the system prompt. Upstream breaks +there on a fresh prompt (no checkpoints yet), and the plain F14 had dropped it, so a new chat with +the same system prompt found no checkpoint at the system-prompt end and re-processed the system +prompt (a hybrid/recurrent state cannot be cut back without one). Now, merged or not, a prompt +processed from before its first user message ends a batch there; the next batch starts at the +user message and gets a checkpoint (user-start batch, near-end rule). A later new chat with the same +system prompt diverges inside the first user message, restores that checkpoint and processes only +its own user message and the generation prompt. +- Only fresh prompts are affected: checkpoints past the restore point are erased on reuse, so the + batch reaches the first user message only when the prompt is processed from before it (a new + chat, or a changed system prompt). Follow-up turns start past it and keep the full merge, + including no break at the last user message (the edit cost below is unchanged). +- First user messages below 8 tokens are skipped (no system prompt, only a BOS before it). +- Cost: turn 1 of every new chat runs the system prompt as its own batch again. That was part of + the U arm's turn-1 layout below (TTFT 6.08 vs 3.99 s for M, which also merged the last-user + break; the system-prompt split alone was not measured). A system prompt of 32+ tokens runs on the + GPU with one extra expert upload, below 32 tokens on the CPU. +- Lifetime of that checkpoint: it is the oldest one of the slot. When the list is full + (`--ctx-checkpoints`, default 32), the min-step thinning keeps the oldest checkpoint and erases + later ones within `--checkpoint-min-step` (8192) of it, and only then the FIFO drops the oldest. A + very long chat can still lose it; the RAM prompt cache (and F11 on disk) keeps the earlier + conversation's copy. +- Disk cache (F11), read: `disk_cache_load` replaces the slot prompt only with an entry that + reuses at least `DISK_CACHE_MIN_TOKENS` (256) more of the new prompt, and `n_reuse` counts a + saved prompt that diverges inside it as its newest checkpoint at or below the divergence. A saved + chat therefore offers the system-prompt checkpoint to a new chat after a restart, but only for a + system prompt of 256+ tokens; it never replaces a better slot prompt. The checkpoints are saved in + the file appendix and trimmed to `--ctx-checkpoints` from the front on load (only if the file has + more). Nothing in it removes the break; check it in the window anyway (validation plan item 5). + +**Invariants that must hold.** +- The merge only applies when the rest fits in one ubatch: that bounds the extra re-processing on a + divergence inside the last user message to less than `n_ubatch` tokens. +- The batch-start checkpoint must still be created (near-prompt-end rule, `do_checkpoint` not cleared + by `has_mtmd`); hence the `!has_mtmd` condition. +- It only changes where batches end, never which tokens are processed, so outputs differ from an + unmerged run only by batch-composition rounding. + +**Measured (2026-11-22, pod, GPU to itself in one swapdown window, build `f3397cded`; driver +`/root/arms/usw_ab.py`, window script `/root/arms/usw-window.sh`, logs and `res.json` per arm in +`/root/arms/usw-ab/{M1,U1,U2,M2}/`).** Production 35B think entry (`q36t`: `${ctx_256k} +${qwen35_think_args} ${moe_offload_args}`, `-hf` pulls the mmproj, supervisord's environment, scratch +arena and `--cache-disk-path`, plus `-lv 4`), one fresh server per arm, arms M (merged, default) and U +(`LLAMA_USERSTART_MERGE=0`) in the order M U U M. Each chat: system prompt, 6 user turns from +`pt-chunk.txt` (150, 10, 40, 150, 600, 40 tokens), synthetic previous answers of 300, 800, 1200, 500, +1300 tokens, `max_tokens 8`, `temperature 0`, streamed; then the last user message edited in the +middle and resent. TTFT in seconds (mean of the two runs per arm; the single runs in brackets), +`prompt_n` was identical in all four runs on every turn: + +| turn | user tokens | prompt_n | M TTFT | U TTFT | M - U | +|---|---|---|---|---|---| +| 1 (fresh prompt) | 150 | 196 | 3.99 (4.43, 3.55) | 6.08 (5.73, 6.42) | -2.1 | +| 2 | 10 | 327 | 4.11 (3.75, 4.47) | 7.66 (6.75, 8.57) | -3.6 | +| 3 | 40 | 869 | 6.34 (6.62, 6.06) | 9.34 (7.26, 11.42) | -3.0 | +| 4 | 150 | 1381 | 7.20 (7.30, 7.10) | 10.95 (12.31, 9.58) | -3.7 | +| 5 | 600 | 1130 | 8.82 (7.47, 10.17) | 9.80 (9.52, 10.07) | -1.0 | +| 6 | 40 | 1370 | 8.11 (8.01, 8.20) | 9.53 (9.33, 9.72) | -1.4 | +| edit of turn 6 | 40 | M 1374, U 66 | 7.94 (8.16, 7.71) | 3.65 (4.09, 3.20) | +4.3 | + +- Batch layout (`prompt processing, n_tokens` and checkpoint lines at `-lv 4`): M runs every turn as + one batch `[restore point, end-4)` plus the tail, with checkpoints at the batch start (superseding + the restored one) and at end minus 4; U splits at the last user message (an extra checkpoint + there, for example 1323 between 515 and 1380 on turn 3) and on turn 1 also at the first user + message (system prompt, 23 tokens). Turn N+1 restores the end-minus-4 checkpoint of turn N in both + arms. No `forcing full prompt re-processing` in any run. +- The 10-token turn gained too, against the plan's "no change". U split it into 308 tokens (the + previous answer, on the GPU) and 19 (message, generation prompt and tail), and the 19-token part runs + the experts of all 40 layers on the CPU, which costs seconds rather than nothing at 6 threads + (inferred from the totals, not profiled). The 600-token turn gained + least (its two parts are 508 and 618 tokens, both on the GPU, so the split costs one extra + upload, about 1-2 s against noise of the same size). +- Edit of the last user message (the cost of the trade): M has no checkpoint at the user-message + start, restores the batch start and re-processes previous answer + message (1374 tokens, one + ubatch); U restores the user-start checkpoint and re-processes 66 tokens. +4.3 s per such edit. + Ordinary follow-up turns are far more frequent than edits of the last message in this use; a client + that injects per-request context into the last user message (RAG, web search) pays the same + as an edit on every turn, so set `LLAMA_USERSTART_MERGE=0` for such a client. +- Outputs: identical within each arm across runs; between arms turns 5 and 6 differ after a few + tokens (batch-composition rounding, as the invariant says). +- Disk cache: `fork-validate.sh --diskcache` (in the window, GPU leg included) 15 PASS, 0 FAIL, 0 + SKIP. `diskcache-window3.sh` legs with production's 35B command line (`q35.py` copied to + `q35-usw.py` with the candidate build path; log `/root/arms/usw-q35-mm.log`): 18.8k-token chat, + turn 1 83.5 s, save 557 MB in 1.0 s, restart restore and turn 2 `prompt_n` 27 in 3.7 s, output == + reference; cold save and restore identity (`prompt_n` 4, output == reference); image answered + 'Red' and not saved. The saved state after turn 2 holds 4 checkpoints instead of 5 (the user-start + one is gone). + +**Production (deployed 2026-11-22 10:37, `f3397cded`, config unchanged).** Deploy script +`/root/arms/dep-usw.sh` (log `dep-usw.log`): incremental in-place build, downtime 33 s. Post-deploy +checks through llama-swap (`/root/arms/post-usw.py`, `ink-usw.py`, `ink2-usw.py`, logs beside them): +`system_fingerprint` `b12687-f3397cded`; 35B 'Paris', then 4B / 35B handoffs twice (correct answers, +`holder` the answering PID each time, 2.9-6.3 s per switch); a 1140-token 35B chat, then a gemma-26B +image ('Red', the 35B exited by itself with `loop stopped, device memory freed` and `disk cache: +saved the prompt of 1157 tokens`), gemma text, 4B text, then the 35B chat plus one user message: +`disk cache: restored 1157 tokens`, `prompt_n` 30 (the suffix only). Inkling nothink: text correct +(it still spends about 40 tokens on reasoning, so a 96-token budget returns an empty content), image +'Red', a 9293-token Pan Tadeusz prompt at 82.0 t/s with the right answer (F13 measured 81.6). Children +bind llama-swap's ports. Log scan clean, `dmesg` clean (no ring timeout, GPU hang or OOM kill), pod +restarts 0 as before. + +**Failure modes and incidents.** None in validation or the deploy. Known cost: an edit of the last +user message (or per-request context injected into it) re-processes the previous answer too, +4.3 s +measured above. + +**Rebase hazards.** +- Upstream keeps reworking this loop (#20288, #22929, #24176, #25420): the user-start break, the + `checkpoint_offsets` breaks and the near-end / min-step checkpoint rules. Re-check that the batch + start is still checkpointed when the batch ends at prompt end minus 4. + +**Validation plan (run 2026-11-22, results under Measured above).** +1. Pre-check at trace log level (`SLT_TRC`; `-lv` high enough for `LOG_TRC`): per request, the + `created context checkpoint ... n_tokens = N` and `restored context checkpoint` lines. Merged: one batch + `[restore point, end-4)` plus `[end-4, end)`; `LLAMA_USERSTART_MERGE=0`: the extra break at the + last user message. +2. TTFT A/B through the production 35B entry (exact `moe_offload_args` command line, mmproj loaded), + candidate with and without `LLAMA_USERSTART_MERGE=0`, arms alternated in one run: scripted 6-turn + chats, user messages of about 10, 40, 150 and 600 tokens, previous answers 200-1500 tokens. Read + `prompt_n`/`prompt_ms` from the timings and TTFT from the stream. Expected: no change at 10 tokens + (the second part ran on the CPU), about -2 to -2.8 s per turn at 40+ tokens. +3. Reuse: turn N+1 must report the same `prompt_n` in both arms (restore from end-minus-4). Then edit + the last user message and resend: merged re-processes previous answer + message (bounded by one + ubatch), unmerged only the message; no "forcing full prompt re-processing". +4. Disk cache: `fork-validate.sh --diskcache` and `diskcache-window3.sh` (production command line): + restore after a restart, `prompt_n` and output identical to the reference built from the same + commit. + +Additions for the refinement (branch `-20261122`, to run in the window with the 35B think entry's +exact command line plus `-lv 4`, scratch port, arena and cache dir): +5. New chat #2 with the same system prompt. Chat 1: a system prompt of about 300 tokens (above the + 256-token disk-cache minimum), then 3 turns as in item 2. Expected at trace level on chat 1 turn + 1: a batch `[0, first user start)`, then a `created context checkpoint ... n_tokens = `, then the merged batch to end minus 4. Then chat 2: the same system prompt, a new + first user message. Expected: `restored context checkpoint ... n_tokens = ` + and `timings.prompt_n` = chat 2's user message plus the generation prompt only (not the system + prompt); no `forcing full prompt re-processing`. Follow-up turns of chat 1 must still run as one + batch (no break at the last user message): the M layout of the table above. +6. The same after a restart (disk cache): run chat 1, stop the server with SIGTERM (`disk cache: + saved the prompt`), start it again, send chat 2. Expected: `disk cache: restored`, then the + restore of the system-prompt checkpoint and the same `prompt_n` as in item 5. Also once with a + system prompt below 256 tokens: no disk restore is expected there (the minimum), only a fresh + prompt; that is the known limit, not a failure. +7. The 6-turn TTFT table of item 2 with the candidate, M only: turn 1 may be slower than 3.99 s + (the system-prompt split is back), turns 2-6 must match the M column within noise. + +Results of items 5-7 (2026-11-23, candidate build `27c23d20f`, the 35B think entry's command line +with the mmproj and `-lv 4`; drivers `/root/arms/overnight2/f14new.py` and `f14ttft.py`, logs +`/root/arms/overnight2/done/30-win3.log`, per-run dirs `f14/` and `f14ttft/`). All passed: +- Item 5 (system prompt of about 300 tokens, first user start at 328): chat 1 turn 1 created a + checkpoint at `n_tokens = 328` and ran the rest as one batch; turns 2 and 3 each restored the + end-minus-4 checkpoint and ran as one batch (370 and 980 tokens). Chat 2 restored the checkpoint + at 328: `prompt_n` 78 (its user message and the generation prompt), TTFT 2.72 s against 6.97 s + for chat 1's fresh turn 1. No `forcing full prompt re-processing`. +- Item 6 (SIGTERM and restart between the chats): `disk cache: restored 1849 tokens (350.2 MiB, 4 + checkpoints)`, read 467 ms, restore 49 ms, "328 of 406 prompt tokens reusable", then the restore + of the checkpoint at 328 and `prompt_n` 78 as in item 5, TTFT 3.60 s. With a shorter system prompt + (first user start below 256 tokens) no disk restore happened and chat 2 processed all 206 tokens: + the known limit. +- Item 7, M only, two runs (mean, single runs in brackets) against the M column of the table above: + + | turn | prompt_n | M TTFT now | M TTFT 2026-11-22 | + |---|---|---|---| + | 1 | 196 | 6.39 (6.54, 6.24) | 3.99 | + | 2 | 327 | 4.62 (4.64, 4.61) | 4.11 | + | 3 | 869 | 6.02 (5.84, 6.21) | 6.34 | + | 4 | 1381 | 7.20 (6.56, 7.85) | 7.20 | + | 5 | 1130 | 7.35 (7.08, 7.62) | 8.82 | + | 6 | 1370 | 7.91 (7.95, 7.88) | 8.11 | + | edit | 1374 | 7.29 (7.45, 7.13) | 7.94 | + + `prompt_n` is identical on every turn. Turn 1 pays the system-prompt split again (+2.4 s here, + close to U's 6.08 s: this system prompt is 23 tokens, so its batch runs the experts on the CPU); + turns 2-6 are within noise. + +--- + +## 4. Dead ends + +Measured on this hardware and rejected. Each entry has the number and the mechanism. Do not retry +without a new reason. + +| idea | result | mechanism | +|---|---|---| +| Weight pinning (`GGML_CUDA_REGISTER_HOST` and the host-register chain, from a third-party CUDA fork whose +64% was on an RTX 3060) | +17% pp2048 in isolated llama-bench (252 -> 294), fails in serving | RADV cannot import file-backed mmap pages; the pre-stage fallback fails (`ErrorOutOfDeviceMemory` for the ~18 GB expert region) or doubles host RAM. `-lm none` serves faster (Qwen3.6-35B 278 -> 286). Dropped in the 2026-09-09 rebase. | +| Expert-upload prefetch (`GGML_SCHED_PREFETCH_EXPERTS`) | -20% pp (other runs -9% to -22%), no tg benefit | Slots allocate in host-pinned GTT, not VRAM, so it stages host to host and still pays the PCIe read. `=1` means the default 3 slots. Dropped. | +| `GGML_VK_ASYNC_USE_TRANSFER_QUEUE=1` | flat (-0.1%), byte-identical | GCN is excluded from `prefers_transfer_queue` and RADV exposes no transfer-only queue family here; the per-layer upload-then-compute order leaves nothing to overlap. A standalone Vulkan microbench did show 60-73% of an H2D copy on queue family 1 hidden behind compute, so double-buffered prefetch inside one backend context remains an untested idea (estimated +10-15%, unproven). Superseded 2026-11-23 on Mesa 26.3.1 with `RADV_EXPERIMENTAL=transfer_queue` (a real SDMA transfer family): +6-8% prefill, in production (section 5). | +| Fractional `-ncmoe` | no measured win | Config only uses integers (22/40/48); upstream refactored `-ncmoe` into `llm_add_n_cpu_ffn_overrides`. Dropped. | +| MoE cache `--moe-cache-mib` 512 / 1536 / 2304 (Qwen3.6-35B, ncmoe 40, ctx 131072) | tg256@d4096 -42% / +5% / +12%; prefill +1-3%; idle VRAM 6.15 / 7.19 / 7.96 GB vs 5.66 | Small caches thrash (8-of-256 routing over 40 layers) and add a per-layer ids readback; only ~2.3 GiB pays and leaves no VRAM for a long KV. Not enabled. | +| MTP speculative decoding, Qwen3.6-35B | decode -39% (n1), -37% (n2), -50% (n3), -44% (n4), best -19% (n2, p-min 0.75); prefill -3 to -6% | A spec step costs ~180 ms vs 52 ms for plain decode; a 2-token verify alone is only 1.4x a 1-token step, so ~100 ms/step is draft machinery. The nextn layer adds 1.25 GiB VRAM. Entries removed. | +| MTP, gemma-4-26B-A4B | decode -57.9% (n1), prefill pp4k -34% | Same mechanism (~210 ms vs ~50 ms per step); MTP needs `--swa-full`, which alone costs -10.5% decode, -32% pp4k and saturates VRAM. Entries removed. | +| MTP, gemma E4B | decode -10.9% | Acceptance 0.41-0.67. The +19.5% pp seen with it comes from `--swa-full`, not MTP. | +| `--parallel 1` on gemma | no effect (-1.0%, +2.1%) | The Qwen gain is probably tied to its recurrent state being sized per sequence (unverified). | +| `-ub 4096 -b 4096` (Laguna) | flat (90.0 vs 90.9) | Fewer expert uploads cancelled by intra-ubatch attention growth. | +| mul_mat_id tile-padding theory (larger/odd `-ub`) | predicted 2.00x waste and a 1.94x cliff; measured +3.8% and -5.6%, no sawtooth | Theory dead; kills the mul_mat_id tile-selection shader work (an unbuilt, unverified WIP exists on branch `fable5/mmid-tile-wip`, with an unresolved correctness concern in its row_ids fill). | +| `-b` sweeps | non-monotonic (2048/8192 high, 4096/12288 low) | `-b 2048` is already at the top. | +| `-ncmoe` below 40 on the 35B | 34: +2.9% pp but 7.23 GiB peak at tiny context; 28: better at short context, worse at depth (137 vs 170 t/s at d32k); <= 24 collapses (~122) | Resident experts are evicted by KV/activation growth; cannot survive a 128k context. | +| `-ncmoe` 44 on Laguna | +1.5% | Does not fit at 64k context. Keep 48. | +| fp16 on Polaris (Mesa 26.1.6 + `radv_enable_float16_gfx8=true`, `fp16: 1`) | pp2048 -4.7%, -5.3% at d16k, tg +4% | Hurts prefill (the priority). Mesa 26.1.6 alone: +3.3% prefill, below the 5% bar; adopting it needs a pod image change. The pod's Mesa 25.0.7 has no such option. | +| KV quant on Qwen (q4_0, q8_0) | f16 beats q4_0 by +40% pp at 64k; q8_0 170 -> 128 t/s at depth; q4_0 with upstream PR #30738 still -16% vs f16 at d32k (133.6 vs 159.4) | No int-dot/fp16 here, so dequant is pure compute; the hybrid model's KV is small anyway. Keep f16. (PR #30738 was +15% at d16k on gemma-26B with q4_0 KV; not merged upstream as of the 20261024 rebase.) | +| `-fa 0` | 5x slower at depth (170 -> 35 at d32k) | Keep flash attention on. | +| FA scalar `block_rows` 16 -> 32 | 3.5x regression at d32k (135 -> 38) | ~42 KB shmem per workgroup at head_dim 256, one workgroup per SIMD, occupancy collapse. | +| `GGML_VK_DISABLE_GRAPH_OPTIMIZE=1` | restores tg32 at n_ctx=32 (10.44 -> 15.61), nothing at real depth | Upstream #27812's view-alias fix makes KV views look dependent and collapses barrier-free batches; only visible when per-node work is tiny. It is a correctness fix; do not disable it in serving. | +| `--no-mmap`/`-lm none` for Laguna-S 118B | does not load, OOM-killed the node 3 times | Pinned host buffer is charged against the GTT limit (~31.4 GiB); experts are 30.7 GiB. Laguna uses mmap. | +| Laguna `--cache-reuse`, `--swa-full`, `-t 12`, KV quant | ruled out | `--cache-reuse` is force-disabled for iSWA when base and SWA sizes differ. | +| CPU-only task model (`-ngl 0`) to avoid handoffs | rejected | At `--ctx-size 8192` titles could face 8k tokens of CPU prefill. The arbiter is the answer. | +| `-lm dio` (direct IO) instead of the F10 page-cache drop | load +0.9 s on 3.4 GiB (6.89 vs 5.99 s), the same cost as the drop; 175 MiB of the model file and all of the mmproj stay cached | Synchronous 64 MiB O_DIRECT chunks with no readahead; the GGUF metadata goes through a separate buffered FILE and clip.cpp has no direct-IO path. Measured CPU only; reads into pinned Vulkan buffers may fall back to buffered IO (`EFAULT` or `EINVAL`). Not adopted. | +| F15: AVX2 NVFP4 x Q8_0 dot product (two blocks per iteration, vector UE4M3 scale decode; branch `fable5/nvfp4-avx2`) | kernel 1.13x per row (L2-resident, one core); Inkling decode with the production command line +0.8% (6.34 -> 6.39 t/s, B N N B, 2026-11-23); deployed 2026-11-23 01:47, removed the same day | Decode streams about 1.3 GB of host NVFP4 experts per token at k=4; at 6 threads every quant type sits at the same 21-23 GB/s DRAM bandwidth, so a faster dot product turns into idle time. Retry only if the experts become cache- or compute-bound (fewer threads, a smaller quant). | +| The fork's own concat tiled-transpose fast path (F3 until 2026-11-23) | upstream's #30591 tiled concat alone: Qwen 35B pp2048 292.3 vs 286.2 with the fork's path, 254.9 with neither; d16384 208.9 vs 207.7 | Same 32x32 shared-memory transpose; upstream's is one dispatch for both sources, the fork's used two and a pipeline barrier. The fork keeps only the decode gate (F3). | +| Loop-aware `--fit` for Inkling (carry of upstream #32777) | k of about 2.3 instead of 4: prefill -3%, decode -12% (2026-11-23) | Fit keeps a larger margin than the manual k=4 placement needs (F12). | +| F1: skip the MoE routing-ids readback when a ubatch uses every expert (fork 2026-09 to 2026-11-23) | off is faster: Qwen 35B pp2048 +4.5%, d16384 +3.9%, Inkling pp2048 @ d8192 +4.7% (2026-11-23, Mesa 26.3.1 + transfer queue) | Was +4.7% at d32k on Laguna (2026-09, system Mesa). Not re-analysed; uploading every expert seems to cost more now than the readback flush it saved. | +| F3's one-tile gate on upstream's tiled concat (`src1->ne[0] < 32` to the generic kernel) | gate off is faster: Qwen 35B tg256 @ d4096 +5.5%, Qwen3.5-4B -0.4% (noise), Inkling's concats 0.2% of a token (2026-11-23) | The -17% it guarded against came from the fork's old two-dispatch fast path; upstream's one-dispatch tiled kernel is not slower at decode. | + +The one live prefill lead: a partial trailing ubatch is expensive (ub4096 at p8448 = 2 full + 256 +tail measured 258.4 vs 296.4 at p8192, -12.8%), consistent with a fixed expert-upload cost per ubatch. + +Where the time goes (Laguna-S-2.1 118B IQ2_M, all experts on host, `GGML_VK_PERF_LOGGER=1`, depth 0, +22.65 s per 2048-token eval, 17.18 s of it GPU-busy, so about 24% is H2D stall; moved here from the +old README section): expert `MUL_MAT_ID` 52%, attention projections 24%, `FLASH_ATTN_EXT` 16%, +everything else 8%. The expert matmuls run at 1686-2139 GFLOP/s while dense `MUL_MAT` q5_K/q6_K in +the same graph reaches 3096-3691, so closing that gap is the largest remaining opportunity on this +card, not the transfer path. On interleaved-SWA models the sliding-window layers keep a small KV +(`n_kv` pinned at `n_swa * n_seq_max + n_ubatch`), so they cost the same at any depth; on Laguna 36 of +48 layers are O(1) in depth and the whole high-context slowdown comes from the 12 full-attention +layers. + +## 5. Configuration that matters + +`/root/config.yaml` (llama-swap) and `/root/supervisord.conf` on the pod are the source of truth; +this section explains the choices. Values as of the 2026-11-23 window. + +Qwen 35B-A3B MoE entries (macro `moe_offload_args`, applied to all 35B-A3B variants): +`--no-warmup --port ${PORT} -lm none -tb 12 -t 4 -ngl 99 --n-cpu-moe 40 -b 4096 -ub 4096 -fa 1 --parallel 1`, +context 131072 (until 2026-11-23: `-t 6 -b 2048 -ub 2048`; backup `/root/config.yaml.bak-20261123-prefinal`). + +- `-lm none`: load weights into RAM (upstream removed `--no-mmap`; the old spelling makes the server + refuse to start). Faster in serving than mmap and recommended for `--n-cpu-moe`. Exception: + Laguna-S, which must use mmap (GTT limit, section 4). +- `-ub 4096 -b 4096`: the biggest prefill lever. ub512 = 97 t/s, ub1024 = 159, ub2048 = 254 on the + 35B; the per-eval expert upload is amortized over the ubatch. ub4096 (2026-11-23, llama-bench + b4096 in one invocation): pp4096 279.3 -> 304.5 (+9.0%), pp8192 269.3 -> 289.6 (+7.5%), pp4096 @ + d16384 204.3 -> 215.7 (+5.6%); with the production command line (mmproj, ctx 131072, scratch + server, arms 2048 4096 4096 2048) a 32.7K-token prompt 220.4 -> 232.1 t/s (+5.3%), Vulkan0 + compute buffer 994 -> 1712 MiB, VRAM after load 5723 -> 6444 MiB (about 1.7 GB left), image + requests fine. Prompts under 4096 tokens gain little (one ubatch either way). +- `--n-cpu-moe 40`: all experts on host. Lower values are faster at short context but run out of VRAM + at long context (section 4). Measured idle VRAM at ctx 131072: 5.66 GB. +- `--parallel 1`: +22.9% decode on the Qwen 35B (15.5 -> 19.1 t/s), prefill +0.3-1.2%, +64 MiB VRAM. + Without it the server creates 4 slots and a unified KV. Two concurrent requests queue on slot 0. + With one slot a ubatch never holds more than one sequence, which upstream's tiled concat needs + (`ne[2] == 1`). +- `-t 4` (decode threads; prefill uses `-tb 12`): 2026-11-23 llama-bench tg256 @ d4096, `-t + 6,5,4,4,5,6` in one invocation: 14.30/15.53/17.03/16.52/15.62/14.08 t/s, so -t 4 is +18% over + -t 6 on this contended node (fewer threads wait less in the barriers). Through llama-swap after the + change: 16.9 t/s over 300 tokens. `OMP_WAIT_POLICY` active/passive: no gain. Inkling measured + -t 4 at +5% (7.92 -> 8.32), below the noise bar, so its macro keeps -t 6 for now. +- `-fa 1`: essential (section 4). +- f16 KV (no `-ctk/-ctv`): section 4. + +Other models: +- gemma-4-26B-A4B: macro `moe_offload_gemma`, same as above but `--n-cpu-moe 22` (8 layers of experts + resident; gemma's SWA keeps KV small at depth). ncmoe sweep pp2048: 30 = 262, 24 = 266, 18 = 272, + 14 = 157 (VRAM collapse); 22 keeps headroom for 128k context (7.40 of 8 GB at 128k). + Its KV cache is `-ctk q4_0 -ctv q4_0`, set in the `gemma4_sampling` / `gemma4_nothink_sampling` + macros (not in `moe_offload_gemma`); note gemma has no `--parallel 1` (no measured gain there). +- Small models that fit in VRAM (Qwen3.5-4B, gemma E4B/E2B and similar) use auto-fit + (`common_args`); forcing experts to host would slow them. +- The 4B task model runs with `--no-mmproj` and ctx 8192, and is preloaded. +- Laguna-S-2.1 118B IQ2_M (configured as `Laguna-S-2.1-IQ2_M`, matrix var `lag`): mmap, `--n-cpu-moe 48 -b 2048 -ub 2048 -fa 1 --parallel 1`, + ctx 65536. Its exclusivity set must allow the task model (`lag & q4task`); making it exclusive with + the task model killed it on every title request and forced full re-prefills. `--parallel 1` frees + 223 MiB of VRAM at 64k context there (4 auto slots size the SWA cache `n_swa * n_seq_max + + n_ubatch`, 4096 cells instead of 2560). +- Inkling-2-Mini (26B MoE, `inkling2`, 24 layers with the middle 12 looped 3x, 24 heads / 8 KV + heads, head size 128; macro `inkling_args`, entries `unsloth/Inkling-2-Mini-GGUF[-nothink]:UD-Q4_K_XL`, + matrix vars `ink`/`inknt`): the mainline-layout GGUF in `/root/models/inkling/` passed with `-m` + (the repo-root GGUFs that `-hf` would pick are Unsloth's layout), `--mmproj` beside it, + `-t 6`, f16 KV, `--parallel 1`, the disk prompt cache, `-b 1024 -ub 1024 --ctx-size 65536` + (since the 2026-11-22 carry of upstream #32740, F12; before: `-b 512 -ub 512`). Since the F13 + deploy (2026-11-22, `b13c41355`): the experts of loop layers 6-9 stay on the GPU and all others + on the host, `-ot blk[.](0|1|2|3|4|5|10|11|12|13|14|15|16|17|18|19|20|21|22|23)[.]ffn_.*_exps=CPU` + instead of `--n-cpu-moe 24` (k=4 of the F13 placement guide: 7246 MiB of device memory, 868 MiB + left for the mmproj). The `GGML_OP_OFFLOAD_MIN_BATCH=64` env of both entries was removed: F13 + makes the 32-63-token ubatches correct (KLD in F13). Since 2026-11-23 both entries set + `env: ["LLAMA_LOOP_FULL_COPY=0"]` (skip upstream's #32807 full-copy guard, which F13 makes + redundant: +76% in 32-63-token ubatches, F13 window A/B; never together with + `LLAMA_LOOP_HOST_VIEWS=0`). `--fit` was measured against this placement and lost (F12). Other choices from the guide: ctx 32768 with + k=6, or ctx 131072 with k=0 (fits since F13, 134 MiB free, so images would spill). Smaller quants + (UD-Q3_K_XL, UD-IQ3_XXS, `/root/models/inkling/`) were measured and not adopted (F13, Quants). + Its nothink macro uses `--reasoning-effort none` (no `--reasoning-budget 0`: that budget made it + loop on chat-structure tokens, F12); even with effort none it writes a short reasoning block. + Against Qwen3.6-35B (think entries, 7 tasks, one sample each, 3500-token cap, 2026-11-22, + `/root/arms/overnight/quality.py`, `quality/quality.json`): Inkling 6/7, Qwen 5/7. Inkling found + all three bugs of a binary search where Qwen ran out of budget; both ran out on a 4-line Polish + rhyme. Inkling used about a third fewer tokens (9677 vs 14254) but took 1.7x the wall time (2283 + vs 1316 s; decode 4-6 vs 13 t/s) and 4x on a 29K-token question (835 vs 211 s). Too small a + sample to call it smarter; it is clearly slower here. + +Environment, set once for all of llama-swap in `[program:llama-swap] environment=` of +`/root/supervisord.conf`: +- `LLAMA_SLEEP_VRAM_ONLY=1`: enables the arbiter and VRAM-only sleep (F6). +- `LLAMA_VRAM_ARENA=/dev/shm/llama-vram`: the shared arena. Every co-loaded GPU model must use it. +- `LLAMA_SLEEP_EVICT_KV=1`: cold models also free KV, recurrent state, scheduler and scratch (F4), + so the warm model gets nearly the whole card. Costs a 2-3 s re-warm instead of ~0.6 s. +- `LLAMA_MMPROJ_ONDEMAND=1`: encoder in VRAM only during encodes (F5). No-op for models without an mmproj. +- No `--sleep-idle-seconds`: release is purely demand-driven via want.lock. + +- Since 2026-11-23: `VK_ICD_FILENAMES=/opt/mesa-26.3.1/share/vulkan/icd.d/radeon_icd.x86_64.json`, + `RADV_EXPERIMENTAL=transfer_queue`, `GGML_VK_ASYNC_USE_TRANSFER_QUEUE=1`: RADV from Mesa 26.3.1 + (self-built, RADV+ACO only, not the system package) with its SDMA transfer queue, which llama.cpp + then uses for async uploads (the expert copies). Measured in the 2026-11-23 window (llama-bench, + arms old new tq tq new old): Qwen 35B pp2048 284.8 -> 305.9 (+7.4%), pp2048 @ d16384 207.7 -> + 220.7 (+6.3%), Inkling pp2048 @ d8192 102.2 -> 110.6 (+8.2%), decode unchanged within noise; Mesa + 26.3.1 without the transfer queue gives about half of that (+4.5%, +3.8%, +3.1%). test-backend-ops + and `fork-validate.sh --arbiter --ops --concat --diskcache` (39 PASS) passed with it. Backup + `/root/supervisord.conf.bak-20261123-mesa`; switch back with + `sh /root/arms/overnight2/mesa-switch.sh off` (restores the backup and restarts llama-swap). The + standalone tools (llama-bench, fork-validate.sh) still use the system Mesa unless the three + variables are exported. + +Not set, on purpose: `GGML_VK_DISABLE_GRAPH_OPTIMIZE`, `GGML_SCHED_PREFETCH_EXPERTS`, `--moe-cache-mib`. +`--cache-disk-path /root/prompt-cache --cache-disk-size 4096` (F11) is set in the `moe_offload_args`, `moe_offload_gemma` and `inkling_args` macros. + +Machine-level: +- GPU power cap fixed at 120 W by `/root/fan-control.sh` (a separate supervisord program; re-asserted + every second; default/max cap 145 W). The two GPU hangs of 2026-10-09 happened before the cap was + fixed (it used to switch between 120 and 145 W by temperature); heavy runs since have been clean. +- Kernel argument `amdgpu.lockup_timeout=0,120000,0,0` (compute ring 120 s) via Talos + `machine.install.extraKernelArgs`. Without it long 64k-context submissions hit the compute-ring + watchdog (`ring comp_1.x.0 timeout`). +- Upstream changed the default `--port` from 8080 to 9931; the config passes `--port ${PORT}` + explicitly, so it is unaffected. + +## 6. Measurement methodology and traps + +- **Cross-run variance is about 7%.** llama-bench's within-run error bars understate cross-invocation + variance by about 14x (the same config read 276.7 +/- 0.9 and 296.4 +/- 0.6 in two invocations). + Put every comparison you draw a conclusion from inside one llama-bench invocation + (comma-separated sweeps). Two builds cannot share an invocation, so interleave them over at least 3 + rounds and compare medians. Treat any cross-build delta under about 5% as unproven. +- **Alternate arm order.** A fixed order gave the later slot about a 9% advantage and nearly produced + a false regression finding. Use orders like ref, cand, cand, ref. +- **Node CPU contention.** The node runs about 60 pods; llama-bench once got 4.67 of 12 hardware + threads while asking for 6. With `--n-cpu-moe 40` every MoE layer decodes on the CPU, so stolen + threads map onto tg almost directly. Prefill is nearly immune (held +-0.3% while tg32 swung +-14%). + Expect occasional catastrophic tg samples; use medians, never means. Historical tg figures taken + under different load are not comparable. +- **Never use tg32.** At the default depth (n_ctx 32) decode is launch/barrier bound and measures + command-stream overhead: two upstream commits read -36% at tg32 and were at parity at tg256 (and +7% + at d512). Use tg256 (or tg128) with an explicit depth (`-p 0 -n 256 -d 4096`). tg is not monotonic in + n_ctx on this box (n_ctx 256 measured slower than 32 and 544), so only compare same-depth cells. +- **`-b Vulkan` vs `-b Vulkan0`.** `test-backend-ops -b Vulkan` matches nothing, runs 0 cases and + still prints OK with exit 0. The backend is `Vulkan0`. Always check the case count. +- **ubatch larger than the prompt never fills.** With `-ub 2048` use prompt lengths that are + multiples of 2048. A partial trailing ubatch costs a full expert upload. +- **`-tb` is not a llama-bench flag** (server only). Any bad flag makes llama-bench print usage and + exit, which looks like a run that produced no rows. Always check the row count. `-ncmoe` is + llama-bench's spelling of `--n-cpu-moe`. +- **llama-bench prints its table only after all `-d` values finish.** No output does not mean hung. +- **Nothing else may use the GPU** during a measurement; stop llama-swap (`/root/bench/moe/swapdown.sh` does this and restarts it from a trap). +- **Check the build finished** before benchmarking it (library mtime earlier than the run start). + Never overlap a build with a big benchmark (host OOM). +- **Prompt-cache reuse is `timings.prompt_n`,** not `tokens_evaluated` (which is always the full + prompt length). +- **Per-process VRAM** from `/proc//fdinfo/*` `drm-memory-vram` must be deduplicated by + `drm-client-id`; summing all fds double-counts shared buffers. `drm-memory-gtt` is system RAM, not + VRAM. Whole-card usage: `/sys/class/drm/card*/device/mem_info_vram_used`. + `GGML_VK_MEMORY_LOGGER=1` logs every Vulkan buffer alloc/free with a running device total to stderr. +- **test-backend-ops cannot show which concat kernel ran**; check the tiled path with + `GGML_VK_PERF_LOGGER=1` timing (the tiled CONCAT is several times faster), or byte-identical greedy generation (temperature 0, top_k 1, fixed seed, + `cache_prompt: false`). +- **Do not run `llama-cli` detached with closed stdin** on the pod: it can loop forever printing + prompts (it once wrote a 65 GB log). Use llama-bench `-d` or a llama-server script. + +## 7. Known gaps and open risks + +- `llama_context::restore_device()` ignores the `bool` returned by `restore_device_weights()`, + `moe_cache->restore_device()` and `memory->restore_device_buffers()`. On a restore OOM, + `device_resident()` stays false, decode retries the restore on every call, and a graph reading a + null buffer would crash. Only the mmproj path handles a failed restore. +- Memory types without a `release_device_buffers` override keep their KV under `evict_kv` (F4). +- Inkling (F12, section 5): the nothink entry's chat-structure loop came from + `--reasoning-budget 0` and was fixed in the config on 2026-11-22 (F12). Upstream #32755 / #32778 + did not reproduce here; F13 bounds the loop-pass expert copies (more in F13). Drop the F12 carries when upstream merges #32735 and #32740. +- Does `n_inflight` blocking the want-lock yield delay handoffs? Validation says no (handoff median + 692 ms candidate vs 1068 ms reference, 2026-11-21). +- Router mode can spin at shutdown (F7); not used here. +- The unexplained ~1.6 GiB peak-VRAM spike in the first candidate `--perf` arm, seen twice (F9). +- Not reported upstream: the `wait_until_no_sleep()` lost wakeup and the sleep wait that ignored new + tasks (both upstream bugs fixed in 878d1338f), and the graph-optimize alias cost at tiny context. + Repository rules forbid agent-written upstream issues or PRs; the owner would have to write them. +- F10's load-time cost on the 35B (synchronous page freeing, about 0.28 s per GiB on the test model) + is an estimate; its memory effect is verified in production. +- F11 (disk prompt cache): the same-reuse-point identity check and the production-command-line (mmproj + loaded) 35B run both passed on 2026-11-21 (`/root/arms/diskcache-window3.sh`, F11 Validation), and + the cache is on in production. Remaining gap: only the 35B and gemma were checked in production; + other models gain the flag only if they use those macros. +- A SIGTERM during an arbiter release with `LLAMA_SLEEP_EVICT_KV` (F4, not F11) pays that release's + host shadow of the full KV allocation (about 2.6 GB for the 35B at ctx 131072) and its D2H time + (token free in about 1.9 s) before the exit. The same is true of every cold 35B, which holds that + shadow while it is cold. +- F11 saves only the slots, not the RAM prompt cache entries, and every deploy empties it (the key + holds the build commit). Its exit write delays a llama-swap model switch by about 1 s per GB. +- From the 2026-11-23 window (`/root/arms/overnight2/STATUS.md`), measured and not adopted: + - F3's own fast path was redundant with upstream's tiled concat (numbers in section 4); dropped + on 2026-11-23 together with F15 and the #32777 carry, and later the same day F1 and F3's gate + (section 2). + - PCIe link: idle at 2.5 GT/s x8, 8 GT/s x16 under load; forcing 8 GT/s (`pp_dpm_pcie`) changed + nothing (pp2048 286.7/287.9 auto vs 284.8/287.6 forced). The 6.9 GB/s upload estimate is not + the link state. + - `GGML_OP_OFFLOAD_MIN_BATCH` for the 35B: llama-bench shows the CPU 1.5x faster than the GPU + at 64-128-token batches (crossover about 256), but a scratch-server TTFT A/B with short turns + (threshold 256) swung from -23% to +31% with the node load: the CPU path is not robust here. + Threshold 8 loses. For Inkling, threshold 4 loses below 16 tokens and gains only at 24. + - Inkling small CPU batches are slow in the server (a 13-token user batch 3.8 s, the 4-token + end-minus-4 tail 2.7 s in a tool request; llama-bench pp16 is about 1 s at `-t 6`). F14's + system-prompt break turns the user message of a tool request into such a batch. Not + investigated. + - Not run (time): the MoE cache `--moe-cache-cpu-share` retest. +- From the 2026-11-23 slimming window (`/root/arms/run3/win.log`), 35B decode at production `-t 4`, + llama-bench tg256 @ d4096, measured and not adopted: + - `--prio` (process-wide, one value per invocation, arms 0 2 2 0): prio 0 16.37 / 16.94, prio 2 + 15.80 / 16.04 t/s (-4%). No gain. + - `--cpu-strict 0,1,1,0` in one invocation: 17.31 / 17.37 / 17.22 / 16.16 t/s, strict 17.30 vs + 16.74 (+3%), below the 5% bar. diff --git a/docs/fork-rebase-runbook.md b/docs/fork-rebase-runbook.md new file mode 100644 index 000000000..308c2f457 --- /dev/null +++ b/docs/fork-rebase-runbook.md @@ -0,0 +1,867 @@ +# Fork rebase and deploy runbook (RX 580 fork) + +Step-by-step procedure for moving the fork onto a new upstream and putting it into production, as it +has evolved over the 2026-09-09, 2026-10-09, 2026-10-24 and 2026-11-21 rebases. Read [FORK.md](../FORK.md) first: +it lists every fork feature with its invariants and rebase hazards, and this runbook refers to it. + +Ground rules: + +- **Never build on the workstation.** All builds run on the RX 580 pod. Locally, rely on careful reading. +- **Never resolve a conflict with `-X theirs` or `-X ours`.** Resolve every hunk by hand. +- **"Applied cleanly" is not "correct".** Re-read every clean pick against the new upstream. +- **Never `pkill -f` on the pod.** It matches the `kubectl exec` shell and kills it. Kill by explicit PID. +- **Never leave the pod not serving.** Anything that stops llama-swap must restart it from a trap. +- Keep the previous production branch untouched as the safety net. Do not push for the owner; the owner + reviews and pushes. + +Contents: 1. Survey; 2. Trial rebase; 3. The real rebase; 4. Checks without a compiler; 5. Build on +the pod; 6. Validate; 7. Deploy; 8. Post-deploy checks; 9. Rollback; 10. Recovering a hung GPU; +11. Operations reference. + +**Redeploying a new tip on the same upstream base (no rebase)**, e.g. new fork commits on the +production branch (2026-10-25: `6c480f7e7` -> `2fc9f9c35`, same branch, same base): +- Skip sections 1-3. Of section 4 only the ASCII check (on `git diff ..`) and a careful + read of that diff apply; `` is `git -C /root/llama.cpp rev-parse HEAD` on the pod. There is + nothing to range-diff. +- Do sections 5-9 as written: build the tip in a scratch worktree, validate it with `--ref` = the + production build, then deploy. +- The branch name stays the same, so deploy step 2's `git checkout -B ` moves the + production branch on the pod to the tip. After that the rollback pointer file is the only record + of the old production commit on the pod, so write it first (deploy step 1). + +--- + +## 1. Survey upstream + +Local remotes: `origin` is upstream (github.com/ggerganov/llama.cpp), `gitea` is the fork +(git@gitea.lumpiasty.xyz:Lumpiasty/llama.cpp.git, SSH push from the workstation). On the pod, +`origin` is the same gitea repository over HTTPS (fetch only). + +```sh +git fetch origin +OLD_BASE=$(git merge-base origin/master HEAD) # the old upstream base (still an ancestor of the new master) +OLD_TIP=$(git rev-parse HEAD) +git log --oneline "$OLD_BASE"..HEAD # the fork commits, oldest last +git log --oneline "$OLD_BASE"..origin/master | wc -l # size of the upstream delta +``` + +Then look at upstream changes in the areas FORK.md lists as hazards: + +```sh +git log --oneline "$OLD_BASE"..origin/master -- \ + src/llama-context.cpp src/llama-context.h src/llama-model.cpp src/llama-model.h \ + src/llama-kv-cache.cpp src/llama-kv-cache.h src/llama-kv-cache-iswa.cpp \ + src/llama-memory.h src/llama-memory-recurrent.cpp src/llama-memory-hybrid.cpp \ + src/llama-moe-cache.cpp src/llama-moe-cache.h src/models/delta-net-base.cpp \ + ggml/src/ggml-vulkan/ ggml/src/ggml-backend.cpp ggml/src/ggml-backend-impl.h ggml/include/ggml-backend.h \ + tools/server/server-queue.cpp tools/server/server-queue.h tools/server/server-context.cpp tools/server/server.cpp \ + tools/mtmd/clip.cpp tools/mtmd/mtmd.cpp common/arg.cpp tools/llama-bench/ +``` + +**Temporary upstream carries (FORK.md F12)** come first: `git log --oneline --grep '^upstream-carry' +"$OLD_BASE"..HEAD`. For each: merged into the new upstream -> do not cherry-pick it (check that the +merged version is the carried head or newer); still open -> re-fetch the PR head and re-carry it if +it moved; closed -> ask the owner. A PR head can also shrink: on 2026-11-22 #32740 dropped the Vulkan part the fork needs, so the old +head stayed carried (FORK.md F12). Compare `git diff --stat` of the old and new head before re-carrying. +To carry a PR (2026-11-21: #32735, #32740; 2026-11-22: #32777): +```sh +git fetch https://github.com/ggml-org/llama.cpp pull//head:pr- +git cherry-pick $(git merge-base pr- HEAD)..pr- # the PR's commits, oldest first; resolve by hand +# squash them into one commit with the PR author, subject "upstream-carry #: ", and a +# body with the PR URL, the carried head and any conflict resolution (git commit-tree on the final tree) +diff <(git diff $(git merge-base pr- HEAD) pr- | grep '^[+-]') <(git diff HEAD~1 HEAD | grep '^[+-]') +``` +The last diff shows only the lines you changed while resolving conflicts (for #32740: none, the F2 +line differs only in context). Validate a carry like any compiled change (sections 5-6), plus the +PR's own tests. + +For each fork commit decide: still needed, needs a semantic merge, or obsolete. Examples of past +decisions: +- 2026-09-09: dropped the weight-pinning chain, the expert prefetch and fractional `-ncmoe` (all measured + losses or no win on this card, FORK.md section 4). +- 2026-10-09: the routing-ids readback skip had nothing to apply to (upstream #29943 deleted its block + in `ggml-backend.cpp`); it was re-authored in `llama_context::sched_copy_experts`. Upstream's new MoE + cache (#29887) needed a new fork commit so the VRAM arbiter releases and invalidates it. +- Also check CLI changes that break production config or the scripts (upstream #28334 removed + `--no-mmap`/`--mmap`/`--mlock` and llama-bench `-mmp`; the default `--port` changed to 9931). + +## 2. Trial rebase in a scratch worktree + +Measure the conflicts before doing the real thing: + +```sh +git worktree add /tmp/trial-rebase origin/master +cd /tmp/trial-rebase +git cherry-pick "$OLD_BASE".."$OLD_TIP" # stop at each conflict, note file + hunk, then: +git cherry-pick --abort # or resolve roughly to see the next one +cd - && git worktree remove --force /tmp/trial-rebase +``` + +Write down, per commit: clean / conflict (which file, which hunk, what both sides did). That list +becomes the brief for the real rebase. + +## 3. The real rebase + +```sh +NEW=fable5/vram-ondemand-rebase-$(date +%Y%m%d) +git switch -c "$NEW" origin/master +git cherry-pick # one at a time, in the original order +``` + +**A rebase is not done until `fork-validate.sh` phases 1 and 2 (section 6) pass on a pod build of +the new branch.** A rebased branch that is only picked, checked by reading, or built is unfinished +work, whatever the cherry-picks looked like. Report it as unfinished until both phases pass. + +Rules: +- Cherry-pick in the original order, keep authors and messages. New commits you author get the + fork's trailer (`Co-Authored-By: Claude ...` for agent-written commits, FORK.md status block), + unless the owner asks for something else. +- Resolve every conflict by hand. Union both sides where both added code; keep upstream's new terms. +- Fold each fix into the commit it belongs to so every commit builds on its own: + `git commit --fixup=` then `GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash origin/master`. +- Leave the previous production branch untouched. + +**What `-X theirs` silently broke in a trial (2026-10-09).** It "applied" every commit and produced +broken code: +- resurrected the scheduler readback block upstream had deleted from `ggml-backend.cpp`; +- dropped `!use_sparse` from the GCN `use_mask_opt` condition; +- dropped upstream's `copy_experts_info` (compile error); +- dropped upstream's `is_empty()` in the recurrent memory; +- dropped upstream's MoE-cache memory breakdown block; +- left a static/extern mismatch with the new `ggml-vulkan-common.h` declarations (compile error). + +The correct resolutions in that rebase: keep upstream's `n_embd` width check plus our decode +auto-restore; `copy_experts_info` plus our `kv_device_evicted`; `is_empty()` plus our `dev_shadows`; +upstream's `if (moe_cache)` breakdown block outside our `if (sched)` guard; make `ggml_vk_concat` and +`ggml_backend_vk_free` non-static to match the new header while our helpers stay static. + +**Clean picks that were wrong (2026-10-24).** +- Concat fast path (3df719e1e): applied cleanly, did not compile. Upstream `733f57a99` renamed + `pipeline_cpy_f32_f32`/`pipeline_cpy_f16_f16` to `pipeline_cpy_32`/`pipeline_cpy_16` (bitwise copies, + same push constants). +- MoE cache release/restore (7ac2014a8): applied cleanly, did not compile (upstream `33d6135cb` changed + LRU to SLRU, `g.lru` -> `g.slru`) and had a runtime bug: `moe_cache_slru::init()` resets only the + probation segment, so re-initialising a used cache corrupts its lists. `invalidate()` now assigns a + fresh `moe_cache_slru()` first. +- VRAM sharing core (481be8b28): besides its one conflict, upstream's new `load_tensors_hadamard()` + pushes two more entries into `pimpl->ctxs_bufs`. Without matching `weight_release.emplace_back()` + calls, `release_device_weights()` reads past the end of `weight_release`. Nothing conflicted. +- Conflicts that round: `ctx_buf_maps.emplace_back` replaced upstream by `ctx_bufs.emplace_back(ctx, + std::move(buf_ptrs))` (keep upstream's line, our release-slot block before it); `llama-context.h` + (keep upstream's `n_reallocs_same/diff` beside our `kv_device_evicted`); `recv_with_timeout` + (upstream `4e201388c` uses a fixed deadline: keep our order "check `!running`, return null", then + `wait_until(lock, deadline)`). + +**What the 2026-11-21 rebase (upstream `e6d624b9a`, 757 commits past `3f03b1772`) changed** (nothing +built or run locally; every item below is by reading only and needs the pod build): +- Upstream refactors that moved fork code (hand ports, not conflicts of one hunk): + - `clip.cpp`/`clip.h` are gone (#31865). The encoder release/restore (F5) is now + `mtmd_model_release_device`/`mtmd_model_restore_device` on `mtmd_model` (`mtmd-model.cpp`), called + from `mtmd_release_device`/`mtmd_restore_device` under `compute_mutex` after syncing the shared + scheduler; the page-cache drop of F10 moved to `mtmd_model_loader::load_tensors`. + - `server_prompt_cache` moved to `server-slot-sched.{h,cpp}` and `get_available_slot()` was replaced + by `server_slot_sched::select()`. The disk prompt cache (F11) lives there now + (`server_prompt_disk_cache`), is called from the task dispatch after `update_prompt_cache()`, and + uses `common_state_data` and `shared_ptr`. Only prompts made with + the server lora config are saved, and a restored prompt gets that config in `prompt.lora`. + - Upstream's `llama_memory_bufs` replaced the raw `ctxs_bufs` vectors of the KV cache and the recurrent + memory: the null-buffer guard moved into `llama_memory_bufs::memory_breakdown()`, and the release + code indexes `ctxs_bufs.bufs[i]`. Those two did not compile after a clean pick. + - The MoE cache is now a ClassLRU (`moe_cache_lru`, `g.lru`) with `no_alloc` as a constructor + argument and `cpu_share`. `invalidate()` rebuilds `g.lru`, refills every slot map with + `g.lru.empty` (not -1), clears the CPU maps and `cpu_experts`. + - `server.cpp` was split into `server_run_instance` and friends: the self-pipe shutdown thread + (F7) is started in `server_run_instance` only, just before `server_install_signal_handlers()`. + - `server_queue` got `n_inflight` (#32133). `should_sleep` checks it first, so a response that is still + open also blocks the want-lock yield. This is a decision, not an accident: check it with `--arbiter`. +- Upstream added its own tiled-transpose concat (#30591) with no size gate. The fork path still runs + first (`ne0 >= 32`); the gate and the `GGML_VK_CONCAT_FASTPATH` knob were added to upstream's selector + (`ggml_vk_concat_is_transposed`), otherwise decode would take upstream's tiled path again (F3). + (2026-11-23: the fork path and then the gate were both removed; upstream's tiled path is not slower + at decode, FORK.md F3.) +- Memory types with no release override (stay in VRAM when cold, not used in production): + `llama_kv_cache_dsa`, `_dsa_iswa`, `_dsv4`, `_msa`, `llama_memory_hybrid_iswa`. The KV rotation + tensors (`attn_rot_bufs`, #31073) are small and are not released either. + +**What the 2026-11-22 rebase (upstream `5bacb7c86`, 19 commits past `e6d624b9a`) changed.** Branch +`fable5/vram-ondemand-rebase-20261122`. The 64 picks (65 fork commits minus the #32735 carry) all +applied cleanly; the range-diff against the old branch is identical except for that dropped carry and +the new commits at the end. Reading checks: +- #32735 merged as `8a97fa98a`, patch identical to the carried head `0ea4ffd00`: carry dropped. +- #32740 is still open but was split: its head `8c6f0c0ca` is now only the GGML contract (op API, + CPU reference, test-backend-ops cases); the Vulkan kernel, the `kv_rows` support and the Inkling + graph use were removed from it and are in no open PR (Metal is #32808). Carrying that head would + drop Inkling's in-kernel bias (back to the 15.8 GiB compute buffer at ctx 65536, FORK.md F12). The + validated carry of head `808fd1c4e` is kept as is (FORK.md F12 has the owner decision). +- #32807 (`5bacb7c86`) adds an `LLM_ARCH_INKLING2_LOOP` guard to `sched_copy_experts` (whole-tensor + copies), upstream's fix for #32755. It sits beside F1 in the same function; no conflict. It does + not remove the held per-pass copies, so F13 stays (FORK.md F13, "Upstream #32807"). +- #32713 (non-causal prompts fit in one ubatch) touches `update_slots` near the F14 loop but not + the user-start break; F14 unchanged by it. +- #32799 (`ignore_merges` for inkling2) changes Inkling's tokenization: Inkling prompts cached by + the previous build no longer match. The disk cache key holds the build commit, so nothing stale is + restored. +- New commits: the F14 first-user-message break (FORK.md F14), the `LLAMA_LOOP_FULL_COPY` knob + (F13) and the carry of #32777 (F12). + +**The 2026-11-23 slimming (branch `fable5/vram-ondemand-rebase-20261123`, same upstream +`5bacb7c86`).** Not a rebase onto new upstream: the 74 commits of `-20261122` were rebuilt as one +commit per feature (FORK.md section 2) and the features without a measured benefit were dropped +(F1, F3's fast path and gate, F15, the #32777 carry, the `rx580-bench` harness). Procedure, for the next time it is needed: `git cherry-pick -n` each feature's +commits in their original order, then commit them as one with a message that keeps every original +message under a `---- (was )` line; the VRAM commits, which mixed library and server +hunks, were picked together and committed by path (`git add ggml src include`, then `tools/mtmd`, +then `tools/server`). Checks: `git diff -- . ':!*.md'` must be exactly the +removals (compare each removed file's hunks with the reverse of the dropped commit), and the build, +`fork-validate.sh` phases 1 and 2 and the A/B against production must pass like any compiled change. +A future rebase now cherry-picks 10 code and script commits plus the documentation. + +Open questions from the 2026-11-21 rebase: +- Is the fork's own concat fast path (F3) now redundant with upstream's tiled concat (#30591)? Yes: + measured on 2026-11-23 and dropped (FORK.md section 2, "Removed on 2026-11-23"). +- Does `n_inflight` blocking the want-lock yield delay handoffs? Validation says no: handoff median + candidate 692 ms vs reference 1068 ms (`a-handoff-latency`, 2026-11-21). + +**Semantic re-checks to do for every rebase, clean or not** (details in FORK.md): +- F2: `use_mask_opt` still contains upstream's terms plus our `>= 256` (and `!bias &&` from #32740, carried as F12 or merged upstream). +- Upstream's tiled concat (no fork code since 2026-11-23, FORK.md F3): `build_conv_state` still + emits `ggml_concat(conv_states, ggml_transpose(qkv_mixed), 0)` with `qkv_mixed` contiguous; if a + `ggml_cont` appears there, the 35B loses about 13% prefill and only `--perf` shows it. +- F13 with `LLAMA_LOOP_FULL_COPY=0`: `sched_copy_experts` still keys its routing readback on the ids + of the split's first node (per pass, which the per-pass views rely on). +- F4: every `ctxs_bufs` push in `src/llama-model.cpp` has a `weight_release` push + (`git grep -n "ctxs_bufs.emplace_back\|weight_release" src/llama-model.cpp`); list memory types + (`git grep -n "public llama_memory_i" src/`) and note any without a release override; MoE-cache + internals; `sched_reserve()` still goes through `sched_new()` and re-registers callbacks; + `free_scratch` still the last `ggml_backend_i` member; Vulkan prealloc fields match `ggml_vk_cleanup`. +- F6/F7: `server_queue::start_loop` still evaluates `should_sleep()` only from the idle branch, never + inside `yield_to_queue()`; `handle_sleeping_state`, `server_res_generator`, `load_model` ordering; + signal setup in `server.cpp`. +- F8: new iterators over `ctxs_bufs` or users of `sched` on teardown paths. +- Scripts: flag spellings used by `scripts/fork-validate.sh` and the window scripts in `/root/arms/`, and the log + lines `fork-validate.sh` greps for (FORK.md F9). +- Production config: every flag in `/root/config.yaml` still exists in `common/arg.cpp`. + +## 4. Checks without a compiler + +Before handing the branch over for a build: + +```sh +git diff origin/master..HEAD | grep -n '^[+-]\(<<<<<<<\|=======\|>>>>>>>\)' # no conflict markers +git diff origin/master..HEAD | grep -nP '^\+.*[^\x00-\x7F]' # ASCII only in added lines +git range-diff "$OLD_BASE".."$OLD_TIP" origin/master..HEAD # patch vs patch +``` + +- The range-diff must show only the edits you made on purpose. In 2026-10-24 the whole patch was + identical to the old one except for 4 deliberate edits. +- Brace balance per changed file: the change in `{`/`}` balance from new base to new tip should equal + the change from old base to old tip. +- Every identifier in added lines must exist on the new master or be defined by the fork. This catches + a renamed function but not a renamed member (like `lru` -> `slru`); re-read member accesses by hand. +- Write down every spot where you would normally lean on the compiler and hand that list to whoever + builds. + +Then the owner pushes the branch to gitea, and the pod fetches it from there (section 5). + +**If you were told not to push**, do not stop at an unbuilt branch. Unless the task says otherwise, a +rebase task continues through the build and validation (sections 5 and 6) and reports the results; +the owner pushes afterwards. Get the branch onto the pod with a git bundle: +```sh +# workstation; is a commit the pod already has, e.g. production's HEAD +git bundle create /tmp/x.bundle .. +export KUBECONFIG=/home/user/Projects/klaster/talos/generated/kubeconfig +kubectl -n llama exec -i deploy/supervisord -- sh -c 'cat > /root/x.bundle' < /tmp/x.bundle +kubectl -n llama exec deploy/supervisord -- sh -c 'cd /root/llama.cpp && git fetch /root/x.bundle :' +``` +The branch is then local in `/root/llama.cpp`: in section 5 skip the `git fetch origin` and use +`git worktree add "$W" `. Delete `/root/x.bundle` afterwards (disk is tight). Deploy step 2 +likewise uses the local branch instead of fetching from origin. + +## 5. Build on the pod, in a scratch worktree + +Production keeps serving during this step. + +```sh +export KUBECONFIG=/home/user/Projects/klaster/talos/generated/kubeconfig +kubectl -n llama exec -i deploy/supervisord -- sh -c ' + set -e + B=fable5/vram-ondemand-rebase-YYYYMMDD + W=/root/arms/rebYYYYMMDD + git -C /root/llama.cpp fetch origin "$B" + git -C /root/llama.cpp worktree add "$W" FETCH_HEAD + cd "$W" + export HF_UI_VERSION=b11906 # production's: cut -d'|' -f2 /root/llama.cpp/build/tools/ui/.ui-stamp + cmake -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DGGML_VULKAN=1 -DGGML_NATIVE=ON -DLLAMA_BUILD_UI=OFF + nice -n 19 cmake --build build --target llama-server llama-bench test-backend-ops -j 8 +' +``` + +- Build only the targets you need; the full `all` target fails on the UI assets (needs npm/network). + If a tree has a stale `tools/ui/dist` with a stub `index.html`, remove it (it breaks llama-ui-embed). +- `nice -n 19 -j 8` leaves the serving models CPU. A full build takes about 3.5 minutes. +- Report compile errors verbatim against the list from step 4. +- Do not overlap a build with a large benchmark (host OOM). Disk is tight: `/root` had about 13 GB + free (97% full) on 2026-10-25, so check `df -h /root` first. Each build tree is about 700 MB; + remove scratch worktrees you no longer need with `git -C /root/llama.cpp worktree remove `. +- `-DLLAMA_BUILD_UI=OFF` does NOT make the UI asset step harmless. The `llama-ui-assets` step still + runs, and when the build number has no HF tag it falls back to `latest`. On 2026-11-21 `latest` + broke the build (missing `bundle[hash].js`, `.css` and `workbox[hash].js`). Set + `HF_UI_VERSION=` for both `cmake -B build` and `cmake --build`, where the stamp is + production's current one in `build/tools/ui/.ui-stamp` (b11906 on 2026-11-21). The file holds + `ggml-org/llama-ui|b11906` and CMake requires `^[A-Za-z0-9._-]+$`, so take only the tag with + `cut -d'|' -f2 build/tools/ui/.ui-stamp`; never pass `$(cat ...)`. The validated + worktree's UI assets may then differ from the deployed ones (the code is identical). +- Long runs: launch detached (`setsid nohup sh X > X.log 2>&1 /root/arms/X.sh' < + X.sh`), then start it alone: `setsid nohup sh /root/arms/X.sh > X.log 2>&1 X && sh -n X && setsid ... &` inside the `kubectl exec` shell. The + chain is a child of that session, and it can die with the session before `setsid` runs. + +## 6. Validate with `scripts/fork-validate.sh` + +Copy the script from the candidate tree (it is in the repo) and run it in two phases. The header of +the script describes each check. + +Rule: any test of a production model must use production's exact command line: the `cmd` of its +`/root/config.yaml` entry with the macros expanded, including the mmproj that `-hf` pulls (production +never passes `--no-mmproj` to the 35B or gemma), and supervisord's `environment=`. Change only +`--port`, the arena and scratch paths. The 2026-10-25 deploy of the disk prompt cache aborted on the +first request: every test had used `--no-mmproj`, which hid a `GGML_ASSERT(!has_mtmd)`, and it was +rolled back (FORK.md F11). + +```sh +# phase 1, beside production +# production driver environment (supervisord environment=, FORK.md section 5); fork-validate.sh keeps +# GGML_VK_ASYNC_USE_TRANSFER_QUEUE (it unsets every other inherited GGML_*), so both arms run on it +export VK_ICD_FILENAMES=/opt/mesa-26.3.1/share/vulkan/icd.d/radeon_icd.x86_64.json RADV_EXPERIMENTAL=transfer_queue GGML_VK_ASYNC_USE_TRANSFER_QUEUE=1 +bash /root/arms/rebYYYYMMDD/scripts/fork-validate.sh \ + --build /root/arms/rebYYYYMMDD/build --ref /root/llama.cpp/build --ops --diskcache +``` + +Add `--arbiter` to phase 1 only if the card has >= 1536 MiB free (8192 MiB minus the bytes in +`cat /sys/class/drm/card*/device/mem_info_vram_used`); below that it FAILs at once. With gemma-26B +warm in production only about 1.2 GiB is free and nothing frees it without downtime; then run +`--arbiter` in the phase-2 swapdown window instead (about 2 minutes more downtime), as below. + +**Page cache before and after phase 2.** The `--ref` build may lack F10 (FORK.md), and `--perf` +loads the 35B many times: during a reference arm on 2026-10-25 MemAvailable fell to 27 GB. Run the +eviction snippet of deploy step 3 before phase 2 and again after it (swapdown does not), and check +`/proc/meminfo`. + +```sh +# phase 2, with llama-swap stopped: run it under the swapdown wrapper, whose trap restarts llama-swap +cat > /root/arms/fv-perf.sh <<'EOF' +export VK_ICD_FILENAMES=/opt/mesa-26.3.1/share/vulkan/icd.d/radeon_icd.x86_64.json RADV_EXPERIMENTAL=transfer_queue GGML_VK_ASYNC_USE_TRANSFER_QUEUE=1 +HUB=/root/.cache/huggingface/hub +Q35=$HUB/models--unsloth--Qwen3.6-35B-A3B-GGUF/snapshots/a483e9e6cbd595906af30beda3187c2663a1118c/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf +G26=$HUB/models--SC117--gemma-4-26B-A4B-it-qat-heretic-GGUF/snapshots/e6759b29958180a998f62f991e4c741fe9b4d452/gemma-4-26B-A4B-it-qat-heretic-UD-Q4_K_XL.gguf +bash /root/arms/rebYYYYMMDD/scripts/fork-validate.sh \ + --build /root/arms/rebYYYYMMDD/build --ref /root/llama.cpp/build \ + --arbiter --perf --moecache "$G26" --keep +EOF +setsid nohup sh /root/bench/moe/swapdown.sh /root/arms/fv-perf.sh > /root/arms/fv-perf.log 2>&1 ` (pod-only helper, not in the repo) stops llama-swap, waits for + an idle GPU, runs the script, and restarts llama-swap from an EXIT/INT/TERM/HUP trap. It prints + `SWAPDOWN_DONE` at the end. Afterwards confirm llama-swap is RUNNING and `/v1/models` returns 200. +- `--moecache` needs a cache that actually hits (default 2048 MiB; at 256 MiB gemma-26B had 0 hits, + which proves nothing). +- `--arbiter` also checks that a cold server really frees its VRAM (`v-vram-release`, + `v-vram-restore`; SKIPs if production's VRAM moved during the measurement, then rerun) and A/Bs + ordinary handoff latency against `--ref` (`a-handoff-latency`). `--ref` must be the build currently + in production, so both comparisons are against what serves today. +- Phase 2 downtime, measured 2026-10-25: about 32 minutes in all (`--arbiter` about 2 min, `--perf` + about 28 min, `--moecache` under 30 s). The `--concat` and `--moe-exact` checks were removed on 2026-11-23 + with F3 and F1 (the history entries below still list them). +- `--perf` gates on medians of all repetition samples (since 2512290f9); the samples are in + `/perf.tsv`, and `fork-validate.sh --perf-report ` re-aggregates them offline. A pod + restart empties `/tmp`, so copy a scratch dir you want to keep to `/root/arms/` (the 2026-10-24 + scratch dirs were lost that way). +- Overlayfs (since the persistent rootfs, 2026-11-22): `/tmp` is on overlayfs, where `stat` + reports another device than `/proc/locks` prints, so a scratch arena under `/tmp` made every + token check fail (`arbiter/start: A serves but does not hold token.lock` while A held the lock). + `fork-validate.sh` from `70d39bdbc` on keeps its arenas on `/dev/shm`. Use the script of that + commit or later, also for a `--ref` run of an older build. +- Phase 1 of the 2026-11-22 rebase (candidate build `/root/arms/reb20261122/build`, code + `6c895a491`, scripts `70d39bdbc`, vs production `f3397cded`, beside production with 3579 MiB + free; logs `/root/arms/reb20261122-p1.log`, `-p1b.log`): `--ops --concat --diskcache` 23 PASS + (ops 5/5 with FLASH_ATTN_EXT 5693/5693, concat off/cand 5.3x, diskcache 15/15 including the GPU + legs), `--arbiter` 16 PASS on the rerun with the fixed script (handoff median cand 789.5 / ref + 768 ms; the first run's single FAIL was the overlayfs mismatch above). F12: test-backend-ops + SCALE and FLASH_ATTN_EXT OK, `test-flash-attn-indexed-bias` 16 Vulkan0 cases, max error 1.3e-4. + Still to run in the window: phase 2 (`--arbiter --perf --moe-exact --moecache`, the runbook + command with this build path) and the Inkling/F14 items below. +- Overnight window 2026-11-23 (the plan below, run in full; queue runner + `/root/arms/overnight2/runner.sh` with one swapdown window per script, progress log + `/root/arms/overnight2/STATUS.md`): phase 2 `--arbiter --perf --moe-exact --moecache` on + `27c23d20f` vs production `f3397cded`, 29 PASS, 0 FAIL, 0 SKIP in 33 minutes (log + `done/10-win1.log`, scratch copied to `fv-phase2-scratch/`). Perf medians ref -> cand: pp2048 + 286.29 -> 286.60, d16384 207.77 -> 208.06, d32768 161.48 -> 162.17, tg256@d4096 14.87 -> 14.29 + (not gated); handoff median ref 710.5 / cand 699.5 ms; peak VRAM 5478 MiB both. Items 2-5 passed + (FORK.md F12 `--fit` result, F13 window A/B result, F14 items 5-7, F15 window result); Inkling + answers on both entries correct, tool calls work on both (no #32800 HTTP 500, no #32818 grammar + crash). Deployed `ec3bf13f6` (`27c23d20f` + F15) with `LLAMA_LOOP_FULL_COPY=0` on the Inkling + entries; deploy script `/root/arms/overnight2/deploy.sh` (pointer, build copy, config backup, + in-place build, probe, automatic rollback on a failed build or probe), downtime 225 s. Later in the window + (config and environment only, each with its backup): Mesa 26.3.1 with the transfer queue for + llama-swap (`/root/arms/overnight2/mesa-switch.sh on|off`, backup + `/root/supervisord.conf.bak-20261123-mesa`), and `moe_offload_args` `-t 4 -b 4096 -ub 4096` + (backup `/root/config.yaml.bak-20261123-prefinal`); FORK.md section 5. Post-deploy checks of + section 8 passed after the deploy and again after the Mesa switch (`post.log`, `post-mesa.log`). + Two traps: `llama-fit-params` rejects `--mmproj` and `--jinja`, and llama-bench separates + `-ot` overrides with `;` (`,` starts a new test group), unlike llama-server. +- Slimming, 2026-11-23 day windows (status log `/root/arms/run3/STATUS.md`, scripts and logs in + `/root/arms/run3/`, each window under swapdown). Window 1 (09:50-11:26 UTC): candidate C + (`fa89f2cb3`, F1 and F3's gate still in) vs production `ec3bf13f6`, `--ops --concat --arbiter + --perf --moe-exact --moecache --diskcache` 52 PASS, 0 FAIL, 0 SKIP (`fv.log`), plus the ablations + that removed F1 and the gate (FORK.md section 2). Window 3 (11:31-11:57): candidate S + (`ccb58a3dc`, F1 and F3 removed) `--ops --arbiter --moecache --diskcache --perf`: 26 PASS, 2 FAIL + (`fv3.log`). Both FAILs and a silently skipped `--perf` were a script bug, not the code: removing + `--moe-exact` had also removed `gpu_exclusive` and the `--diskcache` prompt helper (FORK.md F9). + Fixed in `a1eb757ea` (script only). Window 4 (11:58-12:53): `--perf --diskcache` with the fixed + script, 19 PASS, 0 FAIL, 0 SKIP (`fv4.log`): pp2048 307.40 -> 321.20 t/s (+4.5%), d16384 220.59 + -> 225.22 (+2.1%), d32768 169.86 -> 174.81 (+2.9%), tg256@d4096 11.69 -> 12.74 (not gated), peak + VRAM candidate 5700 MiB; handoff median 635.5 ms both (window 3). Gate check (decode of the other + delta-net / short-conv models without F3's gate, C vs S, `win3.log`, `gate4.log`): Qwen3.5-4B tg256@d4096 -0.4%, Inkling +2.8% (medians of 9 samples, S C C S S C), Inkling concat kernels +0.3 ms per token (perf logger); the gate stays removed. Inkling tool request + (251 tokens, fresh prompt, production command line, S): `-tb 12` 10612 / 9961 ms median prompt + time against `-tb 6` 5231 / 5278 ms, decode unchanged, `get_weather` with city Warsaw in every arm (arguments cut by `max_tokens` 64) + (`inktb-s/`); llama-bench Inkling pp256 and pp2048 with 12 and 6 threads, arms 12 6 6 12: 83.7 / 128.9 t/s either way, so `-tb 6` costs no prefill (FORK.md section 5). Deploy: below. +- What the 2026-11-22 window must run, in this order (GPU to itself under swapdown; about 75-90 + minutes in all): + 1. Phase 2 as written above with `W=/root/arms/reb20261122` (about 32 minutes). + 2. F13 vs upstream's #32807 (FORK.md F13, "Window A/B to run": memory, `kld48.sh`, speed with + `LLAMA_LOOP_HOST_VIEWS=0` and `LLAMA_LOOP_FULL_COPY=0`). + 3. `--fit` vs the k=4 `-ot` for Inkling (FORK.md F12, "How to use it for Inkling"). Smoke run + beside production (3.5 GiB free, so not a placement result; `/root/arms/reb20261122-fit-smoke.log`): + fit's loop path runs on Inkling; the probing took 27.8 s, which every Inkling cold start would + pay with `--fit` in the config (freeze the printed `-ot` instead); the projected memory is not + monotonic in `n_layer` (5173 MiB at 44, 6736 at 43) and fit still reported success with -3116 + MiB free. Check both with the full card. + 4. F14 refinement (FORK.md F14, validation plan items 5-7): the new-chat checkpoint, its disk-cache + variant and the M-only TTFT table, with the 35B think entry's exact command line. + 5. The Inkling post-deploy items of section 8 step 8 against a scratch server of the candidate: + #32799 changed Inkling's tokenization, so judge the answer text. +- F14 run (2026-11-22, candidate `f3397cded` = `166ec22e2` (docs on `b13c41355`) + F14, server-only change; one + swapdown window, `/root/arms/usw-window.sh`, log `/root/arms/usw-window.log`, about 15 minutes): + the 35B TTFT A/B with and without `LLAMA_USERSTART_MERGE=0` (FORK.md F14, M U U M, production 35B + think command line with the mmproj), `--diskcache` 15 PASS, 0 FAIL, 0 SKIP, and the + `diskcache-window3.sh` 35B legs (all passed). The full `--perf`/`--arbiter` set was not rerun: the + change touches only the server prompt-batch loop. Deploy downtime 33 s (incremental in-place + build). +- Last full run (2026-11-22, candidate `b13c41355` = `3621025e8` + F13 vs reference `3621025e8`, one + swapdown window, `--ops --concat --diskcache --arbiter --perf --moe-exact --moecache`, log + `/root/arms/overnight/fv.log`): 52 PASS, 0 FAIL, 0 SKIP in 41 minutes. Perf medians ref -> cand: + pp2048 286.61 -> 284.94 (-0.6%), d16384 207.93 -> 207.96, d32768 161.93 -> 162.12, tg256@d4096 + 14.11 -> 14.47; handoff median ref 715 / cand 706.5 ms; peak VRAM ref 5478 / cand 7771 MiB (the + first-arm spike of FORK.md F9, this time in a candidate arm). With the card free, phase 1 and 2 + can run as one invocation like this. +- Previous full run (2026-11-22, candidate `3621025e8` = `3bf6b55b3` + the F12 carries, vs reference + `3bf6b55b3`; logs `/root/arms/carry1122-p1.log`, `-p2.log`): phase 1 `--ops --concat --diskcache` + 20 PASS, 1 FAIL (`concat/candidate-timing` beside a full card, see above), 1 SKIP (diskcache GPU + leg); phase 2 `--concat --arbiter --diskcache --perf --moe-exact --moecache` 47 PASS, 0 FAIL, 0 + SKIP. Perf medians ref -> cand: pp2048 286.97 -> 286.32, d16384 208.31 -> 208.21, d32768 162.25 -> + 162.37; handoff median ref 696 / cand 700 ms; peak VRAM ref 7771 / cand 5502 MiB. Plus SCALE + 15/15 and `test-flash-attn-indexed-bias` (FORK.md F12). Window about 30 minutes. +- Earlier full run (2026-11-21, candidate `3bf6b55b3` vs reference `adc2aa3ec`): phase 1 39 PASS, phase 2 + 9 PASS plus the 35B disk-cache legs (`q35.py`, mmproj loaded). Perf medians ref -> cand: pp2048 + 259.39 -> 286.61 (+10.5%), d16384 199.26 -> 207.63 (+4.2%), d32768 156.61 -> 157.51 (+0.6%), + tg256@d4096 9.17 -> 8.85 t/s (noisy, not gated). Handoff median: candidate 692 ms, reference + 1068 ms. Downtime: about 42 minutes of validation and about 7 minutes of deploy. +- Earlier full run (2026-10-25, candidate `2fc9f9c35` vs reference `6c480f7e7`, logs + `/root/arms/dep-2fc9f9c35-fv1.log` and `-fv2.log`): phase 1 `--ops --concat` 8 PASS, phase 2 + `--arbiter --perf --moe-exact --moecache` 29 PASS; 37 PASS, 0 FAIL. Perf medians ref/cand: pp2048 + 274.53/273.82, d16384 200.52/200.37, d32768 157.60/157.57, tg256@d4096 16.82/16.66 t/s. Handoff + median ref 693.5 / cand 678 ms. `--moe-exact`: 39 skips logged, identical to the reference and to + the skip forced off. Peak VRAM per arm ref 5476, cand 7062, cand 5767, ref 5476 MiB: the ~1.6 GiB + spike in the first candidate arm has now been seen twice (open question, FORK.md F9). +- Any arbiter change: `a-handoff-latency` is the ordinary-handoff A/B that two lost deploys showed + is needed. For a change aimed at latency itself, also run more blocks by hand; 25%/200 ms is a + regression gate, not a measurement. +- Disk prompt cache (FORK.md F11, from `fable5/disk-prompt-cache`): add `--diskcache` to phase 1. It + is CPU only and runs beside production (about 2 minutes). Its GPU leg SKIPs below 1536 MiB of free + VRAM; then run `--diskcache` again in the phase-2 window. A 35B measurement driver is on the pod: + `/root/arms/diskcache-test/q35.py [CHARS]` (scratch port 8095, scratch arena and cache dir, the + production 35B flags, a pan-tadeusz conversation; about 6 minutes). The 2026-10-25 window script + `/root/arms/diskcache-window.sh` (page-cache evictions, `--diskcache --arbiter`, `q35.py`) runs + under swapdown (run 2026-10-25: 29 PASS). `/root/arms/diskcache-window3.sh` runs `q35.py` + with production's exact 35B command line (mmproj loaded): save/restore, cold save, the + same-reuse-point identity and an image request (FORK.md F11). Run 2026-11-21 on adc2aa3ec: all + legs passed (18.8k-token chat, prefill 84.6 s -> turn 2 4.7 s after the restart, identical + output; save 557 MB in 1.0 s, token free 0.34 s, peak RSS +430 MB; cold save identity; image + answered and not saved; log `/root/arms/diskcache-test/q35-mm.log`). It supersedes + `diskcache-window2.sh` (`cmp.py` runs with `--no-mmproj`). + `q35.py` and the window scripts live only on the pod (not in the repo) and hard-code a build path. + Before each use, edit them to point at the candidate build (`/root/arms/rebYYYYMMDD/build`), not + production's `/root/llama.cpp/build`, or you validate the wrong binary. + +On any FAIL: stop and report; the scratch dir (`/tmp/fork-validate.*`) is kept with all logs. + +## 7. Deploy + +Deploy exactly the validated commit. Downtime: 6 minutes for the 2026-10-24 redeploy. The deploy +rebuilds the production tree in place (step 6) from the same commit and with the same cmake flags as +the validated worktree build, so nothing is copied over; compare +`grep -E 'GGML_NATIVE|LLAMA_BUILD_UI|BUILD_SHARED_LIBS|CMAKE_BUILD_TYPE' build/CMakeCache.txt` in both +trees if in doubt. + +Run the stop, build and start (steps 4-7) as one script on the pod, started with `setsid nohup sh +