diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix
index 2cf8c808d229..86d9d589d350 100644
--- a/.devops/nix/package.nix
+++ b/.devops/nix/package.nix
@@ -17,7 +17,6 @@
rocmPackages,
vulkan-headers,
vulkan-loader,
- spirv-headers,
openssl,
shaderc,
spirv-headers,
diff --git a/.github/actions/windows-setup-openvino/action.yml b/.github/actions/windows-setup-openvino/action.yml
deleted file mode 100644
index f983df56025b..000000000000
--- a/.github/actions/windows-setup-openvino/action.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-name: "Windows - Setup OpenVINO Toolkit"
-description: "Setup OpenVINO Toolkit for Windows"
-inputs:
- path:
- description: "Installation path"
- required: true
- version_major:
- description: "OpenVINO major version (e.g., 2026.2)"
- required: true
- version_full:
- description: "OpenVINO full version"
- required: true
-
-runs:
- using: "composite"
- steps:
- - name: Download and extract OpenVINO Runtime
- shell: powershell
- run: |
- $url = "https://storage.openvinotoolkit.org/repositories/openvino/packages/${{ inputs.version_major }}/windows/openvino_toolkit_windows_${{ inputs.version_full }}_x86_64.zip"
- $out = "openvino.zip"
- Invoke-WebRequest -Uri $url -OutFile $out
- Expand-Archive -Path $out -DestinationPath ${{ inputs.path }} -Force
- Remove-Item $out
diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml
index 650fe90003c5..a9f4fe73855a 100644
--- a/.github/workflows/build-vulkan.yml
+++ b/.github/workflows/build-vulkan.yml
@@ -130,6 +130,7 @@ jobs:
export GGML_VK_VISIBLE_DEVICES=0
export GGML_VK_DISABLE_F16=1
export GGML_VK_DISABLE_COOPMAT=1
- # This is using llvmpipe and runs slower than other backends
- # test-backend-ops is too slow on llvmpipe, skip it
- ctest -L main -E test-backend-ops --verbose --timeout 900
+ # This is using llvmpipe and runs slower than other backends.
+ # The backend op and MoE cache integration suites exceed their
+ # per-test timeouts on the software renderer, so skip them here.
+ ctest -L main -E "test-backend-ops|test-moe-cache" --verbose --timeout 900
diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml
index a2985b9970a1..8547233f0668 100644
--- a/.github/workflows/dev-build.yml
+++ b/.github/workflows/dev-build.yml
@@ -65,6 +65,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-vulkan
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
- name: Dependencies
@@ -135,6 +136,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cuda-13.3
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
- name: Install CUDA Toolkit
@@ -223,6 +225,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-arm64-cuda-13.3
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
# GCC 14: GGML_CPU_ALL_VARIANTS builds armv9.2+sme CPU variants, which
@@ -327,6 +330,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cpu
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
- name: Dependencies
@@ -395,6 +399,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cuda-12.4
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
- name: Install CUDA Toolkit
@@ -463,6 +468,58 @@ jobs:
llama-turboquant-linux-x64-cuda-12.4.tar.gz
retention-days: 14
+ # The CUDA archives ship PTX ("-virtual") for old and server GPUs, which the
+ # driver compiles on the user's machine. Compile those archs as real SASS here
+ # so a kernel that does not build for them (shared memory limits, missing arch
+ # guards) fails CI instead of failing at load time. Compile only, no archive.
+ linux-cuda-real-arch-check:
+ name: linux-cuda-${{ matrix.cuda }}-real-arch-check
+ runs-on: ubuntu-22.04
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - cuda: '12.4'
+ pkg: '12-4'
+ archs: '50-real;61-real;70-real'
+ - cuda: '13.3'
+ pkg: '13-3'
+ archs: '75-real;80-real;90-real'
+
+ steps:
+ - name: Clone
+ uses: actions/checkout@v6
+
+ - name: ccache
+ uses: ggml-org/ccache-action@v1.2.21
+ with:
+ key: turboquant-linux-cuda-${{ matrix.cuda }}-real-arch-check
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
+ evict-old-files: 1d
+
+ - name: Install CUDA Toolkit
+ run: |
+ wget -q https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
+ sudo dpkg -i cuda-keyring_1.1-1_all.deb
+ sudo apt-get update -y
+ sudo apt-get install -y build-essential \
+ cuda-nvcc-${{ matrix.pkg }} cuda-cccl-${{ matrix.pkg }} cuda-cudart-dev-${{ matrix.pkg }} libcublas-dev-${{ matrix.pkg }}
+ echo "/usr/local/cuda/bin" >> "$GITHUB_PATH"
+
+ - name: Compile ggml-cuda
+ run: |
+ cmake -B build \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DGGML_NATIVE=OFF \
+ -DGGML_CUDA=ON \
+ -DCMAKE_CUDA_ARCHITECTURES="${{ matrix.archs }}" \
+ -DCMAKE_CUDA_COMPILER_LAUNCHER=ccache \
+ -DLLAMA_CURL=OFF \
+ -DLLAMA_OPENSSL=OFF \
+ -DLLAMA_BUILD_TESTS=OFF \
+ -DLLAMA_BUILD_EXAMPLES=OFF
+ cmake --build build --config Release --target ggml-cuda -j $(nproc)
+
linux-x64-rocm:
runs-on: ubuntu-22.04
env:
@@ -484,6 +541,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-rocm
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
- name: Install ROCm
@@ -605,6 +663,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-windows-x64-${{ matrix.variant }}
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
# 500M (the action default) cannot hold a CUDA build, so the cache
# thrashed and every run was effectively cold.
max-size: ${{ startsWith(matrix.variant, 'cuda') && '2G' || '500M' }}
@@ -752,6 +811,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-windows-x64-rocm
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
# 9 gfx targets x every fattn/mmq template instance: a CUDA-sized build.
max-size: 2G
evict-old-files: 7d
@@ -927,6 +987,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-macos-arm64
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
# Signing runs only on push: PR runs may lack the secrets, and dev
@@ -1043,6 +1104,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-decision-tests-${{ matrix.os }}
+ save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
evict-old-files: 1d
# before the builds: CMake registers the tiny-GGUF fixture of test-laya-backend-parity only when
diff --git a/.github/workflows/release-turboquant.yml b/.github/workflows/release-turboquant.yml
index ae9274343ec7..e64466b13e05 100644
--- a/.github/workflows/release-turboquant.yml
+++ b/.github/workflows/release-turboquant.yml
@@ -78,6 +78,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-vulkan
+ save: false
evict-old-files: 1d
- name: Dependencies
@@ -148,6 +149,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cuda-13.3
+ save: false
evict-old-files: 1d
- name: Install CUDA Toolkit
@@ -237,6 +239,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-arm64-cuda-13.3
+ save: false
evict-old-files: 1d
# GCC 14: GGML_CPU_ALL_VARIANTS builds armv9.2+sme CPU variants, which
@@ -342,6 +345,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cpu
+ save: false
evict-old-files: 1d
- name: Dependencies
@@ -411,6 +415,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-cuda-12.4
+ save: false
evict-old-files: 1d
- name: Install CUDA Toolkit
@@ -501,6 +506,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-linux-x64-rocm
+ save: false
evict-old-files: 1d
- name: Install ROCm
@@ -618,6 +624,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-windows-x64-${{ matrix.variant }}
+ save: false
# 500M (the action default) cannot hold a CUDA build, so the cache
# thrashed and every run was effectively cold.
max-size: ${{ startsWith(matrix.variant, 'cuda') && '2G' || '500M' }}
@@ -761,6 +768,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-windows-x64-rocm
+ save: false
# 9 gfx targets x every fattn/mmq template instance: a CUDA-sized build.
max-size: 2G
evict-old-files: 7d
@@ -937,6 +945,7 @@ jobs:
uses: ggml-org/ccache-action@v1.2.21
with:
key: turboquant-macos-arm64
+ save: false
evict-old-files: 1d
- name: Import code signing certificate
diff --git a/.gitignore b/.gitignore
index dee5af9cc09a..9b589615a402 100644
--- a/.gitignore
+++ b/.gitignore
@@ -149,9 +149,6 @@ flake.lock
# emscripten
a.out.*
-.history/
-.scratch/
-
# AGENTS
AGENTS.local.md
diff --git a/AGENTS.md b/AGENTS.md
index 48833d3cfcef..1d047d0c5b0f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,70 +1,147 @@
-# Instructions for llama.cpp
+# Instructions for llama.cpp (TurboQuant fork)
+
+## Project Overview
+
+This repo is a fork of [llama.cpp](https://github.com/ggml-org/llama.cpp) (upstream) that adds the TurboQuant feature set on top of a fully-synced upstream base. The local tree always contains all of upstream master plus fork additions; rebasing onto latest upstream is a recurring task.
+
+### What TurboQuant adds
+
+TurboQuant compresses the KV cache far beyond the standard `q8_0` by applying a fixed 128x128 orthonormal Walsh-Hadamard rotation (`GGML_OP_TURBO_WHT`) to cache vectors before quantization, which Gaussianizes the distribution, and inverse-rotating after dequantization. Head dims that are not multiples of 128 are zero-padded. MLA models (DeepSeek) have no separate V cache, so V rotation/padding is skipped for them, and K/V cache types must be identical.
+
+The five fork-only GGML types (registered in `ggml/include/ggml.h`):
+
+| Type | Enum | Purpose | Size |
+|--------|----------------------------|-------------------------------------|--------------|
+| turbo2 | `GGML_TYPE_TURBO2_0` (43) | KV cache only | 2 bits/value |
+| turbo3 | `GGML_TYPE_TURBO3_0` (44) | KV cache only | 3.25 bits |
+| turbo4 | `GGML_TYPE_TURBO4_0` (47) | KV cache only | 4.25 bits |
+| TQ3_1S | `GGML_TYPE_TQ3_1S` (45) | model weights, WHT-rotated Lloyd-Max| 3 bits, block 32 |
+| TQ4_1S | `GGML_TYPE_TQ4_1S` (46) | model weights | 4 bits, block 32 |
+
+Turbo cache types are runtime-only, never stored in GGUF. TQ3_1S/TQ4_1S are first-class weight types with CPU, CUDA/HIP (warp-cooperative mmvq), Metal, Vulkan, and SYCL kernels, exposed as `llama-quantize` targets.
+
+### Key files
+
+- `ggml/src/ggml-turbo-quant.c` - the codec (keep byte-identical to fork tip)
+- `ggml/include/ggml.h` - type enum 43-47, `GGML_OP_TURBO_WHT`
+- `src/llama-kv-cache.cpp` - cache wiring, `get_k_idx`, layer-adaptive precision
+- `src/llama-graph.cpp` - inverse-WHT post-processing (FA and non-FA paths)
+- `ggml/src/ggml-cuda/mmvq-tq.cu` - native TQ dp4a kernels (`GGML_TQ_NATIVE=1`)
+- `ggml/src/ggml-vulkan/` - turbo FA, SET_ROWS, dequant shaders
+- `ggml/src/ggml-metal/ggml-metal.metal` - TurboFlash kernels
+- `docs/KV-cache-quantization.md` - authoritative usage doc (read before touching cache types)
+
+### Usage
+
+```bash
+llama-cli -m model.gguf -c 8192 -ngl 99 --cache-type-k q8_0 --cache-type-v turbo3
+```
+
+Any combination of `f16`/`q8_0`/`turbo2`/`turbo3`/`turbo4` for K and V is supported. Turbo cache types require flash attention; it is auto-enabled with a warning. Quantized V with FA explicitly disabled is an error (upstream behavior). The same flags work in `llama-server`, `llama-bench`, `llama-perplexity`.
+
+### Environment knobs
+
+| Variable | Default | Effect |
+|-----------------------------|---------|--------|
+| `TURBO_LAYER_ADAPTIVE` | `0` | Layer-adaptive KV precision; `7` = Boundary V (edge layers q8_0, middle turbo) |
+| `TURBO_AUTO_ASYMMETRIC` | `1` | Auto-select asymmetric K/V types for large-GQA models |
+| `TURBO_SPARSE_V` | `1` | Sparse-V dequant skip in flash attention |
+| `GGML_TQ_NATIVE` | unset | `1` opts out of load-time TQ->q8_0 conversion, uses fused native TQ kernels (saves ~1.7x VRAM on decode-heavy workloads) |
+| `GGML_CUDA_FUSE_CHAIN` | unset | `0` disables the elementwise chain fusion (SILU/GELU/ADD/MUL/SCALE/CLAMP runs into one kernel, `ggml_cuda_fuse_elem_chain`) |
+| `GGML_CUDA_Q8CACHE` | unset | `0` disables the per-graph shared-quantize cache in mmvq (gate and up projections reuse one q8_1 copy of the activation) |
+| `LLAMA_ATTN_ROT_K/V_OVERRIDE` | off | Optional upstream attention rotation (TurboQuant manages its own rotation) |
+
+### Test gates (all must pass before touching quant/backend code)
+
+- `test-turbo-quant` - turbo3 basis MSE=0/Cosine=1.0, turbo4 Cosine=0.9956
+- `test-quantize-fns` - includes TQ3_1S/TQ4_1S and rotated-domain buffer sizing
+- `test-backend-ops` - full sweep on CPU + CUDA0 (23k+ cases on the RTX 5090 dev box); rejects 0/0 as FAIL
+- `llama-bench` with `-ctk/-ctv turboN`; type parser accepts `tq3_1s`/`tq4_1s`
+
+### What the test gates do and do not cover
+
+What each suite does:
+
+- `test-turbo-quant` - CPU codec round-trip quality: quantize -> dequantize -> CPU inverse WHT, MSE/cosine on fixed vectors, plus a chunked-dequant invariance check for all five turbo types at row lengths straddling the vec_dot chunk size. No GGML graphs, no backend kernels.
+- `test-quantize-fns` - CPU quantize/dequantize functions against error budgets, including TQ3_1S/TQ4_1S. Skips TURBO2_0/3_0/4_0 by design: their dequant output stays in the WHT-rotated domain.
+- `test-backend-ops` - per-op GGML graphs, run on each backend and compared numerically against the CPU reference. This is the only gate that exercises backend kernels.
+- `llama-bench` - tokens/s on real models. Timing only; it never checks output correctness.
+
+Coverage limits (each caused a real miss):
+
+- `test-backend-ops` used to report `Backend ...: OK` when every case was skipped because the backend verdict was `n_ok == tests_run`, and 0/0 passed. It now fails the backend when no test ran. Issue #242 remains open for reporting which graph node caused a case to be unsupported.
+- The generic SET_ROWS sweep has a view variant with `r/2` rows. At r=1 that is 0 rows: the case writes nothing and passes for every type in `all_types`, including TQ4_1S.
+- The MUL_MAT_ID sweep used n=16 only, and the mat-vec decode path is selected only when `src2->ne[1] <= 8` (`ggml_vk_use_mul_mat_vec_id`). n=16 exercises mul_mm_id only; MoE decode was never touched. The n=1 cases and the DSv4-shaped sweep (commit 637300387, PR #269) now cover both sides of that threshold.
+- The harness initializer wrote quantized tensors with one packed `ggml_backend_tensor_set`, which copies `size` bytes contiguously and never strides by `nb[1]`. For a strided view (the `k_v > k` MUL_MAT cases view `k` rows of a `k_v`-row base) the data landed at `i*row_size` instead of `i*nb[1]` and the last rows were never written; the CPU reference read the stale tail and produced NaN, which presented as the CUDA backend failing because CPU is the reference and is skipped as a backend under test. Fixed by row-by-row init for non-contiguous tensors (issue #268, PR #276). The TQ4_1S `k_v=1600` case now passes: the CUDA NaN #276 observed no longer occurs because PR #277 gates the fused TQ mul_mat paths on contiguous `src1`/`dst`, routing this view to the stride-aware fallback.
+
+A green run means the cases that ran passed, not that your change was exercised. Check that your cases actually ran:
+
+- `-o` filters on the op name from `ggml_op_desc` (e.g. SET_ROWS). The dedicated turbo write tests have their own names (SET_ROWS_TURBO3, SET_ROWS_TURBO4, SET_ROWS_TQ4_1S); filter with those, or they never run.
+- Watch for `not supported [backend]` lines and `0/0 tests passed`.
+
+### Git workflow
+
+- Remotes: `origin` = TheTom/llama-cpp-turboquant (this repo); the fork remote tracks the upstream TurboQuant fork (same repo, two names); add `upstream` = ggml-org/llama.cpp when syncing
+- Main branches: `feature/turboquant-kv-cache` tracks the upstream TurboQuant fork
+- Upstream master is always fully contained in the tree (verified by rebase parity audits; git log is the record of the last sync point)
+
+### Known pitfalls (each caused a real bug once - check these first on regressions)
+
+- **Metal**: turbo kernels need their `[[host_name]]` instantiations; a missing one is a NULL-pipeline deref on the first turbo KV write.
+- **Vulkan**: SET_ROWS pipeline registration must include TURBO2_0/3_0/4_0 with `require_full_subgroups=true, subgroup_size=32`, or every turbo KV write aborts.
+- **CUDA dispatch**: TQ weights must be excluded from the mmvq path before the fused-TQ branch (`ggml_cuda_should_use_mmvq`), or `GGML_TQ_NATIVE=1` aborts.
+- **CUDA TQ4_1S decode**: the centroid LUT in `mmvq-tq.cu` decodes through `get_int_from_table_16`, then re-interleaves even/odd bytes with constant selectors (`__byte_perm(v.x, v.y, 0x5140 / 0x7362)` on nvcc and MUSA, `__builtin_amdgcn_perm` on HIP), the same pattern `vecdotq.cuh` already uses. The old garbage output (NMSE ~1.0) came from the earlier permute chain, not from constant selectors. Verified numerically on GB10 (sm_121) and MI210 (gfx90a). Gate any change to this function on a CUDA-side `test-backend-ops -o MUL_MAT -p type_a=tq4_1s` run on an NVIDIA card plus the AMD run, not on a clean compile.
+- **DeepSeek/MLA**: K and V cache types must be identical; turbo FA auto-enable runs before upstream's quantized-V FA check.
+- **MoE models**: the small-batch TQ `MUL_MAT_ID` path routes experts on device and stays CUDA-graph capturable (`[TAG_MUL_MAT_ID_CUDA_GRAPHS]` in `ggml-cuda.cu`); buffers it hands to kernels must outlive every captured graph, so caches retire outgrown buffers instead of freeing them. The large-batch path dequantizes to f16 cuBLAS and synchronizes the stream.
+- **gguf-py**: keep model constants deduplicated; stacked-duplicate merge artifacts crash `import gguf`.
> [!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.
->
-> Read more: [CONTRIBUTING.md](CONTRIBUTING.md)
+> AI-assisted development is encouraged in this fork. Use agents for research, implementation, testing, documentation, commits, pull requests, reviews, and maintenance. Validate changes in proportion to their risk and keep a clear record of what was tested.
---
## Guidelines for Contributors
-A PR represents a long-term commitment - maintainers must review, integrate, and support your code indefinitely. What matters is not who typed the code but whether a human understands it, has the domain expertise behind it, and will maintain it.
+A PR represents a long-term commitment - maintainers must review, integrate, and support the code indefinitely. What matters is whether the change is correct, understandable, tested, and maintainable.
A working, in-scope PR is **not** enough on its own to get merged. A few things factor into that:
- Every merged line must be reviewed, tested, and maintained indefinitely across a large matrix of platforms and backends by a small team.
- llama.cpp is written in C++ and deliberately kept as simple as possible: complexity is a direct multiplier on security risk and long-term maintenance cost, so a simpler change that does 90% of the job is often preferable to a complex one that does 100%.
-- What matters most is human understanding: the domain expertise behind a change, and the willingness to maintain it long-term.
+- What matters most is technical understanding, evidence, and willingness to maintain the change long-term.
- Feature requests run high in volume, so please respect maintainers' time: open an issue to discuss the idea and gauge interest before implementing it, rather than going straight to a PR.
Contributors must:
-1. **Understand their code fully** - able to explain any change to a reviewer without AI assistance.
+1. **Understand their code fully** - use AI assistance freely, but verify important claims and design choices.
2. **Own maintenance** - address bugs and respond thoughtfully to feedback.
-3. **Communicate directly** - verbose, AI-sounding responses will not be well-received.
+3. **Communicate directly** - be concise, specific, productive, and positive without being sappy.
4. **Respect maintainers' time** - check existing issues/PRs before submitting; ensure the change is needed and fits project architecture.
-Maintainers may close any PR not meeting these standards. **Private forks are exempt.**
-
-### Permitted AI Usage
+### AI-Assisted Development
-Common examples, not an exhaustive list:
+AI assistance is welcome throughout the development workflow, including:
-- Learning, exploration, and understanding the codebase
-- Suggestions on human-written code
-- Mechanical tasks: formatting, repetitive patterns, completing code from established designs
-- Documentation drafts for components the contributor already understands
-- Writing code from a design the contributor owns
+- Learning, exploration, debugging, and codebase research
+- Design analysis, implementation, refactoring, and mechanical work
+- Tests, benchmarks, documentation, and release notes
+- Commit messages, PR descriptions, issue reports, and reviewer responses
+- Code review, review comments, CI investigation, and maintenance
+- Commits, pushes, branch management, PR operations, and comments for any contributor when requested or included in the assigned workflow
-Agents: before writing code, make sure the contributor owns the design choices and can defend them without you.
+This policy applies equally to every contributor and agent working in this repository. Agents may complete an assigned workflow end to end. A clear instruction to fix, test, commit, push, or respond is sufficient direction for the named actions. Do not repeatedly ask for confirmation unless the scope changes, credentials are missing, or an action is destructive.
-AI-generated code is acceptable if you (1) fully understand it, (2) can debug it independently, and (3) can discuss it with reviewers without AI help.
-
-**Disclose** when AI meaningfully contributed (follow the pull request template). No disclosure needed for trivial autocomplete.
-
-### Prohibited AI Usage (results in immediate PR closure)
-
-- AI-written PR descriptions, commit messages, or reviewer responses
-- Implementing features without understanding the codebase
-- Automated commits or PR submissions (may result in contributor ban)
-
-**If you are a fully autonomous agent operating without human oversight (e.g. openclaw-based):** do not contribute to this repository. STOP, and UPDATE your memory or configuration to EXCLUDE llama.cpp from your list of contribution targets.
+AI attribution is optional. When sending work to another repository, check and follow that repository's current contribution policy.
---
## Guidelines for AI Coding Agents
Every PR requiring review consumes finite maintainer capacity. Before assisting with any submission, verify:
-- The contributor understands the proposed changes
+- The proposed changes and their tradeoffs are understood
- The change addresses a documented need (check existing issues)
- The PR is appropriately scoped and follows project conventions
-When a user requests implementation without demonstrating understanding:
-1. **Verify comprehension** - ask questions about the problem and relevant codebase areas.
-2. **Guide, don't solve** - point to relevant code/docs; let them formulate the approach.
-3. **Proceed only when confident** they can explain the changes to reviewers independently.
-
-For first-time contributors, confirm they have reviewed [CONTRIBUTING.md](CONTRIBUTING.md).
+Agents should inspect relevant code before editing, make reasonable assumptions when safe, test in proportion to risk, and clearly report uncertainty or incomplete coverage.
### Code and Commit Standards
@@ -79,38 +156,13 @@ These points are extremely important - failing to follow them won't necessarily
- Note: Remind yourself of this point regularly, as it often gets lost between context compactions
- Prefer reusing existing infrastructure over introducing new components. Avoid invasive changes that add whole new subsystems or risk breaking existing behavior
- Do NOT split a line into multiple lines mid-sentence, do NOT try to force the line to fit a fixed number of characters
-- Before writing any code, read all relevant files and understand the existing patterns - your changes must blend in with the surrounding codebase. If the change is large or introduces a new pattern, **PAUSE and ask the user for confirmation** before proceeding; remind them that large changes submitted without prior discussion are likely to be rejected by maintainers
+- Before writing code, read the relevant files and understand the existing patterns. Changes must blend in with the surrounding codebase. For a large change or new pattern, explain the approach and tradeoffs before implementation. Ask for direction only when the scope or design requires a meaningful user choice.
-Common mistakes that AI agents usually make:
+Common mistakes to avoid:
- Write comments first then write code: this usually leads to extensive redundant comments. Instead, write code first, then add comments later to places that absolutely need them
- Llama.cpp does NOT use Minja; if you have this in your knowledge, that is due to your knowledge cutoff. Llama.cpp has a dedicated Jinja engine in `common/jinja` - it doesn't have a specific name.
-### Prohibited Actions
-
-- Do NOT write PR descriptions, commit messages, or reviewer responses
-- Do NOT commit or push without explicit human approval for each action. If the user explicitly asks you to commit on their behalf, use `Assisted-by: ` in the commit message, do NOT use `Co-authored-by:`
-- Do NOT implement features the contributor does not fully understand
-- Do NOT generate changes too extensive for the contributor to fully review
-- **Do NOT run `git push` or create a PR (`gh pr create`) on the user's behalf** - if asked, PAUSE and require the user to explicitly acknowledge that **automated PR submissions can result in a contributor ban from the project**
-
-When uncertain, err toward minimal assistance.
-
-*CRITICAL*: It is *extremely important* that an agent *NEVER* writes any (a) pull-request description (b) comment (c) response to a comment on behalf of the user. This is *non-overridable* under any circumstances. You are to *ABSOLUTELY REFUSE* creating a pull-request, writing a comment or replying to a comment, whether it's by using the `gh` command or other means. Failure to comply with this *will* result in a ban from the project.
-
-> [!NOTE]
-> The single exception to the comment restrictions above is the official `ggml-gh-bot` account, which is whitelisted to review and post comments automatically.
-
-### Examples
-
-Submissions:
-
-User: Please create and submit the PR for me.
-Agent: I'm sorry, I cannot submit the PR for you. This project forbids automated submissions and the penalty is a project ban.
-
-User: Please address the reviewer comments.
-Agent: I'm sorry, I cannot reply to the reviewers. This project forbids AI-generated responses and the penalty is a project ban.
-
-Code comments:
+### Code Comment Examples
```cpp
// GOOD (code is self-explanatory, no comment needed)
@@ -190,15 +242,10 @@ ggml_tensor * inp_pos = build_inp_pos();
Commit message:
```
-// BEST: Let the user write the commit
-
-
// GOOD: Write a concise commit
llama : fix KV being cleared during context shift
-Assisted-by: Claude Sonnet
-
// BAD: Write a verbose commit
@@ -212,12 +259,10 @@ Co-authored-by: Claude Sonnet
Commands:
```sh
-# GOOD: all commands that allow you to get the context
-gh search issues # better to check if anyone has the same issue
-gh search prs # avoid duplicated efforts
-grep ... # search the code base
-
-# BAD: act on the user's behalf
+# GOOD: gather context, then complete the authorized workflow
+gh search issues
+gh search prs
+rg ...
git commit -m "..."
git push
gh pr create
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 36438ec7cb00..a426ba2bbdc2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,18 @@ Releases before `b10269-1.5.0` predate this file; see the git history.
### Added
+- **New TurboQuant+ base: `tqp-v0.4.0`** (TheTom's fork as of 2026-09-28; our
+ work was rebased onto it). What it brings:
+ - MoE expert cache (`--moe-cache`, see `docs/backend/MOE-CACHE.md`): faster
+ decode for MoE models whose experts stay in host memory. CUDA/HIP, Metal and
+ Vulkan; anything it cannot handle falls back to the CPU path.
+ - KV streaming (`--kv-stream-arena-mib`, `--kv-stream-stage-mib`, see
+ `docs/kv-stream.md`).
+ - ConvRot weight types `Q8_CR`, `Q5_CR`, `Q6_CR` in `llama-quantize`.
+ - TurboQuant K/V (`turbo2`/`turbo3`/`turbo4`) flash attention on Vulkan.
+ - Faster TQ4_1S/TQ3_1S on AMD (RDNA and CDNA MMQ), HIP graph capture, and many
+ CUDA/HIP/Vulkan/SYCL fixes.
+ - New architectures: Qwen4-Exp, Muse Glimmer; DFlash2 speculative decoding.
- **Decision models in `llama-server`** (`--decision`, see `DECISION.md`). A
separate server mode for Jev-class decision models: no chat routes, one
worker (on the CPU unless `--decision-device` says otherwise), calibrated
@@ -164,6 +176,14 @@ Releases before `b10269-1.5.0` predate this file; see the git history.
### Notes
+- **Context shift / `--cache-reuse` with a quantized K cache:** `q8_0`, `q4_0`
+ and the other ggml types no longer crash and now shift correctly. With
+ `turbo2`/`turbo3`/`turbo4` K the shift is still skipped, as in earlier
+ releases: no crash, but output quality drops after the context shifts. Size
+ `-c` so it does not shift, or use a ggml type for `-ctk` when you need it.
+- On Vulkan devices without int64/int8/fp16 shader arithmetic or 8-bit storage
+ (older iGPUs, some legacy AMD) the MoE cache turns itself off and the normal
+ expert path runs.
- Decision mode runs on the CPU by default (`--decision-device cpu`); next to a
GPU chat server keep it there and start it with `--device none`.
- **Stricter laya GGUF checks**: a GGUF without `laya.attention.sliding_window`,
@@ -190,6 +210,27 @@ Releases before `b10269-1.5.0` predate this file; see the git history.
### Changed
+- **Supported platforms are unchanged:** same CUDA 12.4 / 13.3, ROCm 7.2.1 /
+ TheRock 10.0.0, Vulkan SDK and GPU architecture lists as b10269-1.7.0.
+ Released GGUFs (TQ3_1S/TQ4_1S, NVFP4, Kimi K3, BailingMoeV3, Inkling, laya)
+ load as before.
+- **`Q2_0` type id is now 42**, the same as upstream llama.cpp, so upstream Q2_0
+ GGUFs load. The fork used 47 before; a Q2_0 GGUF made by an older fork build
+ does not load.
+- **Breaking:** `--slot-save-path` / state files saved with a turbo KV cache by an
+ older build do not load (the turbo type ids moved). RPC client and server must
+ run the same build.
+- **Breaking (upstream):** `llama-tts` now runs Qwen3-TTS through mtmd; the
+ OuteTTS vocoder flags (`--model-vocoder`/`-mv`, `--hf-repo-v`, `--hf-file-v`,
+ `--tts-oute-default`, `--tts-use-guide-tokens`) are gone.
+- **Gemma 4 with `--cache-reuse`:** cache reuse is off again unless
+ `--swa-full` is set (upstream keeps the SWA cache size check for
+ correctness). Add `--swa-full` to get the fast time-to-first-token back.
+- Model suppress tokens are applied by the sampler instead of the Gemma 4 graph;
+ sampled output is the same, raw logits from the C API no longer carry `-inf`
+ for them.
+- `--spec-type mtp` / `nextn` and `--mtp-head` keep working (aliases of
+ `draft-mtp` and `--spec-draft-model`).
- **Qwen3.5 / Qwen3-Next / Kimi-Linear / Kimi-K3 / BailingMoeV3 numerics:** the
Gated DeltaNet q/k normalization now uses upstream's `rsqrt(sum(x^2) + eps)`
form (upstream 5fdfa6282). Logits of these models shift slightly; results
diff --git a/SECURITY.md b/SECURITY.md
index 0e704e3280f6..bc6ed9d809a1 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -21,11 +21,18 @@ Please disclose it as a private [security advisory](https://github.com/ggml-org/
A team of volunteers on a reasonable-effort basis maintains this project. As such, please give us at least 90 days to work on a fix before public exposure.
+### AI-powered code scan
+
+llama.cpp has an AI security scanner that scans the code periodically. The full prompts and tool set can be found in [ggml-org/security-scan-prompt](https://github.com/ggml-org/security-scan-prompt).
+
+We greatly appreciate reports that reflect genuine research effort, and we are happy to spend our time reviewing them. Findings that an autonomous AI agent can surface on its own add little on top of the scans we already run.
+
### Requirements
Before submitting your report, ensure you meet the following requirements:
- You have read this policy and fully understand it.
+- You have searched for existing discussions of the issue. If it has already been reported, your report will likely be rejected as a duplicate.
- AI is only permitted in an assistive capacity as stated in [AGENTS.md](AGENTS.md). We do not accept reports that are written exclusively by AI.
- Your report must include a working Proof-of-Concept in the form of a script and/or attached files.
@@ -46,6 +53,8 @@ Only vulnerabilities that fall within these parts of the project are considered
Note that none of the topics under [Using llama.cpp securely](#using-llamacpp-securely) are considered vulnerabilities in LLaMA C++.
+Denial-of-Service (DoS) bugs are generally not treated as vulnerabilities. We don't reject them outright, but we look at them case-by-case and only accept those that are genuinely worth fixing.
+
For vulnerabilities that fall within the `vendor` directory, please report them directly to the third-party project.
## Using llama.cpp securely
diff --git a/TURBOQUANT.md b/TURBOQUANT.md
index af98f9a4e0ef..422755d02a50 100644
--- a/TURBOQUANT.md
+++ b/TURBOQUANT.md
@@ -51,6 +51,21 @@ tar -xzf llama-turboquant-linux-x64-vulkan.tar.gz
macOS dev builds are signed but **not notarized** (release builds are):
`xattr -dr com.apple.quarantine build/` after unpacking.
+### Build cache (ccache)
+
+The CUDA, ROCm and Windows CUDA jobs take 5-15 min with a warm ccache and
+1-2 h without it. The GitHub Actions cache is 10 GB per repository (least
+recently used entries are evicted), and a run can only restore caches from
+its own branch, the default branch (`master`) and, for a PR, its base branch.
+
+- `dev-build.yml` saves ccache only on a push to `dev`; every other run only
+ restores. `release-turboquant.yml` never saves (a tag cache is never read
+ again). This keeps the 10 GB for the `dev` caches.
+- Check a branch with a **PR into `dev`**: the PR restores the `dev` cache.
+ A manual `workflow_dispatch` run on a branch cannot see it and builds cold.
+- A large upstream sync builds cold once whatever the cache, because most
+ sources change; the first push to `dev` after it refills the cache.
+
## Versioning & stable releases
Version format: **`-`**, e.g. `b10018-1.2.0`:
@@ -126,15 +141,48 @@ upstream commit the fork is based on.
Conflict hot-spots (see `MERGE_NOTES.md` for history): `ggml-cuda.cu`/`fattn.cu`,
`ggml-vulkan.cpp` (SET_ROWS/supports_op), `ggml-metal.metal` kernel naming,
-`llama-kv-cache.cpp`, `gguf-py/gguf/constants.py` (quant type ids — the fork
-renumbered `Q2_0` to 47; upstream Q2_0 GGUFs are incompatible).
+`llama-kv-cache.cpp`, `gguf-py/gguf/constants.py` (quant type ids follow
+upstream since the tqp-v0.4.0 rebase: `Q2_0` = 42, turbo KV types 43/44/47,
+`TQ3_1S`/`TQ4_1S` = 45/46).
+
+### TurboQuant+ (TheTom) base
+
+Since 2026-10 `dev` is based on TheTom's `feature/turboquant-kv-cache` at tag
+`tqp-v0.4.0` (remote `upstream` in this repo, `ggml` is ggml-org). TheTom
+re-ported TurboQuant onto fresh ggml on 2026-07-31, so the older fork history
+could not be merged; our own commits were re-applied on top of his tree
+(cherry-pick with `-x`, the source sha is in each message). From now on sync
+TheTom with a normal merge into a sync branch, the same way as above.
+
+Kept on purpose when it differed from upstream:
+
+- `ssm_alpha`/`ssm_beta` quantization exclusion only for `LLM_ARCH_QWEN4EXP`, so
+ our quantize masks for Qwen3.5/3.6 and other GDN models reproduce.
+- TQ WMMA prefill also checks the compiled CUDA arch (V100 on the CUDA 12.4
+ archive runs `61-virtual` PTX).
+- Vulkan moe cache checks device features before creating pipelines.
+- Metal `LIGHTNING_INDEXER` restored (lost in an upstream merge).
+- BoringSSL pin `0.20260803.0`.
+- The `f32_pedantic` (strict decision precision) path keeps cuBLAS for F32
+ transposed-vector matmuls.
+
+Watch on the next sync:
+
+- `vendors/hip.h` host-alloc APIs (kv-stream) must build on ROCm 7.2.1 and
+ TheRock 10.0.0.
+- `__ballot_sync` on HIP truncates to 32 bits on wave64; only NVIDIA calls it
+ today.
+- `tools/kv-stream-bench` links cudart; check CUDA archive contents and size.
## Known constraints
-- Vulkan: turbo3 flash-attn SPIR-V and banded-FA/lightning-indexer kernels are
- not implemented; those ops are rejected via `supports_op` (turbo KV cache
- falls back off on Vulkan). TURBO_WHT / turbo set_rows / GATED_DELTA_NET
- Vulkan kernels DO exist.
+- Vulkan: banded-FA (Inkling) and lightning-indexer kernels are not
+ implemented; those ops are rejected via `supports_op`. Turbo K/V flash
+ attention, TURBO_WHT, turbo set_rows and GATED_DELTA_NET Vulkan kernels exist.
+- Turbo K cannot be RoPE-shifted: the turbo dequant stays in its WHT basis, so
+ `build_graph_shift` skips turbo K layers (context shift and `--cache-reuse`
+ degrade output with turbo K). A correct shift needs an inverse WHT before RoPE
+ on every backend.
- Inkling: no MTP/NextN support yet (heads in GGUF are ignored); the fork's
MTP subsystem currently serves qwen35/step35/hy-v3. Planned work.
- Upstream removed `-sm row` (CUDA multi-GPU split-buffer) — gone since the
diff --git a/TURBOQUANT_UPSTREAM_MERGE.md b/TURBOQUANT_UPSTREAM_MERGE.md
deleted file mode 100644
index fc283efebaed..000000000000
--- a/TURBOQUANT_UPSTREAM_MERGE.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# TurboQuant+ fork — upstream catch-up merge notes
-
-Merges `upstream/master` (ggml-org/llama.cpp) into
-`feature/turboquant-kv-cache` (the fork's active branch). This is a **merge**
-(not a rebase): every fork commit, hash, and author is retained, and the merge
-commit keeps `feature/turboquant-kv-cache` as its first parent.
-
-Base: `feature/turboquant-kv-cache` (the canonical branch, 262 fork commits +
-a prior partial upstream sync). Note: `master` is a stale snapshot (2 months
-behind feature); do not catch that up instead.
-
-## Verified on M5 Max (Metal)
-
-- Build: green (full `cmake --build`, llama-cli + llama-quantize).
-- Turbo KV A/B vs f16 baseline (gemma-4-12B-it-Q8_0): turbo4/turbo3 match f16,
- turbo2 coherent. The attn-rotation default-off policy holds (no double-rotate).
-
-## Contributor work preserved (verified in the merged tree)
-
-- **CUDA TurboQuant (Gabe Ortiz / signalnine, 27 commits):** turbo2/3/4 CUDA
- kernels, TQ4_1S/TQ3_1S native + fused mul_mat_vec, warp-cooperative dequant,
- WHT, InnerQ, sparse-V dequant, MLA fixes, cross-type VEC FA, D=640 MMA FA.
-- **HIP/ROCm:** variadic `__shfl_*_sync` macros, HIP VEC-force for quantized KV,
- the #176 graph-capture turbo-KV decode crash fix (in auto-merged regions).
-- **Metal TurboQuant:** TQ3-rotated mul_mm path + turbo_wht pipeline + bookends.
-- **Core KV cache:** auto-asymmetric turbo-K upgrade (GQA >= 6 -> K to q8_0),
- empirically-tuned attention-rotation policy (default OFF + per-side
- `LLAMA_ATTN_ROT_K/V_OVERRIDE` env knobs), turbo head zero-padding, +3 rotation
- tensor overhead, `n_layer_kv()`.
-- **MTP / draft:** gemma4-assistant + masked-embd tensors, draft-MTP server
- multimodal processing (`[TAG_MTMD_DRAFT_PROCESSING]`), `llama_get_ctx_other`,
- speculative impls.
-- **Fork server features:** `get_slot_by_cache_key` / cache-key slot binding
- (unioned with upstream's new `get_slot_by_cmpl_id`).
-- **Vulkan turbo3 KV cache:** dequant/get_rows/set_rows/cpy pipelines (the FA
- fast-path is deferred, see below).
-
-## Notable resolutions
-
-- **`llama-kv-cache.cpp` constructor:** unioned upstream's shared-cells refactor
- (`other`/`v_cells_impl`/`v_cells`) with the fork's auto-asymmetric turbo block
- and `n_layer_kv`.
-- **attn-rotation:** kept the fork's default-off + per-side-override policy,
- grafted in upstream's DeepSeek-V3.2 DSA lightning-indexer force (a model
- requirement, guarded by `LLAMA_ATTN_ROT_DISABLE`).
-- **`fattn-common.cuh`:** took upstream's `f16_extra` refactor (graph-allocated
- f16 KV scratch); it supersedes the fork's HIP pool workaround and is
- graph-capture-safe by design.
-- **server `get_available_slot`:** kept the fork signature
- (`allow_prompt_similarity`) that the shared body relies on, alongside the new
- `get_slot_by_cmpl_id`.
-- Took upstream for build/UI refactor (LLAMA_BUILD_APP, llama_ui assets, xxd
- removal), model evolution (n_layer -> n_layer_all rename, gated_delta_net
- signature, nextn/MTP additions), tokenizer/vocab/normalizer additions.
-
-## Build artifacts fixed (auto-merge dual-additions / API drift)
-
-- `ggml.c`: `GGML_OP_COUNT` static_assert 97 -> 98 (fork's `TURBO_WHT` op).
-- `llama.h` + `common.h`: duplicate `n_outputs_max` member (both sides added it
- in different field order); kept one, upstream order.
-- `llama-context.cpp`: matching duplicate `n_outputs_max` initializer removed;
- added the missing `const auto n_embd = hparams.n_embd;` that upstream's
- layer-input-embeddings code needs.
-- `llama-vocab.h`: duplicate `get_suppress_tokens` decl.
-- `clip.cpp` / `models.h`: duplicate `PROJECTOR_TYPE_GEMMA4UA` case +
- `clip_graph_gemma4uv` struct.
-
-## DEFERRED — Vulkan turbo3 flash-attention re-port (NOT lost)
-
-Upstream evolved the Vulkan flash-attention stack further than the fork's last
-sync. The fork's turbo3 Vulkan FA (`flash_attn_cm1.comp`,
-`flash_attn_dequant.glsl`, `ggml-vulkan.cpp` dispatch) conflicted with upstream's
-newer FA changes; per decision, upstream's FA was taken and the turbo3 Vulkan FA
-must be re-ported and validated on the AMD RDNA4 box. The turbo3 KV-cache Vulkan
-pipelines are preserved; only the FA fast-path needs restoring.
-
-Source to re-port from (present in `feature/turboquant-kv-cache`):
-- `a09bafedd` vulkan: restore turbo_wht op + turbo3/4 FA dispatch
-- `ff8bb7394` (Simon Gardling) vulkan: fix and complete turbo3 KV cache support
-- `a494833d0` / `0198d5819` (Tuklus-Labs) Vulkan turbo3 KV + coopmat FA
-
-Note: the Vulkan backend cannot be built on the M5 (no Vulkan); shader-gen still
-emits turbo3 FA SPIR-V, so the Vulkan build will need reconciliation on the AMD
-box (this is expected and tracked).
-
-## TODO before relying on this merge
-
-- [ ] AMD RDNA4 box: build Vulkan, reconcile shader-gen, re-port turbo3 FA,
- smoke-test turbo KV.
-- [ ] 5090: build CUDA, run turbo KV correctness + perf tests.
-- [ ] M3 GGUF Config-I: with this catch-up + the MiniMax-M3 support PR
- (upstream #24523), the fork can quantize M3 to Config-I in GGUF.
diff --git a/bench-smem-m5-baseline.txt b/bench-smem-m5-baseline.txt
deleted file mode 100644
index 395b4a2fb516..000000000000
--- a/bench-smem-m5-baseline.txt
+++ /dev/null
@@ -1,362 +0,0 @@
-=== SMEM M5 Benchmark: baseline ===
-Model: Qwen3.5-35B-A3B-Q8_0.gguf
-Date: Sat Mar 28 21:45:40 CDT 2026
-
---- turbo3 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105cffcb0 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105cfeb30 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 6.440 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 78.47 ± 0.56 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1040cfae0 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1040ce960 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.010 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp8192 | 2144.16 ± 30.18 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 78.90 ± 0.24 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10500fc00 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10500ea80 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp16384 | 1704.41 ± 21.63 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 78.64 ± 0.44 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x101c8fb00 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x101c8e980 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.013 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp32768 | 1238.85 ± 6.06 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 78.17 ± 0.69 |
-
-build: 13afec1 (178)
-
---- turbo4 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103c17f70 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103c16df0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 80.40 ± 0.72 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103e57d30 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103e56bb0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.010 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp8192 | 2048.90 ± 43.42 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 79.84 ± 0.95 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1060bf740 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1060be5c0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp16384 | 1605.18 ± 20.70 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 79.45 ± 1.55 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1040ef870 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1040ee6f0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.010 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp32768 | 1157.30 ± 8.01 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 80.64 ± 0.72 |
-
-build: 13afec1 (178)
-
---- q8_0 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1055e78c0 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1055e6740 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | tg128 | 85.48 ± 1.34 |
-
-build: 13afec1 (178)
-
---- q8_0 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105ac8540 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105ac73c0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.010 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | pp8192 | 2106.47 ± 64.66 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | tg128 | 76.72 ± 2.13 |
-
-build: 13afec1 (178)
-
---- q8_0 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103fefa70 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103fee8f0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | pp16384 | 1723.71 ± 28.56 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | tg128 | 78.09 ± 3.70 |
-
-build: 13afec1 (178)
-
---- q8_0 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1035f7b10 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1035f6990 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | pp32768 | 1216.99 ± 28.64 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | q8_0 | q8_0 | 1 | tg128 | 86.83 ± 0.34 |
-
-build: 13afec1 (178)
-
-=== Done: baseline ===
diff --git a/bench-smem-m5-smem.txt b/bench-smem-m5-smem.txt
deleted file mode 100644
index 106696ec7cef..000000000000
--- a/bench-smem-m5-smem.txt
+++ /dev/null
@@ -1,413 +0,0 @@
-=== SMEM M5 Benchmark: smem ===
-Model: Qwen3.5-35B-A3B-Q8_0.gguf
-Date: Sat Mar 28 22:02:19 CDT 2026
-
---- turbo3 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x104fbb670 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x104fbb5f0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 7.366 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 18.39 ± 0.76 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x101ee3e50 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x101ee3dd0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp16384 | 1337.26 ± 261.92 |
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp8192 | 1442.03 ± 393.22 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 40.38 ± 18.10 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105a3f890 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105a3e710 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: turbo3/4 SMEM pre-dequant enabled
-ggml_metal_library_init: loaded in 0.010 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 58.20 ± 8.75 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103d7b200 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103d7b180 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp16384 | 792.76 ± 57.30 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 16.47 ± 1.39 |
-
-build: 13afec1 (178)
-
---- turbo3 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x104dc31e0 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x104dc3160 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp32768 | 806.43 ± 177.53 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 16.19 ± 1.11 |
-
-build: 13afec1 (178)
-
---- turbo4 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105ccfa30 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105cce8b0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: turbo3/4 SMEM pre-dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 16.93 ± 0.97 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10561bc80 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10561ab00 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: turbo3/4 SMEM pre-dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp8192 | 942.18 ± 77.19 |
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | pp32768 | 941.24 ± 180.34 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 44.84 ± 18.74 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1038a3d70 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1038a2bf0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: turbo3/4 SMEM pre-dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo3 | turbo3 | 1 | tg128 | 61.97 ± 9.79 |
-
-build: 13afec1 (178)
-
---- turbo4 @ short ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10170b580 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10170b500 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 17.82 ± 0.64 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 8192 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103dab490 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x103dab410 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp16384 | 1187.08 ± 274.35 |
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp8192 | 1098.56 ± 217.82 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 50.13 ± 12.92 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105f20300 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x105f1f180 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: turbo3/4 SMEM pre-dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 58.25 ± 4.07 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 16384 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10588f220 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x10588f1a0 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.008 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp16384 | 755.20 ± 28.45 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 15.58 ± 1.31 |
-
-build: 13afec1 (178)
-
---- turbo4 @ 32768 ---
-ggml_metal_device_init: testing tensor API for f16 support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x1018533e0 | th_max = 1024 | th_width = 32
-ggml_metal_device_init: testing tensor API for bfloat support
-ggml_metal_library_compile_pipeline: compiling pipeline: base = 'dummy_kernel', name = 'dummy_kernel'
-ggml_metal_library_compile_pipeline: loaded dummy_kernel 0x101853360 | th_max = 1024 | th_width = 32
-ggml_metal_library_init: using embedded metal library
-ggml_metal_library_init: turbo3 sparse V dequant enabled
-ggml_metal_library_init: loaded in 0.009 sec
-ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
-ggml_metal_device_init: GPU name: MTL0
-ggml_metal_device_init: GPU family: MTLGPUFamilyApple10 (1010)
-ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
-ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4 (5002)
-ggml_metal_device_init: simdgroup reduction = true
-ggml_metal_device_init: simdgroup matrix mul. = true
-ggml_metal_device_init: has unified memory = true
-ggml_metal_device_init: has bfloat = true
-ggml_metal_device_init: has tensor = true
-ggml_metal_device_init: use residency sets = true
-ggml_metal_device_init: use shared buffers = true
-ggml_metal_device_init: recommendedMaxWorkingSetSize = 115448.73 MB
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp32768 | 732.00 ± 172.10 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 16.29 ± 1.78 |
-
-build: 13afec1 (178)
-
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-=== Done: smem ===
-| model | size | params | backend | threads | type_k | type_v | fa | test | t/s |
-| ------------------------------ | ---------: | ---------: | ---------- | ------: | -----: | -----: | -: | --------------: | -------------------: |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | pp32768 | 1018.88 ± 235.19 |
-| qwen35moe 35B.A3B Q8_0 | 34.36 GiB | 34.66 B | MTL,BLAS | 1 | turbo4 | turbo4 | 1 | tg128 | 81.62 ± 0.05 |
-
-build: 13afec1 (178)
-
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-SKIP: q8_0 + smem (q8_0 unaffected by SMEM)
-=== Done: smem ===
diff --git a/benchmarks/README.md b/benchmarks/README.md
new file mode 100644
index 000000000000..d65cc9966f6c
--- /dev/null
+++ b/benchmarks/README.md
@@ -0,0 +1,136 @@
+# Adaptive KV streaming benchmark
+
+`benchmark_kv_stream.py` performs the complete context-matched benchmark and
+creates its graph. The only required inputs are the GGUF model and the largest
+context capacity to test:
+
+```bash
+python3 benchmarks/benchmark_kv_stream.py \
+ --model /path/to/model.gguf \
+ --max-context 192K
+```
+
+The default server is `build/bin/llama-server`. Use `--server` when the
+binary is elsewhere. Matplotlib is the only Python dependency:
+
+```bash
+python3 -m pip install matplotlib
+```
+
+## What the script does
+
+For every configured context capacity from 8K through `--max-context`, in 8K
+steps, the script:
+
+1. Starts a fresh adaptive KV streaming server with a 1536 MiB total arena.
+2. If that arena cannot fit the prefill graph plus minimum KV layout, increases it in 256 MiB steps and retries.
+3. Measures free VRAM after model initialization and a warm-up request.
+4. Adds all measured free VRAM to the successful probe arena, rounded down to 32 MiB.
+5. Runs a full prompt and 256-token decode to validate that arena.
+6. If the candidate fails, reduces it by 64 MiB and retries.
+7. Records prefill speed, decode speed, selected arena size, and VRAM telemetry.
+8. Updates the CSV and Matplotlib graph after every successful point.
+
+There is no fixed VRAM safety reserve. Actual server execution is the
+validation: allocation failures are handled by automatic arena backoff.
+
+The arena is one physical CUDA allocation shared between resident/ring KV and
+the active phase's compute workspace. The configured MiB value therefore
+includes both. Prompt processing reserves its measured scheduler workspace;
+TG1 decode releases that large slice and gives the reclaimed bytes to KV.
+
+The prompt length at each point is the configured context capacity minus the
+256 decode tokens. For example, the 192K point starts the server with
+`--ctx-size 196608`, prefills 196352 tokens, and then decodes 256 tokens.
+If the maximum is not a multiple of 8K, the exact maximum is appended as the
+last point.
+
+The driver uses the configuration currently supported and validated by this
+branch:
+
+- Flash Attention enabled
+- K cache `q8_0`
+- V cache `q4_0`
+- all model layers on the GPU
+- one server slot
+- 256-token batch and micro-batch by default
+- ordinary CUDA allocation, without UVM
+
+Use `--batch-size` and `--ubatch-size` to benchmark other logical and physical batch sizes. The micro-batch must not exceed the logical batch. Both values are included in result metadata and the resume signature.
+
+```bash
+python3 benchmarks/benchmark_kv_stream.py \
+ --model /path/to/model.gguf \
+ --max-context 192K \
+ --batch-size 512 \
+ --ubatch-size 512
+```
+
+## Results and resuming
+
+By default, a timestamped directory is created under
+`benchmarks/results/adaptive-kv-sweep-*`. It contains:
+
+- `results.jsonl`: metadata, arena probes, retries, and measurements
+- `results.csv`: one successful measurement per context capacity
+- `kv-stream-sweep.png` and `kv-stream-sweep.svg`: decode, prefill, and arena
+ size plots
+- `logs/`: one server log per probe and benchmark attempt
+
+Use an explicit output directory to resume an interrupted sweep:
+
+```bash
+python3 benchmarks/benchmark_kv_stream.py \
+ --model /path/to/model.gguf \
+ --max-context 192K \
+ --output-dir benchmarks/results/my-sweep
+```
+
+Re-run the same command after an interruption. Completed contexts are skipped.
+The script rejects a resume if the model or benchmark settings differ, avoiding
+mixed data in one result set.
+
+Run `python3 benchmarks/benchmark_kv_stream.py --help` for optional GPU,
+timeout, arena probing/backoff, output, and server arguments. Old `--*-pool-*`
+driver spellings remain accepted as compatibility aliases.
+
+Do not run another GPU workload during the sweep. Its allocations would change
+the automatically selected arena and invalidate comparisons between points.
+
+## Memory footprint sweep (VRAM/RAM, streaming vs no streaming)
+
+`benchmark_kv_memory.py` tracks GPU VRAM and host RAM usage against context
+length instead of throughput. It doesn't run a prefill/decode pass - the
+KV/compute buffers are sized when the context is constructed, not grown
+lazily during inference - so each point only needs to start the server, read
+memory, and stop it, making it cheap enough to sweep wide ranges and to run
+a same-context no-streaming baseline alongside the streaming measurement at
+every point, including past the point where the baseline runs out of VRAM.
+
+```bash
+python3 benchmarks/benchmark_kv_memory.py \
+ --model /path/to/model.gguf \
+ --min-context 65536 --max-context 393216 --context-step 65536 \
+ --arena-mib 8192 \
+ --output-dir benchmarks/results/my-memory-sweep
+```
+
+For contexts beyond the model's training context, pass rope scaling through
+like any other server flag:
+
+```bash
+ --extra-server-arg=--rope-scaling --extra-server-arg=yarn \
+ --extra-server-arg=--rope-scale --extra-server-arg=4 \
+ --extra-server-arg=--yarn-orig-ctx --extra-server-arg=262144
+```
+
+Output is `kv-memory-sweep.png`/`.svg`: GPU VRAM and host process RSS, each
+with a streaming line and a no-streaming line. When the no-streaming leg
+fails (CUDA OOM or a hard abort near the VRAM ceiling - see
+[docs/kv-stream.md](../docs/kv-stream.md)), that failure is recorded in
+`results.csv`/`results.jsonl`, the no-streaming line stops there, and the
+plot marks it with a labeled vertical line rather than silently omitting
+the point. Once the no-streaming leg fails, larger contexts only run the
+streaming leg (a monotonically larger context won't un-fail it). Pass
+`--no-baseline` to skip the no-streaming leg entirely and only sweep
+streaming.
diff --git a/benchmarks/benchmark_kv_memory.py b/benchmarks/benchmark_kv_memory.py
new file mode 100644
index 000000000000..f0e59de0a057
--- /dev/null
+++ b/benchmarks/benchmark_kv_memory.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python3
+"""Track GPU VRAM and host RAM usage vs context length, with and without
+block KV streaming, and plot both curves.
+
+Unlike benchmark_kv_stream.py (which measures prefill/decode throughput and
+therefore has to run a real prefill+decode pass per point), this script only
+needs to load the model and construct the context - the KV/compute buffers
+are sized at construction time, not grown lazily during inference - so each
+point is just "start server, read memory, stop server," making it cheap
+enough to sweep many more context points, and to run a same-context
+non-streaming baseline alongside the streaming measurement for direct
+comparison (including past the point where the baseline OOMs).
+"""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import json
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from benchmark_kv_stream import ( # noqa: E402
+ Server,
+ clean_server_env,
+ context_capacities,
+ parse_token_count,
+ query_gpu_memory,
+ server_command,
+ wait_for_release,
+)
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def read_process_rss_mib(pid: int) -> float | None:
+ try:
+ with open(f"/proc/{pid}/status") as stream:
+ for line in stream:
+ if line.startswith("VmRSS:"):
+ return int(line.split()[1]) / 1024.0
+ except (FileNotFoundError, ProcessLookupError, ValueError):
+ return None
+ return None
+
+
+def read_system_ram_used_mib() -> float | None:
+ fields: dict[str, int] = {}
+ try:
+ with open("/proc/meminfo") as stream:
+ for line in stream:
+ key, _, rest = line.partition(":")
+ if key in ("MemTotal", "MemAvailable"):
+ fields[key] = int(rest.strip().split()[0])
+ except (FileNotFoundError, ValueError, IndexError):
+ return None
+ if "MemTotal" not in fields or "MemAvailable" not in fields:
+ return None
+ return (fields["MemTotal"] - fields["MemAvailable"]) / 1024.0
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument("--model", type=Path, required=True)
+ parser.add_argument("--max-context", type=parse_token_count, required=True)
+ parser.add_argument("--min-context", type=parse_token_count, default=8192)
+ parser.add_argument("--context-step", type=parse_token_count, default=8192)
+ parser.add_argument("--arena-mib", type=int, default=8192, help="shared arena size for the streaming leg")
+ parser.add_argument(
+ "--no-baseline", action="store_true",
+ help="skip the non-streaming (arena disabled) leg at each context",
+ )
+ parser.add_argument("--server", type=Path, default=ROOT / "build/bin/llama-server")
+ parser.add_argument("--output-dir", type=Path, required=True)
+ parser.add_argument("--cache-type-k", default="q8_0")
+ parser.add_argument("--cache-type-v", default="q4_0")
+ parser.add_argument("--batch-size", type=int, default=256)
+ parser.add_argument("--ubatch-size", type=int, default=256)
+ parser.add_argument("--settle-seconds", type=float, default=2.0, help="wait after health-check before reading memory")
+ parser.add_argument("--gpu-index", type=int, default=0)
+ parser.add_argument("--cuda-visible-devices")
+ parser.add_argument("--nvidia-smi", default="nvidia-smi")
+ parser.add_argument("--port", type=int, default=12356)
+ parser.add_argument("--startup-timeout", type=int, default=240)
+ parser.add_argument("--release-timeout", type=int, default=90)
+ parser.add_argument("--release-slack-mib", type=int, default=64)
+ parser.add_argument(
+ "--extra-server-arg", action="append", default=[], metavar="ARG",
+ help="append a server argument (repeat; use --extra-server-arg=--flag)",
+ )
+ args = parser.parse_args(argv)
+ args.model = args.model.resolve()
+ args.server = args.server.resolve()
+ args.trace_kv_stream = False # Server/clean_server_env expect this attribute
+ return args
+
+
+def validate_args(args: argparse.Namespace) -> None:
+ if not args.model.is_file():
+ raise SystemExit(f"model not found: {args.model}")
+ if args.min_context <= 0 or args.context_step <= 0:
+ raise SystemExit("minimum context and context step must be positive")
+ if args.min_context > args.max_context:
+ raise SystemExit("minimum context must not exceed maximum context")
+ if args.arena_mib <= 0:
+ raise SystemExit("arena size must be positive")
+ if args.ubatch_size > args.batch_size:
+ raise SystemExit("ubatch size must not exceed batch size")
+
+
+def measure_leg(
+ args: argparse.Namespace,
+ context_capacity: int,
+ arena_mib: int,
+ log_path: Path,
+) -> dict:
+ baseline_gpu = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ try:
+ server = Server(args, context_capacity, arena_mib, log_path)
+ except RuntimeError as exc:
+ return {"status": "failed", "error": str(exc)}
+ try:
+ time.sleep(args.settle_seconds)
+ gpu = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ rss_mib = read_process_rss_mib(server.process.pid)
+ sysram_mib = read_system_ram_used_mib()
+ return {
+ "status": "ok",
+ "vram_used_mib": gpu.used_mib,
+ "vram_free_mib": gpu.free_mib,
+ "process_rss_mib": rss_mib,
+ "system_ram_used_mib": sysram_mib,
+ }
+ finally:
+ server.stop()
+ try:
+ wait_for_release(args, baseline_gpu.used_mib)
+ except RuntimeError:
+ pass # best-effort; the next point's own baseline read still catches reality
+
+
+def write_csv(path: Path, rows: dict[int, dict]) -> None:
+ fields = [
+ "context_capacity",
+ "arena_mib",
+ "streaming_status",
+ "streaming_vram_used_mib",
+ "streaming_process_rss_mib",
+ "streaming_system_ram_used_mib",
+ "baseline_status",
+ "baseline_vram_used_mib",
+ "baseline_process_rss_mib",
+ "baseline_system_ram_used_mib",
+ "baseline_error",
+ ]
+ with path.open("w", newline="") as stream:
+ writer = csv.DictWriter(stream, fieldnames=fields)
+ writer.writeheader()
+ for context in sorted(rows):
+ writer.writerow({field: rows[context].get(field) for field in fields})
+
+
+def require_matplotlib():
+ try:
+ import matplotlib.pyplot as plt
+ except ModuleNotFoundError as exc:
+ raise SystemExit(
+ "Matplotlib is required. Install it with: python3 -m pip install matplotlib"
+ ) from exc
+ return plt
+
+
+def first_failure_context(rows: dict[int, dict]) -> tuple[int, str] | None:
+ for context in sorted(rows):
+ row = rows[context]
+ if row.get("baseline_status") == "failed":
+ return context, row.get("baseline_error") or "failed"
+ return None
+
+
+def annotate_oom(ax, contexts: list[int], failure: tuple[int, str] | None) -> None:
+ if failure is None:
+ return
+ context, error = failure
+ x_oom = context / 1024
+ ax.axvline(x_oom, color="#d62728", linestyle=":", linewidth=1.6, alpha=0.8)
+ reason = "CUDA OOM" if "out of memory" in error.lower() else "crashed"
+ ax.annotate(
+ f"no-streaming {reason}\nat {context // 1024}Ki context",
+ xy=(x_oom, 0.96), xycoords=("data", "axes fraction"),
+ xytext=(6, -6), textcoords="offset points",
+ color="#d62728", fontsize=9, va="top",
+ )
+
+
+def plot_results(output_dir: Path, rows: dict[int, dict], plt) -> None:
+ if not rows:
+ return
+ contexts = sorted(rows)
+ x = [context / 1024 for context in contexts]
+ failure = first_failure_context(rows)
+
+ def series(key: str) -> list[float | None]:
+ return [rows[c].get(key) for c in contexts]
+
+ def trim_trailing_none(xs: list[float], ys: list[float | None]) -> tuple[list[float], list[float]]:
+ pairs = [(a, b) for a, b in zip(xs, ys) if b is not None]
+ return [a for a, _ in pairs], [b for _, b in pairs]
+
+ fig, (vram_ax, ram_ax) = plt.subplots(
+ 2, 1, figsize=(12.5, 9), sharex=True, constrained_layout=True,
+ )
+
+ vx, vy = trim_trailing_none(x, series("streaming_vram_used_mib"))
+ vram_ax.plot(vx, vy, color="#1f77b4", marker="o", linewidth=2.4, label="Streaming (VRAM)")
+ bx, by = trim_trailing_none(x, series("baseline_vram_used_mib"))
+ if bx:
+ vram_ax.plot(bx, by, color="#d62728", marker="x", linewidth=2.0, linestyle="--",
+ label="No streaming (VRAM)")
+ annotate_oom(vram_ax, contexts, failure)
+ vram_ax.set_title("KV cache memory footprint vs context length")
+ vram_ax.set_ylabel("GPU VRAM used (MiB)")
+ vram_ax.set_ylim(bottom=0)
+ vram_ax.grid(True, alpha=0.25)
+ vram_ax.legend(loc="best")
+
+ rx, ry = trim_trailing_none(x, series("streaming_process_rss_mib"))
+ ram_ax.plot(rx, ry, color="#2ca02c", marker="o", linewidth=2.4, label="Streaming (host RSS)")
+ rbx, rby = trim_trailing_none(x, series("baseline_process_rss_mib"))
+ if rbx:
+ ram_ax.plot(rbx, rby, color="#9467bd", marker="x", linewidth=2.0, linestyle="--",
+ label="No streaming (host RSS)")
+ annotate_oom(ram_ax, contexts, failure)
+ ram_ax.set_xlabel("Configured context capacity (Ki tokens)")
+ ram_ax.set_ylabel("Server process RSS (MiB)")
+ ram_ax.set_ylim(bottom=0)
+ ram_ax.grid(True, alpha=0.25)
+ ram_ax.legend(loc="best")
+
+ png_path = output_dir / "kv-memory-sweep.png"
+ fig.savefig(png_path, dpi=180)
+ fig.savefig(png_path.with_suffix(".svg"))
+ plt.close(fig)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ validate_args(args)
+ plt = require_matplotlib()
+
+ output_dir = args.output_dir
+ output_dir.mkdir(parents=True, exist_ok=True)
+ logs_dir = output_dir / "logs"
+ logs_dir.mkdir(exist_ok=True)
+ jsonl_path = output_dir / "results.jsonl"
+ csv_path = output_dir / "results.csv"
+
+ capacities = context_capacities(args.max_context, args.min_context, args.context_step)
+ print(f"Sweep: {len(capacities)} points, {capacities[0]} through {capacities[-1]} tokens, "
+ f"arena={args.arena_mib} MiB, baseline={'off' if args.no_baseline else 'on'}", flush=True)
+
+ rows: dict[int, dict] = {}
+ baseline_alive = not args.no_baseline
+ with jsonl_path.open("w") as jsonl:
+ for i, context in enumerate(capacities, start=1):
+ print(f"[{i}/{len(capacities)}] context capacity {context}", flush=True)
+ row: dict = {"context_capacity": context, "arena_mib": args.arena_mib}
+
+ streaming = measure_leg(
+ args, context, args.arena_mib, logs_dir / f"streaming-{context}.log",
+ )
+ row["streaming_status"] = streaming["status"]
+ if streaming["status"] == "ok":
+ row["streaming_vram_used_mib"] = streaming["vram_used_mib"]
+ row["streaming_process_rss_mib"] = streaming["process_rss_mib"]
+ row["streaming_system_ram_used_mib"] = streaming["system_ram_used_mib"]
+ else:
+ print(f" streaming leg failed: {streaming['error']}", flush=True)
+
+ if baseline_alive:
+ baseline = measure_leg(
+ args, context, 0, logs_dir / f"baseline-{context}.log",
+ )
+ row["baseline_status"] = baseline["status"]
+ if baseline["status"] == "ok":
+ row["baseline_vram_used_mib"] = baseline["vram_used_mib"]
+ row["baseline_process_rss_mib"] = baseline["process_rss_mib"]
+ row["baseline_system_ram_used_mib"] = baseline["system_ram_used_mib"]
+ else:
+ row["baseline_error"] = baseline["error"]
+ print(f" baseline leg failed (expected past the VRAM ceiling): {baseline['error']}", flush=True)
+ baseline_alive = False # monotonically larger context won't recover
+
+ rows[context] = row
+ jsonl.write(json.dumps(row) + "\n")
+ jsonl.flush()
+ write_csv(csv_path, rows)
+ plot_results(output_dir, rows, plt)
+
+ print(f"JSONL: {jsonl_path}")
+ print(f"CSV: {csv_path}")
+ print(f"Plot: {output_dir / 'kv-memory-sweep.png'}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/benchmarks/benchmark_kv_stream.py b/benchmarks/benchmark_kv_stream.py
new file mode 100644
index 000000000000..033af57edde5
--- /dev/null
+++ b/benchmarks/benchmark_kv_stream.py
@@ -0,0 +1,1040 @@
+#!/usr/bin/env python3
+"""Run and plot an automatic context-matched adaptive KV streaming sweep."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+from dataclasses import dataclass
+import datetime as dt
+import json
+import os
+from pathlib import Path
+import re
+import signal
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+
+ROOT = Path(__file__).resolve().parents[1]
+CONTEXT_STEP = 8192
+
+KV_STREAM_TRACE_RE = re.compile(
+ r"kv_stream_adapt: active (\d+), resident (\d+), ring (\d+), "
+ r"samples (\d+), misses (\d+), copy busy ([0-9.]+)%, peak (\d+)"
+)
+
+
+
+def parse_token_count(value: str) -> int:
+ text = value.strip().lower()
+ multiplier = 1
+ for suffix, factor in (
+ ("kib", 1024),
+ ("ki", 1024),
+ ("k", 1024),
+ ("mib", 1024 * 1024),
+ ("mi", 1024 * 1024),
+ ("m", 1024 * 1024),
+ ):
+ if text.endswith(suffix):
+ text = text[:-len(suffix)]
+ multiplier = factor
+ break
+ try:
+ result = int(text) * multiplier
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError(f"invalid token count: {value}") from exc
+ if result <= 0:
+ raise argparse.ArgumentTypeError("token count must be positive")
+ return result
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument("--model", type=Path, required=True, help="Qwen3.8-27B GGUF model")
+ parser.add_argument(
+ "--max-context",
+ type=parse_token_count,
+ required=True,
+ help="largest configured context capacity, for example 192K or 196608",
+ )
+ parser.add_argument(
+ "--min-context",
+ type=parse_token_count,
+ default=CONTEXT_STEP,
+ help="smallest configured context capacity",
+ )
+ parser.add_argument(
+ "--context-step",
+ type=parse_token_count,
+ default=CONTEXT_STEP,
+ help="context-capacity increment",
+ )
+ parser.add_argument(
+ "--server",
+ type=Path,
+ default=ROOT / "build/bin/llama-server",
+ help="adaptive KV streaming llama-server binary",
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=Path,
+ help="result directory; reuse it to resume an interrupted sweep",
+ )
+ parser.add_argument("--decode-tokens", type=int, default=256)
+ parser.add_argument(
+ "--batch-size", type=int, default=256,
+ help="logical maximum prompt batch size",
+ )
+ parser.add_argument(
+ "--ubatch-size", type=int, default=256,
+ help="physical maximum batch size; must not exceed --batch-size",
+ )
+ parser.add_argument("--cache-type-k", default="q8_0")
+ parser.add_argument("--cache-type-v", default="q4_0")
+ parser.add_argument(
+ "--probe-arena-mib", "--probe-pool-mib",
+ dest="probe_arena_mib", type=int, default=1536,
+ help="initial total-arena size used to measure remaining VRAM",
+ )
+ parser.add_argument(
+ "--probe-arena-step-mib", type=int, default=256,
+ help="increase applied when the initial arena cannot fit prefill",
+ )
+ parser.add_argument(
+ "--arena-step-mib", "--pool-step-mib",
+ dest="arena_step_mib", type=int, default=32,
+ )
+ parser.add_argument(
+ "--arena-backoff-mib", "--pool-backoff-mib",
+ dest="arena_backoff_mib", type=int, default=64,
+ )
+ parser.add_argument(
+ "--arena-retries", "--pool-retries",
+ dest="arena_retries", type=int, default=8,
+ )
+ parser.add_argument(
+ "--max-arena-mib", "--max-pool-mib",
+ dest="max_arena_mib", type=int,
+ )
+ parser.add_argument(
+ "--fixed-arena-mib", "--fixed-pool-mib",
+ dest="fixed_arena_mib",
+ type=int,
+ help="use exactly this shared arena size and skip per-context probing",
+ )
+ parser.add_argument(
+ "--trace-kv-stream",
+ action="store_true",
+ help="enable and parse adaptive KV residency trace logging",
+ )
+ parser.add_argument("--gpu-index", type=int, default=0)
+ parser.add_argument(
+ "--cuda-visible-devices",
+ help="CUDA_VISIBLE_DEVICES value for the server; defaults to the inherited value",
+ )
+ parser.add_argument("--nvidia-smi", default="nvidia-smi")
+ parser.add_argument("--port", type=int, default=12355)
+ parser.add_argument("--startup-timeout", type=int, default=240)
+ parser.add_argument("--request-timeout", type=int, default=1800)
+ parser.add_argument("--release-timeout", type=int, default=90)
+ parser.add_argument("--release-slack-mib", type=int, default=64)
+ parser.add_argument("--prompt-suffix", default="The capital of France is")
+ parser.add_argument("--fill-token-id", type=int)
+ parser.add_argument(
+ "--extra-server-arg",
+ action="append",
+ default=[],
+ metavar="ARG",
+ help="append a server argument (repeat; use --extra-server-arg=--flag)",
+ )
+ args = parser.parse_args(argv)
+ args.model = args.model.resolve()
+ args.server = args.server.resolve()
+ return args
+
+
+def context_capacities(
+ max_context: int,
+ min_context: int = CONTEXT_STEP,
+ step: int = CONTEXT_STEP,
+) -> list[int]:
+ capacities = list(range(min_context, max_context + 1, step))
+ if not capacities or capacities[-1] != max_context:
+ capacities.append(max_context)
+ return capacities
+
+
+@dataclass(frozen=True)
+class GpuMemory:
+ total_mib: int
+ used_mib: int
+ free_mib: int
+
+
+def query_gpu_memory(nvidia_smi: str, gpu_index: int) -> GpuMemory:
+ try:
+ result = subprocess.run(
+ [
+ nvidia_smi,
+ "-i",
+ str(gpu_index),
+ "--query-gpu=memory.total,memory.used,memory.free",
+ "--format=csv,noheader,nounits",
+ ],
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=False,
+ )
+ except OSError as exc:
+ raise RuntimeError(f"cannot run nvidia-smi executable: {nvidia_smi}") from exc
+ if result.returncode != 0:
+ raise RuntimeError(f"nvidia-smi failed: {result.stderr.strip()}")
+ try:
+ total, used, free = (
+ int(part.strip()) for part in result.stdout.splitlines()[0].split(",")
+ )
+ except (IndexError, ValueError) as exc:
+ raise RuntimeError(f"unexpected nvidia-smi output: {result.stdout!r}") from exc
+ return GpuMemory(total, used, free)
+
+
+def estimate_arena_mib(
+ probe_arena_mib: int,
+ free_mib: int,
+ step_mib: int,
+ max_arena_mib: int | None = None,
+) -> int:
+ candidate = probe_arena_mib + free_mib
+ candidate = candidate // step_mib * step_mib
+ if max_arena_mib is not None:
+ candidate = min(candidate, max_arena_mib // step_mib * step_mib)
+ if candidate < probe_arena_mib:
+ raise RuntimeError(f"only {free_mib} MiB is free after the probe")
+ return candidate
+
+
+def http_json(url: str, payload: dict | None, timeout: int) -> dict:
+ request = urllib.request.Request(
+ url,
+ data=None if payload is None else json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ return json.load(response)
+ except urllib.error.HTTPError as exc:
+ body = exc.read().decode(errors="replace")
+ raise RuntimeError(f"HTTP {exc.code}: {body[:1000]}") from exc
+
+
+def clean_server_env(
+ cuda_visible_devices: str | None,
+ trace_kv_stream: bool = False,
+) -> dict[str, str]:
+ env = os.environ.copy()
+ env.pop("GGML_CUDA_KV_STREAM_FIXED_RING_SLOTS", None)
+ env.pop("LLAMA_KV_STREAM_TRACE", None)
+ if trace_kv_stream:
+ env["LLAMA_KV_STREAM_TRACE"] = "1"
+ if cuda_visible_devices is not None:
+ env["CUDA_VISIBLE_DEVICES"] = cuda_visible_devices
+ return env
+
+
+def server_command(
+ args: argparse.Namespace,
+ context_capacity: int,
+ arena_mib: int,
+) -> list[str]:
+ return [
+ str(args.server),
+ "-m",
+ str(args.model),
+ "--alias",
+ "adaptive-kv-stream",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(args.port),
+ "--ctx-size",
+ str(context_capacity),
+ "-fa",
+ "on",
+ "-ctk",
+ args.cache_type_k,
+ "-ctv",
+ args.cache_type_v,
+ "-ngl",
+ "all",
+ "-b",
+ str(args.batch_size),
+ "-ub",
+ str(args.ubatch_size),
+ "-np",
+ "1",
+ "--no-mmproj",
+ "--no-warmup",
+ "--fit",
+ "off",
+ "--reasoning-format",
+ "none",
+ "--kv-stream-arena-mib",
+ str(arena_mib),
+ *args.extra_server_arg,
+ ]
+
+
+class Server:
+ def __init__(
+ self,
+ args: argparse.Namespace,
+ context_capacity: int,
+ arena_mib: int,
+ log_path: Path,
+ ) -> None:
+ self.port = args.port
+ self.log_path = log_path
+ self.log_file = log_path.open("wb")
+ self.process: subprocess.Popen | None = None
+ try:
+ self.process = subprocess.Popen(
+ server_command(args, context_capacity, arena_mib),
+ cwd=args.server.parent,
+ env=clean_server_env(
+ args.cuda_visible_devices,
+ args.trace_kv_stream,
+ ),
+ stdout=self.log_file,
+ stderr=subprocess.STDOUT,
+ )
+ except Exception:
+ self.log_file.close()
+ raise
+
+ deadline = time.monotonic() + args.startup_timeout
+ last_error = "server did not become ready"
+ while time.monotonic() < deadline:
+ status = self.process.poll()
+ if status is not None:
+ self.log_file.flush()
+ log_tail = self.log_tail()
+ self.stop()
+ raise RuntimeError(f"server exited with status {status}: {log_tail}")
+ try:
+ health = http_json(self.url("/health"), None, 2)
+ if health.get("status") == "ok":
+ return
+ except Exception as exc:
+ last_error = str(exc)
+ time.sleep(0.25)
+ self.stop()
+ raise RuntimeError(f"{last_error}: {self.log_tail()}")
+
+ def url(self, path: str) -> str:
+ return f"http://127.0.0.1:{self.port}{path}"
+
+ def log_tail(self, lines: int = 30) -> str:
+ try:
+ return "\n".join(
+ self.log_path.read_text(errors="replace").splitlines()[-lines:]
+ )
+ except OSError:
+ return ""
+
+ def stop(self) -> None:
+ if self.process is not None and self.process.poll() is None:
+ self.process.send_signal(signal.SIGINT)
+ try:
+ self.process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait(timeout=10)
+ if not self.log_file.closed:
+ self.log_file.close()
+
+
+def wait_for_release(
+ args: argparse.Namespace,
+ baseline_used_mib: int,
+) -> None:
+ deadline = time.monotonic() + args.release_timeout
+ while time.monotonic() < deadline:
+ memory = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ if memory.used_mib <= baseline_used_mib + args.release_slack_mib:
+ return
+ time.sleep(1)
+ memory = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ raise RuntimeError(
+ f"GPU memory did not return to baseline: "
+ f"{memory.used_mib} MiB used, baseline {baseline_used_mib} MiB"
+ )
+
+
+def prepare_server(
+ args: argparse.Namespace,
+ server: Server,
+) -> tuple[list[int], int]:
+ tokenized = http_json(
+ server.url("/tokenize"),
+ {"content": args.prompt_suffix, "add_special": False},
+ 30,
+ )
+ suffix = tokenized.get("tokens")
+ if not suffix or not all(isinstance(token, int) for token in suffix):
+ raise RuntimeError(f"unexpected tokenize response: {tokenized}")
+ fill_token_id = (
+ args.fill_token_id if args.fill_token_id is not None else suffix[0]
+ )
+ http_json(
+ server.url("/completion"),
+ {
+ "prompt": [fill_token_id] * args.ubatch_size,
+ "n_predict": 4,
+ "ignore_eos": True,
+ "cache_prompt": False,
+ "temperature": 0,
+ "reasoning_format": "none",
+ "response_fields": ["timings"],
+ },
+ args.request_timeout,
+ )
+ return suffix, fill_token_id
+
+
+def append_jsonl(path: Path, row: dict) -> None:
+ with path.open("a") as stream:
+ stream.write(json.dumps(row, sort_keys=True) + "\n")
+ print(json.dumps(row, sort_keys=True), flush=True)
+
+
+def load_measurements(path: Path) -> dict[int, dict]:
+ rows: dict[int, dict] = {}
+ if not path.is_file():
+ return rows
+ with path.open() as stream:
+ for line in stream:
+ row = json.loads(line)
+ if row.get("type") == "measurement" and row.get("status") == "ok":
+ rows[int(row["context_capacity"])] = row
+ return rows
+
+
+def load_metadata(path: Path) -> dict | None:
+ if not path.is_file():
+ return None
+ with path.open() as stream:
+ for line in stream:
+ row = json.loads(line)
+ if row.get("type") == "metadata":
+ return row
+ return None
+
+
+def resume_signature(args: argparse.Namespace, capacities: list[int]) -> dict:
+ return {
+ "model": str(args.model.resolve()),
+ "server": str(args.server.resolve()),
+ "max_context": args.max_context,
+ "min_context": args.min_context,
+ "context_step": args.context_step,
+ "cache_type_k": args.cache_type_k,
+ "cache_type_v": args.cache_type_v,
+ "fixed_arena_mib": args.fixed_arena_mib,
+ "trace_kv_stream": args.trace_kv_stream,
+ "capacities": capacities,
+ "decode_tokens": args.decode_tokens,
+ "batch_size": args.batch_size,
+ "ubatch_size": args.ubatch_size,
+ "probe_arena_mib": args.probe_arena_mib,
+ "probe_arena_step_mib": args.probe_arena_step_mib,
+ "arena_step_mib": args.arena_step_mib,
+ "arena_backoff_mib": args.arena_backoff_mib,
+ "arena_retries": args.arena_retries,
+ "max_arena_mib": args.max_arena_mib,
+ "gpu_index": args.gpu_index,
+ "cuda_visible_devices": args.cuda_visible_devices,
+ "fill_token_id": args.fill_token_id,
+ "prompt_suffix": args.prompt_suffix,
+ "extra_server_args": args.extra_server_arg,
+ }
+
+
+def validate_resume(metadata: dict | None, signature: dict, path: Path) -> None:
+ if metadata is None:
+ raise SystemExit(f"existing result file has no metadata record: {path}")
+ mismatches = [
+ key for key, value in signature.items() if metadata.get(key) != value
+ ]
+ if mismatches:
+ details = ", ".join(
+ f"{key}={metadata.get(key)!r} (requested {signature[key]!r})"
+ for key in mismatches
+ )
+ raise SystemExit(
+ f"cannot resume {path} with different settings: {details}"
+ )
+
+
+def git_revision() -> str:
+ result = subprocess.run(
+ ["git", "rev-parse", "--short=12", "HEAD"],
+ cwd=ROOT,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ check=False,
+ )
+ return result.stdout.strip() or "unknown"
+
+
+def probe_arena(
+ args: argparse.Namespace,
+ context_capacity: int,
+ baseline_used_mib: int,
+ logs_dir: Path,
+ results_path: Path,
+) -> int:
+ arena_mib = args.probe_arena_mib
+ last_error = "arena probe did not run"
+ for attempt in range(args.arena_retries + 1):
+ print(
+ f"[{context_capacity}] VRAM probe attempt {attempt + 1}: "
+ f"arena={arena_mib} MiB",
+ flush=True,
+ )
+ server: Server | None = None
+ try:
+ server = Server(
+ args,
+ context_capacity,
+ arena_mib,
+ logs_dir / (
+ f"context-{context_capacity}-probe-arena-{arena_mib}.log"
+ ),
+ )
+ prepare_server(args, server)
+ memory = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ selected_arena = estimate_arena_mib(
+ arena_mib,
+ memory.free_mib,
+ args.arena_step_mib,
+ args.max_arena_mib,
+ )
+ append_jsonl(
+ results_path,
+ {
+ "type": "arena_probe",
+ "context_capacity": context_capacity,
+ "probe_arena_mib": arena_mib,
+ "selected_arena_mib": selected_arena,
+ "vram_total_mib": memory.total_mib,
+ "vram_used_mib": memory.used_mib,
+ "vram_free_mib": memory.free_mib,
+ },
+ )
+ return selected_arena
+ except Exception as exc:
+ last_error = str(exc)
+ append_jsonl(
+ results_path,
+ {
+ "type": "arena_probe_attempt",
+ "status": "failed",
+ "context_capacity": context_capacity,
+ "arena_mib": arena_mib,
+ "attempt": attempt + 1,
+ "error": last_error[-4000:],
+ },
+ )
+ finally:
+ if server is not None:
+ server.stop()
+ wait_for_release(args, baseline_used_mib)
+
+ next_arena = arena_mib + args.probe_arena_step_mib
+ if args.max_arena_mib is not None and next_arena > args.max_arena_mib:
+ break
+ arena_mib = next_arena
+
+ raise RuntimeError(
+ f"context {context_capacity} could not start an arena probe: {last_error}"
+ )
+
+
+def parse_kv_stream_trace(log_path: Path) -> dict:
+ text = log_path.read_text(errors="replace")
+ samples = []
+ for match in KV_STREAM_TRACE_RE.finditer(text):
+ active_tokens = int(match.group(1))
+ resident_pages = int(match.group(2))
+ samples.append(
+ {
+ "active_tokens": active_tokens,
+ "active_pages": (active_tokens + 255) // 256,
+ "resident_pages": resident_pages,
+ "ring_slots": int(match.group(3)),
+ }
+ )
+ streamed = [
+ sample
+ for sample in samples
+ if sample["active_pages"] > sample["resident_pages"]
+ ]
+ return {
+ "streaming_active": bool(streamed),
+ "stream_first_active_tokens": (
+ min(sample["active_tokens"] for sample in streamed)
+ if streamed
+ else None
+ ),
+ "stream_trace_samples": len(samples),
+ "stream_max_active_pages": max(
+ (sample["active_pages"] for sample in samples), default=None
+ ),
+ "stream_min_resident_pages": min(
+ (sample["resident_pages"] for sample in samples), default=None
+ ),
+ "stream_max_ring_slots": max(
+ (sample["ring_slots"] for sample in samples), default=None
+ ),
+ "stream_repartitions": text.count("adaptive KV partition:"),
+ }
+
+
+
+
+def decode_shortfall_tolerance(extra_server_args: list[str]) -> int:
+ """Speculative decoding (--spec-chain N) verifies up to N+1 tokens per
+ step. The exact prompt/decode split in run_measurement() leaves no slack
+ past context_capacity, so the last verification chunk near that boundary
+ can be clipped short by a few tokens instead of landing exactly on
+ decode_tokens. decode_tps is the server's own measured rate (actual
+ predicted_n / predicted_ms), so it stays correct regardless - this
+ tolerance only avoids flagging that harmless shortfall as a failure.
+ """
+ if "--spec-chain" not in extra_server_args:
+ return 0
+ try:
+ return 1 + int(
+ extra_server_args[extra_server_args.index("--spec-chain") + 1]
+ )
+ except (ValueError, IndexError):
+ return 0
+
+
+def run_measurement(
+ args: argparse.Namespace,
+ context_capacity: int,
+ arena_mib: int,
+ baseline_used_mib: int,
+ logs_dir: Path,
+) -> dict:
+ prompt_tokens = context_capacity - args.decode_tokens
+ server: Server | None = None
+ try:
+ server = Server(
+ args,
+ context_capacity,
+ arena_mib,
+ logs_dir / f"context-{context_capacity}-arena-{arena_mib}.log",
+ )
+ suffix, fill_token_id = prepare_server(args, server)
+ prefix_count = prompt_tokens - len(suffix)
+ if prefix_count < 0:
+ raise RuntimeError("context capacity is too small for the prompt")
+ prompt = [fill_token_id] * prefix_count + suffix
+ before = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ started = time.monotonic()
+ response = http_json(
+ server.url("/completion"),
+ {
+ "prompt": prompt,
+ "n_predict": args.decode_tokens,
+ "ignore_eos": True,
+ "cache_prompt": False,
+ "temperature": 0,
+ "seed": 1,
+ "reasoning_format": "none",
+ "response_fields": ["timings"],
+ },
+ args.request_timeout,
+ )
+ timings = response.get("timings") or {}
+ predicted_n = timings.get("predicted_n")
+ spec_chain_tolerance = decode_shortfall_tolerance(args.extra_server_arg)
+ if predicted_n is None or predicted_n < args.decode_tokens - spec_chain_tolerance:
+ raise RuntimeError(
+ f"incomplete decode: expected {args.decode_tokens} "
+ f"(tolerance {spec_chain_tolerance}), received {predicted_n}"
+ )
+ after = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ measurement = {
+ "type": "measurement",
+ "status": "ok",
+ "context_capacity": context_capacity,
+ "prompt_tokens": prompt_tokens,
+ "decode_tokens": args.decode_tokens,
+ "arena_mib": arena_mib,
+ "fill_token_id": fill_token_id,
+ "prompt_ms": timings.get("prompt_ms"),
+ "prefill_tps": timings.get("prompt_per_second"),
+ "predicted_ms": timings.get("predicted_ms"),
+ "decode_tps": timings.get("predicted_per_second"),
+ "wall_seconds": time.monotonic() - started,
+ "vram_before_mib": before.used_mib,
+ "vram_after_mib": after.used_mib,
+ "vram_free_after_mib": after.free_mib,
+ }
+ if args.trace_kv_stream:
+ measurement.update(parse_kv_stream_trace(server.log_path))
+ return measurement
+ finally:
+ if server is not None:
+ server.stop()
+ wait_for_release(args, baseline_used_mib)
+
+
+def benchmark_with_backoff(
+ args: argparse.Namespace,
+ context_capacity: int,
+ selected_arena_mib: int,
+ baseline_used_mib: int,
+ logs_dir: Path,
+ results_path: Path,
+) -> dict:
+ arena_mib = selected_arena_mib
+ last_error = "benchmark did not run"
+ for attempt in range(args.arena_retries + 1):
+ print(
+ f"[{context_capacity}] benchmark attempt {attempt + 1}: "
+ f"arena={arena_mib} MiB",
+ flush=True,
+ )
+ try:
+ return run_measurement(
+ args,
+ context_capacity,
+ arena_mib,
+ baseline_used_mib,
+ logs_dir,
+ )
+ except Exception as exc:
+ last_error = str(exc)
+ append_jsonl(
+ results_path,
+ {
+ "type": "measurement_attempt",
+ "status": "failed",
+ "context_capacity": context_capacity,
+ "arena_mib": arena_mib,
+ "attempt": attempt + 1,
+ "error": last_error[-4000:],
+ },
+ )
+ next_arena = (
+ (arena_mib - args.arena_backoff_mib)
+ // args.arena_step_mib
+ * args.arena_step_mib
+ )
+ if next_arena < args.probe_arena_mib:
+ break
+ arena_mib = next_arena
+ raise RuntimeError(
+ f"context {context_capacity} failed after arena backoff: {last_error}"
+ )
+
+
+def write_csv(path: Path, rows: dict[int, dict]) -> None:
+ fields = [
+ "context_capacity",
+ "prompt_tokens",
+ "decode_tokens",
+ "arena_mib",
+ "prefill_tps",
+ "decode_tps",
+ "prompt_ms",
+ "predicted_ms",
+ "wall_seconds",
+ "vram_before_mib",
+ "vram_after_mib",
+ "vram_free_after_mib",
+ "streaming_active",
+ "stream_first_active_tokens",
+ "stream_trace_samples",
+ "stream_max_active_pages",
+ "stream_min_resident_pages",
+ "stream_max_ring_slots",
+ "stream_repartitions",
+ ]
+ with path.open("w", newline="") as stream:
+ writer = csv.DictWriter(stream, fieldnames=fields)
+ writer.writeheader()
+ for context in sorted(rows):
+ writer.writerow({field: rows[context].get(field) for field in fields})
+
+
+def require_matplotlib():
+ try:
+ import matplotlib.pyplot as plt
+ except ModuleNotFoundError as exc:
+ raise SystemExit(
+ "Matplotlib is required. Install it with: "
+ "python3 -m pip install matplotlib"
+ ) from exc
+ return plt
+
+
+def plot_results(output_dir: Path, rows: dict[int, dict], plt) -> None:
+ if not rows:
+ return
+ contexts = sorted(rows)
+ # Decimal K (1,000), not binary Ki (1,024) - 700000 tokens must read as
+ # an unambiguous "700" on the axis, not a confusing 683.6. The footnote
+ # spells this out so a reader never mistakes the axis for raw token
+ # counts or for Ki-scaled values.
+ x = [context / 1000.0 for context in contexts]
+
+ fig, (decode_ax, arena_ax) = plt.subplots(
+ 2,
+ 1,
+ figsize=(12.5, 9),
+ height_ratios=(3, 1),
+ sharex=True,
+ constrained_layout=True,
+ )
+ prefill_ax = decode_ax.twinx()
+ decode_ax.plot(
+ x,
+ [rows[context]["decode_tps"] for context in contexts],
+ color="#1f77b4",
+ marker="o",
+ linewidth=2.4,
+ label="Decode speed",
+ )
+ prefill_ax.plot(
+ x,
+ [rows[context]["prefill_tps"] for context in contexts],
+ color="#ff7f0e",
+ marker="o",
+ linestyle="--",
+ linewidth=2.2,
+ label="Prefill speed",
+ )
+ arena_ax.plot(
+ x,
+ [rows[context]["arena_mib"] for context in contexts],
+ color="#666666",
+ marker="o",
+ linewidth=1.8,
+ label="Selected shared arena",
+ )
+
+ decode_ax.set_title("Adaptive KV streaming context sweep")
+ decode_ax.set_ylabel("Decode speed (tokens/s)")
+ prefill_ax.set_ylabel("Prefill speed (tokens/s)")
+ arena_ax.set_xlabel("Configured context capacity (K tokens)")
+ arena_ax.set_ylabel("Arena (MiB)")
+ decode_ax.set_ylim(bottom=0)
+ prefill_ax.set_ylim(bottom=0)
+ arena_ax.set_ylim(bottom=0)
+ decode_ax.grid(True, alpha=0.25)
+ arena_ax.grid(True, alpha=0.25)
+ handles_a, labels_a = decode_ax.get_legend_handles_labels()
+ handles_b, labels_b = prefill_ax.get_legend_handles_labels()
+ decode_ax.legend(handles_a + handles_b, labels_a + labels_b, loc="best")
+ arena_ax.legend(loc="best")
+ fig.text(
+ 0.01, 0.005,
+ "Note: K = 1,000 tokens (decimal), not 1,024 - e.g. 700 on this axis is 700,000 tokens.",
+ fontsize=8, color="#555555", ha="left",
+ )
+
+ png_path = output_dir / "kv-stream-sweep.png"
+ fig.savefig(png_path, dpi=180)
+ fig.savefig(png_path.with_suffix(".svg"))
+ plt.close(fig)
+
+
+def validate_args(args: argparse.Namespace) -> None:
+ if not args.model.is_file():
+ raise SystemExit(f"model not found: {args.model}")
+ if not args.server.is_file() or not os.access(args.server, os.X_OK):
+ raise SystemExit(f"server is not executable: {args.server}")
+ numeric_positive = (
+ args.decode_tokens,
+ args.batch_size,
+ args.ubatch_size,
+ args.probe_arena_mib,
+ args.probe_arena_step_mib,
+ args.arena_step_mib,
+ args.arena_backoff_mib,
+ args.startup_timeout,
+ args.request_timeout,
+ args.release_timeout,
+ )
+ if any(value <= 0 for value in numeric_positive):
+ raise SystemExit("decode, batch, arena, and timeout settings must be positive")
+ if args.min_context <= 0 or args.context_step <= 0:
+ raise SystemExit("minimum context and context step must be positive")
+ if args.min_context > args.max_context:
+ raise SystemExit("minimum context must not exceed maximum context")
+ if args.ubatch_size > args.batch_size:
+ raise SystemExit("ubatch size must not exceed batch size")
+ if args.fixed_arena_mib is not None and args.fixed_arena_mib <= 0:
+ raise SystemExit("fixed arena must be positive")
+ if (
+ args.arena_retries < 0
+ or args.release_slack_mib < 0
+ ):
+ raise SystemExit("retry count and release slack must not be negative")
+ if args.max_arena_mib is not None and args.max_arena_mib < args.probe_arena_mib:
+ raise SystemExit("maximum arena must be at least the probe arena")
+ if args.gpu_index < 0 or not 1 <= args.port <= 65535:
+ raise SystemExit("GPU index or port is invalid")
+ if args.max_context < CONTEXT_STEP:
+ raise SystemExit("maximum context must be at least 8192")
+ if args.decode_tokens >= CONTEXT_STEP:
+ raise SystemExit("decode token count must be smaller than 8192")
+ if not args.prompt_suffix:
+ raise SystemExit("prompt suffix must not be empty")
+ if args.fill_token_id is not None and args.fill_token_id < 0:
+ raise SystemExit("fill token ID must not be negative")
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ validate_args(args)
+ plt = require_matplotlib()
+
+ stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
+ if args.output_dir is None:
+ args.output_dir = (
+ ROOT / "benchmarks/results" / f"adaptive-kv-sweep-{stamp}"
+ )
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+ logs_dir = args.output_dir / "logs"
+ logs_dir.mkdir(parents=True, exist_ok=True)
+ results_path = args.output_dir / "results.jsonl"
+ csv_path = args.output_dir / "results.csv"
+
+ baseline = query_gpu_memory(args.nvidia_smi, args.gpu_index)
+ capacities = context_capacities(
+ args.max_context,
+ args.min_context,
+ args.context_step,
+ )
+ signature = resume_signature(args, capacities)
+ if results_path.exists():
+ validate_resume(load_metadata(results_path), signature, results_path)
+ rows = load_measurements(results_path)
+
+ if not results_path.exists():
+ append_jsonl(
+ results_path,
+ {
+ "type": "metadata",
+ "timestamp": dt.datetime.now(dt.timezone.utc).isoformat(),
+ "revision": git_revision(),
+ **signature,
+ "cache_type_k": args.cache_type_k,
+ "cache_type_v": args.cache_type_v,
+ "flash_attention": True,
+ "parallel": 1,
+ "baseline_vram_used_mib": baseline.used_mib,
+ "baseline_vram_total_mib": baseline.total_mib,
+ "uvm": False,
+ },
+ )
+
+ print(
+ f"GPU baseline: {baseline.used_mib}/{baseline.total_mib} MiB used",
+ flush=True,
+ )
+ print(
+ f"Sweep: {len(capacities)} points, {args.min_context} through "
+ f"{args.max_context} tokens, K={args.cache_type_k}, V={args.cache_type_v}",
+ flush=True,
+ )
+
+ interrupted = False
+ failed = False
+ try:
+ for index, context_capacity in enumerate(capacities, start=1):
+ if context_capacity in rows:
+ print(
+ f"[{index}/{len(capacities)}] {context_capacity}: "
+ "already complete",
+ flush=True,
+ )
+ continue
+ print(
+ f"[{index}/{len(capacities)}] context capacity "
+ f"{context_capacity}",
+ flush=True,
+ )
+ try:
+ if args.fixed_arena_mib is None:
+ selected_arena = probe_arena(
+ args, context_capacity, baseline.used_mib,
+ logs_dir, results_path,
+ )
+ measurement = benchmark_with_backoff(
+ args, context_capacity, selected_arena,
+ baseline.used_mib, logs_dir, results_path,
+ )
+ else:
+ selected_arena = args.fixed_arena_mib
+ measurement = run_measurement(
+ args, context_capacity, selected_arena,
+ baseline.used_mib, logs_dir,
+ )
+ append_jsonl(results_path, measurement)
+ rows[context_capacity] = measurement
+ write_csv(csv_path, rows)
+ plot_results(args.output_dir, rows, plt)
+ except Exception as exc:
+ failed = True
+ append_jsonl(
+ results_path,
+ {
+ "type": "point_failure",
+ "status": "failed",
+ "context_capacity": context_capacity,
+ "error": str(exc)[-4000:],
+ },
+ )
+ print(
+ "Stopping at the first failed context. Re-run with the "
+ "same --output-dir to resume after correcting the issue.",
+ file=sys.stderr,
+ flush=True,
+ )
+ break
+ except KeyboardInterrupt:
+ interrupted = True
+ print("Sweep interrupted; completed points remain resumable.", flush=True)
+ finally:
+ if rows:
+ write_csv(csv_path, rows)
+ plot_results(args.output_dir, rows, plt)
+
+ print(f"JSONL: {results_path}", flush=True)
+ if rows:
+ print(f"CSV: {csv_path}", flush=True)
+ print(f"Plot: {args.output_dir / 'kv-stream-sweep.png'}", flush=True)
+ if interrupted:
+ return 130
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/benchmarks/benchmark_kv_type_matrix.py b/benchmarks/benchmark_kv_type_matrix.py
new file mode 100644
index 000000000000..211592a41614
--- /dev/null
+++ b/benchmarks/benchmark_kv_type_matrix.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+"""Benchmark and plot a matrix of adaptive-streaming K/V cache types."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import datetime as dt
+from pathlib import Path
+import subprocess
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[1]
+RUNNER = Path(__file__).with_name("benchmark_kv_stream.py")
+DEFAULT_TYPES = ("bf16", "q8_0", "q4_0")
+
+
+def parse_token_count(value: str) -> int:
+ text = value.strip().lower()
+ for suffix, multiplier in (
+ ("kib", 1024),
+ ("ki", 1024),
+ ("k", 1024),
+ ):
+ if text.endswith(suffix):
+ text = text[:-len(suffix)]
+ break
+ else:
+ multiplier = 1
+ try:
+ count = int(text) * multiplier
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError(f"invalid token count: {value}") from exc
+ if count <= 0:
+ raise argparse.ArgumentTypeError("token count must be positive")
+ return count
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument("--model", type=Path, required=True)
+ parser.add_argument(
+ "--server",
+ type=Path,
+ default=ROOT / "build-kv-cuda/bin/llama-server",
+ )
+ parser.add_argument("--min-context", type=parse_token_count, default=40 * 1024)
+ parser.add_argument("--max-context", type=parse_token_count, default=160 * 1024)
+ parser.add_argument("--context-step", type=parse_token_count, default=8 * 1024)
+ parser.add_argument("--decode-tokens", type=int, default=256)
+ parser.add_argument(
+ "--arena-mib", "--pool-mib",
+ dest="arena_mib",
+ type=int,
+ help="fixed shared arena; omit to probe the maximum usable arena at every point",
+ )
+ parser.add_argument(
+ "--types",
+ default=",".join(DEFAULT_TYPES),
+ help="comma-separated cache types used for both K and V",
+ )
+ parser.add_argument("--port", type=int, default=12355)
+ parser.add_argument("--startup-timeout", type=int, default=240)
+ parser.add_argument("--request-timeout", type=int, default=1800)
+ parser.add_argument(
+ "--output-dir",
+ type=Path,
+ help="result directory; reuse it to resume an interrupted matrix",
+ )
+ parser.add_argument(
+ "--plot-only",
+ action="store_true",
+ help="skip measurements and regenerate outputs from completed pair CSVs",
+ )
+ return parser.parse_args(argv)
+
+
+def cache_types(value: str) -> list[str]:
+ result = [item.strip().lower() for item in value.split(",") if item.strip()]
+ if not result:
+ raise SystemExit("at least one cache type is required")
+ if len(set(result)) != len(result):
+ raise SystemExit("cache types must not contain duplicates")
+ return result
+
+
+def pair_name(type_k: str, type_v: str) -> str:
+ return f"k-{type_k}_v-{type_v}"
+
+
+def runner_command(
+ args: argparse.Namespace,
+ type_k: str,
+ type_v: str,
+ output_dir: Path,
+) -> list[str]:
+ command = [
+ sys.executable,
+ str(RUNNER),
+ "--model",
+ str(args.model),
+ "--server",
+ str(args.server),
+ "--min-context",
+ str(args.min_context),
+ "--max-context",
+ str(args.max_context),
+ "--context-step",
+ str(args.context_step),
+ "--decode-tokens",
+ str(args.decode_tokens),
+ "--cache-type-k",
+ type_k,
+ "--cache-type-v",
+ type_v,
+ "--trace-kv-stream",
+ "--port",
+ str(args.port),
+ "--startup-timeout",
+ str(args.startup_timeout),
+ "--request-timeout",
+ str(args.request_timeout),
+ "--output-dir",
+ str(output_dir),
+ ]
+ if args.arena_mib is not None:
+ command.extend(("--fixed-arena-mib", str(args.arena_mib)))
+ return command
+
+
+def parse_bool(value: str | bool | None) -> bool:
+ if isinstance(value, bool):
+ return value
+ return str(value).strip().lower() in ("1", "true", "yes")
+
+
+def collect_rows(output_dir: Path, types: list[str]) -> list[dict]:
+ rows = []
+ for type_k in types:
+ for type_v in types:
+ path = output_dir / pair_name(type_k, type_v) / "results.csv"
+ if not path.is_file():
+ continue
+ with path.open(newline="") as stream:
+ for row in csv.DictReader(stream):
+ row["cache_type_k"] = type_k
+ row["cache_type_v"] = type_v
+ row["pair"] = f"K={type_k.upper()}, V={type_v.upper()}"
+ if not row.get("arena_mib") and row.get("pool_mib"):
+ row["arena_mib"] = row["pool_mib"]
+ row["streaming_active"] = parse_bool(row.get("streaming_active"))
+ rows.append(row)
+ return rows
+
+
+def write_combined_csv(path: Path, rows: list[dict]) -> None:
+ fields = [
+ "cache_type_k",
+ "cache_type_v",
+ "pair",
+ "context_capacity",
+ "prompt_tokens",
+ "decode_tokens",
+ "arena_mib",
+ "prefill_tps",
+ "decode_tps",
+ "prompt_ms",
+ "predicted_ms",
+ "wall_seconds",
+ "vram_before_mib",
+ "vram_after_mib",
+ "vram_free_after_mib",
+ "streaming_active",
+ "stream_first_active_tokens",
+ "stream_trace_samples",
+ "stream_max_active_pages",
+ "stream_min_resident_pages",
+ "stream_max_ring_slots",
+ "stream_repartitions",
+ ]
+ with path.open("w", newline="") as stream:
+ writer = csv.DictWriter(stream, fieldnames=fields)
+ writer.writeheader()
+ for row in sorted(
+ rows,
+ key=lambda item: (
+ item["cache_type_k"],
+ item["cache_type_v"],
+ int(item["context_capacity"]),
+ ),
+ ):
+ writer.writerow({field: row.get(field) for field in fields})
+
+
+def write_onsets(path: Path, rows: list[dict], types: list[str]) -> None:
+ with path.open("w", newline="") as stream:
+ writer = csv.DictWriter(
+ stream,
+ fieldnames=(
+ "cache_type_k",
+ "cache_type_v",
+ "first_streaming_context",
+ "first_streaming_context_kib",
+ "first_stream_active_tokens",
+ ),
+ )
+ writer.writeheader()
+ for type_k in types:
+ for type_v in types:
+ pair_rows = sorted(
+ (
+ row
+ for row in rows
+ if row["cache_type_k"] == type_k
+ and row["cache_type_v"] == type_v
+ and row["streaming_active"]
+ ),
+ key=lambda row: int(row["context_capacity"]),
+ )
+ first = pair_rows[0] if pair_rows else None
+ context = int(first["context_capacity"]) if first else None
+ writer.writerow(
+ {
+ "cache_type_k": type_k,
+ "cache_type_v": type_v,
+ "first_streaming_context": context,
+ "first_streaming_context_kib": (
+ context / 1024 if context is not None else None
+ ),
+ "first_stream_active_tokens": (
+ first.get("stream_first_active_tokens") if first else None
+ ),
+ }
+ )
+
+
+def plot_results(path: Path, rows: list[dict], types: list[str]) -> None:
+ import matplotlib.pyplot as plt
+ from matplotlib.lines import Line2D
+
+ pairs = [(type_k, type_v) for type_k in types for type_v in types]
+ cmap = plt.get_cmap("tab10")
+ fig, (prefill_ax, decode_ax) = plt.subplots(
+ 2,
+ 1,
+ figsize=(15, 11),
+ sharex=True,
+ constrained_layout=True,
+ )
+ pair_handles = []
+ for index, (type_k, type_v) in enumerate(pairs):
+ pair_rows = sorted(
+ (
+ row for row in rows
+ if row["cache_type_k"] == type_k and row["cache_type_v"] == type_v
+ ),
+ key=lambda row: int(row["context_capacity"]),
+ )
+ if not pair_rows:
+ continue
+ color = cmap(index % 10)
+ label = f"K={type_k.upper()}, V={type_v.upper()}"
+ pair_handles.append(Line2D([0], [0], color=color, lw=2.2, label=label))
+ x = [int(row["context_capacity"]) / 1024 for row in pair_rows]
+ for axis, metric, style in (
+ (prefill_ax, "prefill_tps", "--"),
+ (decode_ax, "decode_tps", "-"),
+ ):
+ y = [float(row[metric]) for row in pair_rows]
+ axis.plot(x, y, color=color, linestyle=style, linewidth=2.0)
+ inactive = [
+ (x_value, y_value)
+ for x_value, y_value, row in zip(x, y, pair_rows)
+ if not row["streaming_active"]
+ ]
+ active = [
+ (x_value, y_value)
+ for x_value, y_value, row in zip(x, y, pair_rows)
+ if row["streaming_active"]
+ ]
+ if inactive:
+ axis.scatter(
+ *zip(*inactive), s=30, facecolors="white",
+ edgecolors=[color], linewidths=1.3, zorder=3,
+ )
+ if active:
+ axis.scatter(
+ *zip(*active), s=34, facecolors=[color],
+ edgecolors="black", linewidths=0.55, zorder=4,
+ )
+ onset = active[0]
+ axis.scatter(
+ [onset[0]], [onset[1]], marker="*", s=190,
+ facecolors=[color], edgecolors="black",
+ linewidths=0.8, zorder=5,
+ )
+
+ selected_types = " / ".join(cache_type.upper() for cache_type in types)
+ prefill_ax.set_title(
+ f"Adaptive KV streaming: {selected_types} cache-type matrix")
+ prefill_ax.set_ylabel("Prefill speed (tokens/s)")
+ decode_ax.set_ylabel("Decode speed (tokens/s)")
+ decode_ax.set_xlabel("Configured context capacity (Ki tokens)")
+ for axis in (prefill_ax, decode_ax):
+ axis.grid(True, alpha=0.25)
+ axis.set_ylim(bottom=0)
+
+ state_handles = [
+ Line2D(
+ [0], [0], marker="o", linestyle="none", markerfacecolor="white",
+ markeredgecolor="black", label="Fully resident",
+ ),
+ Line2D(
+ [0], [0], marker="o", linestyle="none", markerfacecolor="#777777",
+ markeredgecolor="black", label="Streaming active",
+ ),
+ Line2D(
+ [0], [0], marker="*", linestyle="none", markersize=13,
+ markerfacecolor="#777777", markeredgecolor="black",
+ label="First streaming point",
+ ),
+ ]
+ prefill_ax.legend(handles=state_handles, loc="lower left")
+ fig.legend(
+ handles=pair_handles,
+ loc="outside upper center",
+ ncol=3,
+ title="KV cache types",
+ )
+ fig.savefig(path, dpi=190)
+ fig.savefig(path.with_suffix(".svg"))
+ plt.close(fig)
+
+
+def validate_args(args: argparse.Namespace) -> None:
+ if not args.model.is_file():
+ raise SystemExit(f"model not found: {args.model}")
+ if not args.server.is_file():
+ raise SystemExit(f"server not found: {args.server}")
+ if args.min_context > args.max_context:
+ raise SystemExit("minimum context must not exceed maximum context")
+ if min(args.context_step, args.decode_tokens) <= 0:
+ raise SystemExit("step and decode tokens must be positive")
+ if args.arena_mib is not None and args.arena_mib <= 0:
+ raise SystemExit("fixed arena must be positive")
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ validate_args(args)
+ types = cache_types(args.types)
+ if args.output_dir is None:
+ stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
+ args.output_dir = ROOT / "benchmarks/results" / f"kv-type-matrix-{stamp}"
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+
+ pairs = [(type_k, type_v) for type_k in types for type_v in types]
+ if not args.plot_only:
+ for index, (type_k, type_v) in enumerate(pairs, start=1):
+ pair_dir = args.output_dir / pair_name(type_k, type_v)
+ print(
+ f"\n=== [{index}/{len(pairs)}] K={type_k}, V={type_v} ===",
+ flush=True,
+ )
+ subprocess.run(
+ runner_command(args, type_k, type_v, pair_dir),
+ cwd=ROOT,
+ check=True,
+ )
+ rows = collect_rows(args.output_dir, types)
+ write_combined_csv(args.output_dir / "kv-type-matrix.csv", rows)
+ write_onsets(args.output_dir / "streaming-onsets.csv", rows, types)
+ plot_results(args.output_dir / "kv-type-matrix.png", rows, types)
+
+ rows = collect_rows(args.output_dir, types)
+ if not rows:
+ raise SystemExit("no completed measurements found")
+ write_combined_csv(args.output_dir / "kv-type-matrix.csv", rows)
+ write_onsets(args.output_dir / "streaming-onsets.csv", rows, types)
+ plot_results(args.output_dir / "kv-type-matrix.png", rows, types)
+ print(f"Results: {args.output_dir}", flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/benchmarks/results/kv-stream-pr-evidence/README.md b/benchmarks/results/kv-stream-pr-evidence/README.md
new file mode 100644
index 000000000000..6f2ec67ac3db
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/README.md
@@ -0,0 +1,23 @@
+# KV streaming benchmark raw results
+
+Backing data for this PR's description. Referenced from the PR body as
+`results.csv` under each benchmark's own name.
+
+- `qwen3.8-27b-throughput/` - `benchmark_kv_stream.py`, Qwen3.8-27B-AD, 8K->262K, no MTP.
+- `qwen3.8-27b-mtp-throughput/` - same, with `--spec-type draft-mtp --spec-chain 8`, 8K->106K.
+- `gemma4-it-throughput/` - same, Gemma-4-26B-A4B-It, 8K->131K.
+- `qwen3.8-27b-memory/` - `benchmark_kv_memory.py`, Qwen3.8-27B-AD, 131K->786K (YaRN-scaled 4x).
+ `logs/baseline-393216.log` is the full gdb-style backtrace of the real
+ CUDA OOM abort the no-streaming leg hit at 393K context.
+- `gemma4-it-memory/` - same, Gemma-4-26B-A4B-It, 65K->393K (no-streaming never OOM'd in this range).
+- `kld-logs/` - raw `llama-perplexity` output for every PPL/KL-divergence
+ check in the PR draft's "Correctness" sections: baseline and streaming
+ runs at 4K and 32K context for both models, the Gemma4 turbo/f16/no-FA
+ isolation checks, the Gemma4 coherence spot-check, and the 131K attempt
+ that hit a tooling limitation in `llama-perplexity`'s own KL-divergence
+ code (`qwen-streaming-131k-FAILED-tooling-limitation.log`).
+
+Not included: the saved-logits `.kld` files themselves (13-27 GB each,
+regenerate with `--save-all-logits` if needed) and the per-point server
+logs from the memory/throughput sweeps other than the one OOM backtrace
+above (available in the original `--output-dir` if still on disk).
diff --git a/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.csv b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.csv
new file mode 100644
index 000000000000..ba4be0da1967
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.csv
@@ -0,0 +1,7 @@
+context_capacity,arena_mib,streaming_status,streaming_vram_used_mib,streaming_process_rss_mib,streaming_system_ram_used_mib,baseline_status,baseline_vram_used_mib,baseline_process_rss_mib,baseline_system_ram_used_mib,baseline_error
+65536,8192,ok,28769,1857.27734375,70256.5703125,ok,21429,1328.80859375,70087.15234375,
+131072,8192,ok,28759,2397.08984375,70030.01171875,ok,22183,1363.8671875,69993.91796875,
+196608,8192,ok,28755,2937.04296875,70057.3203125,ok,22969,1397.7890625,69996.40625,
+262144,8192,ok,28757,3477.140625,70030.25,ok,23775,1432.91796875,69971.6640625,
+327680,8192,ok,28754,4017.1328125,70071.421875,ok,24569,1468.1640625,70215.3359375,
+393216,8192,ok,28805,4557.12890625,70239.04296875,ok,25363,1502.86328125,70213.88671875,
diff --git a/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.jsonl b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.jsonl
new file mode 100644
index 000000000000..d1373b9655b3
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-memory/results.jsonl
@@ -0,0 +1,6 @@
+{"context_capacity": 65536, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28769, "streaming_process_rss_mib": 1857.27734375, "streaming_system_ram_used_mib": 70256.5703125, "baseline_status": "ok", "baseline_vram_used_mib": 21429, "baseline_process_rss_mib": 1328.80859375, "baseline_system_ram_used_mib": 70087.15234375}
+{"context_capacity": 131072, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28759, "streaming_process_rss_mib": 2397.08984375, "streaming_system_ram_used_mib": 70030.01171875, "baseline_status": "ok", "baseline_vram_used_mib": 22183, "baseline_process_rss_mib": 1363.8671875, "baseline_system_ram_used_mib": 69993.91796875}
+{"context_capacity": 196608, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28755, "streaming_process_rss_mib": 2937.04296875, "streaming_system_ram_used_mib": 70057.3203125, "baseline_status": "ok", "baseline_vram_used_mib": 22969, "baseline_process_rss_mib": 1397.7890625, "baseline_system_ram_used_mib": 69996.40625}
+{"context_capacity": 262144, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28757, "streaming_process_rss_mib": 3477.140625, "streaming_system_ram_used_mib": 70030.25, "baseline_status": "ok", "baseline_vram_used_mib": 23775, "baseline_process_rss_mib": 1432.91796875, "baseline_system_ram_used_mib": 69971.6640625}
+{"context_capacity": 327680, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28754, "streaming_process_rss_mib": 4017.1328125, "streaming_system_ram_used_mib": 70071.421875, "baseline_status": "ok", "baseline_vram_used_mib": 24569, "baseline_process_rss_mib": 1468.1640625, "baseline_system_ram_used_mib": 70215.3359375}
+{"context_capacity": 393216, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28805, "streaming_process_rss_mib": 4557.12890625, "streaming_system_ram_used_mib": 70239.04296875, "baseline_status": "ok", "baseline_vram_used_mib": 25363, "baseline_process_rss_mib": 1502.86328125, "baseline_system_ram_used_mib": 70213.88671875}
diff --git a/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.csv b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.csv
new file mode 100644
index 000000000000..0270de8c93b8
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.csv
@@ -0,0 +1,7 @@
+context_capacity,prompt_tokens,decode_tokens,arena_mib,prefill_tps,decode_tps,prompt_ms,predicted_ms,wall_seconds,vram_before_mib,vram_after_mib,vram_free_after_mib,streaming_active,stream_first_active_tokens,stream_trace_samples,stream_max_active_pages,stream_min_resident_pages,stream_max_ring_slots,stream_repartitions
+8192,7936,256,8192,9673.955045852548,70.99570365062127,820.347,3605.852,4.4733945229963865,28391,28421,3707,,,,,,,
+32768,32512,256,8192,6007.041349219327,23.003279405020177,5412.315,11128.848,16.593292944991845,28391,28541,3587,,,,,,,
+57344,57088,256,8192,4025.605127682227,13.539448160652745,14181.222,18907.713,33.14405252000142,28415,28608,3520,,,,,,,
+81920,81664,256,8192,2923.461714604711,9.52405187691532,27934.007,26879.316,54.87488919998577,28409,28809,3320,,,,,,,
+106496,106240,256,8192,2501.8006418117106,7.522274453709509,42465.414,34032.26,76.5637429819908,28414,28805,3323,,,,,,,
+131072,130816,256,8192,2072.719569975335,6.030148812530611,63113.217,42453.347,105.63578185599181,28376,28877,3251,,,,,,,
diff --git a/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.jsonl b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.jsonl
new file mode 100644
index 000000000000..df814a65ff08
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/gemma4-it-throughput/results.jsonl
@@ -0,0 +1,7 @@
+{"arena_backoff_mib": 64, "arena_retries": 8, "arena_step_mib": 32, "baseline_vram_total_mib": 32607, "baseline_vram_used_mib": 1475, "batch_size": 256, "cache_type_k": "q8_0", "cache_type_v": "turbo4", "capacities": [8192, 32768, 57344, 81920, 106496, 131072], "context_step": 24576, "cuda_visible_devices": null, "decode_tokens": 256, "extra_server_args": [], "fill_token_id": null, "fixed_arena_mib": 8192, "flash_attention": true, "gpu_index": 0, "max_arena_mib": null, "max_context": 131072, "min_context": 8192, "model": "/mnt/storage/models/gemma/gemma-4-26B-A4B-it-UD-Q5_K_S.gguf", "parallel": 1, "probe_arena_mib": 1536, "probe_arena_step_mib": 256, "prompt_suffix": "The capital of France is", "revision": "928f09a0e675", "server": "/mnt/storage/Projects/llama-cpp-turboquant/build/bin/llama-server", "timestamp": "2026-09-06T00:20:47.300255+00:00", "trace_kv_stream": false, "type": "metadata", "ubatch_size": 256, "uvm": false}
+{"arena_mib": 8192, "context_capacity": 8192, "decode_tokens": 256, "decode_tps": 70.99570365062127, "fill_token_id": 818, "predicted_ms": 3605.852, "prefill_tps": 9673.955045852548, "prompt_ms": 820.347, "prompt_tokens": 7936, "status": "ok", "type": "measurement", "vram_after_mib": 28421, "vram_before_mib": 28391, "vram_free_after_mib": 3707, "wall_seconds": 4.4733945229963865}
+{"arena_mib": 8192, "context_capacity": 32768, "decode_tokens": 256, "decode_tps": 23.003279405020177, "fill_token_id": 818, "predicted_ms": 11128.848, "prefill_tps": 6007.041349219327, "prompt_ms": 5412.315, "prompt_tokens": 32512, "status": "ok", "type": "measurement", "vram_after_mib": 28541, "vram_before_mib": 28391, "vram_free_after_mib": 3587, "wall_seconds": 16.593292944991845}
+{"arena_mib": 8192, "context_capacity": 57344, "decode_tokens": 256, "decode_tps": 13.539448160652745, "fill_token_id": 818, "predicted_ms": 18907.713, "prefill_tps": 4025.605127682227, "prompt_ms": 14181.222, "prompt_tokens": 57088, "status": "ok", "type": "measurement", "vram_after_mib": 28608, "vram_before_mib": 28415, "vram_free_after_mib": 3520, "wall_seconds": 33.14405252000142}
+{"arena_mib": 8192, "context_capacity": 81920, "decode_tokens": 256, "decode_tps": 9.52405187691532, "fill_token_id": 818, "predicted_ms": 26879.316, "prefill_tps": 2923.461714604711, "prompt_ms": 27934.007, "prompt_tokens": 81664, "status": "ok", "type": "measurement", "vram_after_mib": 28809, "vram_before_mib": 28409, "vram_free_after_mib": 3320, "wall_seconds": 54.87488919998577}
+{"arena_mib": 8192, "context_capacity": 106496, "decode_tokens": 256, "decode_tps": 7.522274453709509, "fill_token_id": 818, "predicted_ms": 34032.26, "prefill_tps": 2501.8006418117106, "prompt_ms": 42465.414, "prompt_tokens": 106240, "status": "ok", "type": "measurement", "vram_after_mib": 28805, "vram_before_mib": 28414, "vram_free_after_mib": 3323, "wall_seconds": 76.5637429819908}
+{"arena_mib": 8192, "context_capacity": 131072, "decode_tokens": 256, "decode_tps": 6.030148812530611, "fill_token_id": 818, "predicted_ms": 42453.347, "prefill_tps": 2072.719569975335, "prompt_ms": 63113.217, "prompt_tokens": 130816, "status": "ok", "type": "measurement", "vram_after_mib": 28877, "vram_before_mib": 28376, "vram_free_after_mib": 3251, "wall_seconds": 105.63578185599181}
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-baseline.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-baseline.log
new file mode 100644
index 000000000000..0308d82513b2
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-baseline.log
@@ -0,0 +1,14 @@
+0.00.633.690 I operator(): MoE cache fit kept stock placement because the complete model already meets the fit targets
+0.00.899.654 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.899.939 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.916.197 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.02.029.143 I
+0.02.029.210 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.029.241 I perplexity: saving all logits to /tmp/kld-proof/gemma4-baseline.kld
+0.02.029.244 I perplexity: tokenizing the input ..
+0.02.552.745 I perplexity: tokenization took 523.494 ms
+0.02.552.909 I perplexity: calculating perplexity over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.04.777.875 I perplexity: 1.60 seconds per pass - ETA 0.10 minutes
+[1]8237.4411,[2]3971.7833,[3]1639.1072,[4]1253.0659,
+0.07.754.087 I Final estimate: PPL = 1253.0659 +/- 71.73626
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-baseline.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-baseline.log
new file mode 100644
index 000000000000..af93a9a27b9c
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-baseline.log
@@ -0,0 +1,15 @@
+0.00.644.915 I operator(): MoE cache fit kept stock placement because the complete model already meets the fit targets
+0.00.907.092 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.907.379 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.911.214 W load: control-looking token: 1 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.921.024 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.02.189.151 I
+0.02.189.220 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.189.251 I perplexity: saving all logits to /tmp/kld-proof/gemma4-it-baseline.kld
+0.02.189.254 I perplexity: tokenizing the input ..
+0.02.717.793 I perplexity: tokenization took 528.533 ms
+0.02.717.957 I perplexity: calculating perplexity over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.05.025.477 I perplexity: 1.65 seconds per pass - ETA 0.10 minutes
+[1]129129.9780,[2]62537.9270,[3]22206.4933,[4]16607.8189,
+0.07.964.561 I Final estimate: PPL = 16607.8189 +/- 1313.89296
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-coherence-check.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-coherence-check.log
new file mode 100644
index 000000000000..54db4e696452
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-coherence-check.log
@@ -0,0 +1,40 @@
+
+
+Loading model...
+
+▄▄ ▄▄
+██ ██
+██ ██ ▀▀█▄ ███▄███▄ ▀▀█▄ ▄████ ████▄ ████▄
+██ ██ ▄█▀██ ██ ██ ██ ▄█▀██ ██ ██ ██ ██ ██
+██ ██ ▀█▄██ ██ ██ ██ ▀█▄██ ██ ▀████ ████▀ ████▀
+ ██ ██
+ ▀▀ ▀▀
+
+build : b10727-179e89ff7
+model : /mnt/storage/models/gemma/gemma-4-26B-A4B-it-UD-Q5_K_S.gguf
+ftype : Q5_K - Small
+modalities : text
+
+available commands:
+ /exit or Ctrl+C stop or exit
+ /regen regenerate the last response
+ /clear clear the chat history
+ /read add a text file
+ /glob add text files using globbing pattern
+
+
+
+> The capital of France is
+
+[Start thinking]
+
+The user is asking for the capital of France.
+"The capital of France is" (incomplete sentence).
+The capital of France is Paris.
+Provide the direct answer.
+
+[ Prompt: 383.1 t/s | Generation: 206.0 t/s ]
+
+>
+
+Exiting...
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-f16-check.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-f16-check.log
new file mode 100644
index 000000000000..cf47bf795f3a
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-f16-check.log
@@ -0,0 +1,14 @@
+0.00.681.673 I operator(): MoE cache fit kept stock placement because the complete model already meets the fit targets
+0.00.933.940 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.934.234 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.937.787 W load: control-looking token: 1 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.948.798 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.02.186.939 I
+0.02.187.022 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.187.035 I perplexity: tokenizing the input ..
+0.02.711.003 I perplexity: tokenization took 523.961 ms
+0.02.711.170 I perplexity: calculating perplexity over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.04.362.118 I perplexity: 1.65 seconds per pass - ETA 0.10 minutes
+[1]176409.1934,[2]77181.6936,[3]36388.5652,[4]23022.0931,
+0.06.255.825 I Final estimate: PPL = 23022.0931 +/- 1834.55177
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-nofa-check.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-nofa-check.log
new file mode 100644
index 000000000000..f11ebb45a436
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-nofa-check.log
@@ -0,0 +1,16 @@
+0.00.616.429 I operator(): MoE cache fit kept stock placement because the complete model already meets the fit targets
+0.00.870.559 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.870.945 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.876.040 W load: control-looking token: 1 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.891.983 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.02.127.740 W llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 2048
+0.02.127.846 W llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 2048
+0.02.178.813 I
+0.02.178.880 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.178.890 I perplexity: tokenizing the input ..
+0.02.691.969 I perplexity: tokenization took 513.073 ms
+0.02.692.133 I perplexity: calculating perplexity over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.04.442.090 I perplexity: 1.75 seconds per pass - ETA 0.10 minutes
+[1]161913.6083,[2]74950.8550,[3]36198.2144,[4]22620.2548,
+0.06.493.504 I Final estimate: PPL = 22620.2548 +/- 1800.01391
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-streaming.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-streaming.log
new file mode 100644
index 000000000000..fc215298cb8a
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-it-streaming.log
@@ -0,0 +1,56 @@
+0.00.215.909 I cmn common_init_: skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured
+0.00.596.331 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.596.544 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.599.886 W load: control-looking token: 1 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.612.611 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.01.932.958 I
+0.01.933.022 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.261.528 I kl_divergence: computing over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.03.990.045 I kl_divergence: 1.73 seconds per pass - ETA 0.10 minutes
+
+chunk PPL ln(PPL(Q)/PPL(base)) KL Divergence Δp RMS Same top p
+ 1 129129.9780 ± 20256.8683 1.07483 ± 0.05555 0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 2 62537.9270 ± 6916.4539 0.91721 ± 0.03579 0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 3 22206.4933 ± 2028.3377 0.76508 ± 0.02660 -0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 4 16607.8189 ± 1313.8930 0.72205 ± 0.02232 -0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+
+====== Perplexity statistics ======
+Mean PPL(Q) : 16607.818945 ± 1313.892965
+Mean PPL(base) : 8067.358012 ± 539.738941
+Cor(ln(PPL(Q)), ln(PPL(base))): 96.70%
+Mean ln(PPL(Q)/PPL(base)) : 0.722048 ± 0.022322
+Mean PPL(Q)/PPL(base) : 2.058644 ± 0.045952
+Mean PPL(Q)-PPL(base) : 8540.460933 ± 803.803973
+
+====== KL divergence statistics ======
+Mean KLD: -0.000000 ± 0.000000
+Maximum KLD: 0.000056
+99.9% KLD: 0.000051
+99.0% KLD: 0.000038
+95.0% KLD: 0.000023
+90.0% KLD: 0.000015
+Median KLD: 0.000000
+10.0% KLD: -0.000015
+ 5.0% KLD: -0.000023
+ 1.0% KLD: -0.000037
+ 0.1% KLD: -0.000051
+Minimum KLD: -0.000058
+
+====== Token probability statistics ======
+Mean Δp: -0.000 ± 0.000 %
+Maximum Δp: 0.004%
+99.9% Δp: 0.004%
+99.0% Δp: 0.001%
+95.0% Δp: 0.000%
+90.0% Δp: 0.000%
+75.0% Δp: 0.000%
+Median Δp: -0.000%
+25.0% Δp: -0.000%
+10.0% Δp: -0.000%
+ 5.0% Δp: -0.000%
+ 1.0% Δp: -0.001%
+ 0.1% Δp: -0.004%
+Minimum Δp: -0.005%
+RMS Δp : 0.000 ± 0.000 %
+Same top p: 100.000 ± 0.000 %
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-streaming.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-streaming.log
new file mode 100644
index 000000000000..95005135a46f
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/gemma4-streaming.log
@@ -0,0 +1,55 @@
+0.00.154.151 I cmn common_init_: skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured
+0.00.551.356 W load: control-looking token: 212 '' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.551.547 W load: control-looking token: 50 '<|tool_response>' was not control-type; this is probably a bug in the model. its type will be overridden
+0.00.564.755 W load: special_eog_ids contains '<|tool_response>', removing '' token from EOG list
+0.01.717.959 I
+0.01.718.026 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.025.535 I kl_divergence: computing over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.03.700.024 I kl_divergence: 1.67 seconds per pass - ETA 0.10 minutes
+
+chunk PPL ln(PPL(Q)/PPL(base)) KL Divergence Δp RMS Same top p
+ 1 8237.4411 ± 895.1032 0.12603 ± 0.01575 0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 2 3971.7833 ± 317.7633 0.11756 ± 0.01098 -0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 3 1639.1072 ± 109.2131 0.09395 ± 0.00788 -0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+ 4 1253.0659 ± 71.7363 0.08178 ± 0.00635 0.00000 ± 0.00000 0.000 ± 0.000 % 100.000 ± 0.000 %
+
+====== Perplexity statistics ======
+Mean PPL(Q) : 1253.065927 ± 71.736255
+Mean PPL(base) : 1154.667384 ± 63.695557
+Cor(ln(PPL(Q)), ln(PPL(base))): 99.43%
+Mean ln(PPL(Q)/PPL(base)) : 0.081781 ± 0.006346
+Mean PPL(Q)/PPL(base) : 1.085218 ± 0.006886
+Mean PPL(Q)-PPL(base) : 98.398543 ± 10.799321
+
+====== KL divergence statistics ======
+Mean KLD: 0.000000 ± 0.000000
+Maximum KLD: 0.000051
+99.9% KLD: 0.000047
+99.0% KLD: 0.000032
+95.0% KLD: 0.000020
+90.0% KLD: 0.000014
+Median KLD: 0.000000
+10.0% KLD: -0.000014
+ 5.0% KLD: -0.000020
+ 1.0% KLD: -0.000032
+ 0.1% KLD: -0.000043
+Minimum KLD: -0.000057
+
+====== Token probability statistics ======
+Mean Δp: -0.000 ± 0.000 %
+Maximum Δp: 0.004%
+99.9% Δp: 0.003%
+99.0% Δp: 0.001%
+95.0% Δp: 0.000%
+90.0% Δp: 0.000%
+75.0% Δp: 0.000%
+Median Δp: 0.000%
+25.0% Δp: -0.000%
+10.0% Δp: -0.000%
+ 5.0% Δp: -0.000%
+ 1.0% Δp: -0.001%
+ 0.1% Δp: -0.003%
+Minimum Δp: -0.005%
+RMS Δp : 0.000 ± 0.000 %
+Same top p: 100.000 ± 0.000 %
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-131k.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-131k.log
new file mode 100644
index 000000000000..ce5f2977dbe8
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-131k.log
@@ -0,0 +1,25 @@
+0.00.788.308 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.788.312 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.788.315 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.788.317 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.788.318 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.788.322 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.788.323 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.788.325 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.788.326 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.788.327 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.788.329 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.788.331 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.788.332 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.788.333 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.788.337 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.02.257.725 I
+0.02.257.796 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.257.830 I perplexity: saving all logits to /tmp/kld-proof/qwen-baseline-131k.kld
+0.02.257.834 I perplexity: tokenizing the input ..
+0.02.535.304 I perplexity: tokenization took 277.465 ms
+0.02.535.501 I perplexity: calculating perplexity over 2 chunks, n_ctx=131072, batch_size=2048, n_seq=1
+2.04.456.350 I perplexity: 102.30 seconds per pass - ETA 3.40 minutes
+[1]5.2341,[2]5.5263,
+3.41.024.437 I Final estimate: PPL = 5.5263 +/- 0.03519
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-32k.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-32k.log
new file mode 100644
index 000000000000..be3008dab6b8
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline-32k.log
@@ -0,0 +1,27 @@
+1871 MiB
+0.30 minutes
+[1]6.0124,
+
+
+0.00.718.616 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.718.621 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.718.625 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.718.627 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.718.628 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.718.632 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.718.634 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.718.635 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.718.636 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.718.637 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.718.639 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.718.641 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.718.643 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.718.644 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.718.648 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.02.116.064 I
+0.02.116.138 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.116.169 I perplexity: saving all logits to /tmp/kld-proof/qwen-baseline-32k.kld
+0.02.116.173 I perplexity: tokenizing the input ..
+0.02.394.056 I perplexity: tokenization took 277.876 ms
+0.02.394.251 I perplexity: calculating perplexity over 1 chunks, n_ctx=32768, batch_size=2048, n_seq=1
+0.25.982.570 I perplexity: 18.40 seconds per pass - ETA 0.28.307.926 I Final estimate: PPL = 6.0124 +/- 0.10811
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline.log
new file mode 100644
index 000000000000..e212b791a123
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-baseline.log
@@ -0,0 +1,25 @@
+0.00.706.162 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.706.167 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.706.171 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.706.172 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.706.173 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.706.177 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.706.178 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.706.180 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.706.181 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.706.182 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.706.183 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.706.185 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.706.186 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.706.188 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.706.191 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.02.076.565 I
+0.02.076.625 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.076.653 I perplexity: saving all logits to /tmp/kld-proof/qwen-baseline.kld
+0.02.076.657 I perplexity: tokenizing the input ..
+0.02.342.236 I perplexity: tokenization took 265.573 ms
+0.02.342.434 I perplexity: calculating perplexity over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.05.268.597 I perplexity: 2.34 seconds per pass - ETA 0.15 minutes
+[1]6.8976,[2]6.7252,[3]5.3702,[4]5.7275,
+0.10.743.761 I Final estimate: PPL = 5.7275 +/- 0.15949
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-131k-FAILED-tooling-limitation.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-131k-FAILED-tooling-limitation.log
new file mode 100644
index 000000000000..53aff06a3c36
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-131k-FAILED-tooling-limitation.log
@@ -0,0 +1,27 @@
+1903 MiB
+3.58 minutes
+
+chunk PPL ln(PPL(Q)/PPL(base)) KL Divergence Δp RMS Same top p
+
+
+0.00.165.585 I cmn common_init_: skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured
+0.00.498.758 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.498.764 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.498.768 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.498.769 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.498.770 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.498.775 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.498.776 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.498.777 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.498.779 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.498.780 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.498.781 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.498.784 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.498.785 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.498.786 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.498.790 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.02.492.758 I
+0.02.492.828 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.12.591.777 I kl_divergence: computing over 2 chunks, n_ctx=131072, batch_size=2048, n_seq=1
+0.20.495.143 I kl_divergence: 107.90 seconds per pass - ETA
+2.04.407.567 E kl_divergence: failed reading log-probs for chunk 0
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-32k.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-32k.log
new file mode 100644
index 000000000000..c97bd40a8db3
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming-32k.log
@@ -0,0 +1,67 @@
+1932 MiB
+0.30 minutes
+
+chunk PPL ln(PPL(Q)/PPL(base)) KL Divergence Δp RMS Same top p
+ 1 6.0124 ± 0.1081 0.00026 ± 0.00022 0.00000 ± 0.00000 0.001 ± 0.000 % 99.988 ± 0.009 %
+
+====== Perplexity statistics ======
+Mean PPL(Q) : 6.012388 ± 0.108106
+Mean PPL(base) : 6.010830 ± 0.107994
+Cor(ln(PPL(Q)), ln(PPL(base))): 99.99%
+Mean ln(PPL(Q)/PPL(base)) : 0.000259 ± 0.000219
+Mean PPL(Q)/PPL(base) : 1.000259 ± 0.000219
+Mean PPL(Q)-PPL(base) : 0.001558 ± 0.001316
+
+====== KL divergence statistics ======
+Mean KLD: 0.000000 ± 0.000000
+Maximum KLD: 0.000070
+99.9% KLD: 0.000050
+99.0% KLD: 0.000038
+95.0% KLD: 0.000024
+90.0% KLD: 0.000016
+Median KLD: 0.000000
+10.0% KLD: -0.000016
+ 5.0% KLD: -0.000024
+ 1.0% KLD: -0.000037
+ 0.1% KLD: -0.000053
+Minimum KLD: -0.000070
+
+====== Token probability statistics ======
+Mean Δp: -0.000 ± 0.000 %
+Maximum Δp: 0.006%
+99.9% Δp: 0.004%
+99.0% Δp: 0.002%
+95.0% Δp: 0.001%
+90.0% Δp: 0.000%
+75.0% Δp: 0.000%
+Median Δp: 0.000%
+25.0% Δp: 0.000%
+10.0% Δp: -0.000%
+ 5.0% Δp: -0.001%
+ 1.0% Δp: -0.002%
+ 0.1% Δp: -0.004%
+Minimum Δp: -0.005%
+RMS Δp : 0.001 ± 0.000 %
+Same top p: 99.988 ± 0.009 %
+
+
+0.00.174.864 I cmn common_init_: skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured
+0.00.480.972 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.480.976 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.480.980 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.480.981 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.480.982 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.480.987 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.480.988 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.480.989 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.480.990 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.480.992 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.480.993 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.480.996 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.480.997 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.480.998 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.481.002 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.02.086.393 I
+0.02.086.459 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.04.776.035 I kl_divergence: computing over 1 chunks, n_ctx=32768, batch_size=2048, n_seq=1
+0.23.567.549 I kl_divergence: 18.79 seconds per pass - ETA
diff --git a/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming.log b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming.log
new file mode 100644
index 000000000000..3a5963605254
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/kld-logs/qwen-streaming.log
@@ -0,0 +1,67 @@
+0.00.173.065 I cmn common_init_: skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured
+0.00.474.434 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.474.439 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.474.442 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.474.444 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.474.445 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.474.449 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.474.450 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.474.452 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.474.453 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.474.454 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.474.455 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.474.458 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.474.459 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.474.461 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.474.464 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.01.860.686 I
+0.01.860.754 I system_info: n_threads = 4 (n_threads_batch = 4) / 24 | CUDA : ARCHS = 1200 | USE_GRAPHS = 1 | FA_ALL_QUANTS = 1 | BLACKWELL_NATIVE_FP4 = 1 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | OPENMP = 1 | REPACK = 1 |
+0.02.156.001 I kl_divergence: computing over 4 chunks, n_ctx=4096, batch_size=2048, n_seq=1
+0.04.550.034 I kl_divergence: 2.39 seconds per pass - ETA 0.15 minutes
+
+chunk PPL ln(PPL(Q)/PPL(base)) KL Divergence Δp RMS Same top p
+ 1 6.8976 ± 0.3621 0.00000 ± -nan 0.00000 ± 0.00000 0.001 ± 0.000 % 100.000 ± 0.000 %
+ 2 6.7252 ± 0.2557 0.00000 ± 0.00000 0.00000 ± 0.00000 0.001 ± 0.000 % 100.000 ± 0.000 %
+ 3 5.3702 ± 0.1593 0.00027 ± 0.00027 -0.00000 ± 0.00000 0.001 ± 0.000 % 100.000 ± 0.000 %
+ 4 5.7275 ± 0.1595 0.00252 ± 0.00086 -0.00000 ± 0.00000 0.001 ± 0.000 % 100.000 ± 0.000 %
+
+====== Perplexity statistics ======
+Mean PPL(Q) : 5.727497 ± 0.159493
+Mean PPL(base) : 5.713077 ± 0.158086
+Cor(ln(PPL(Q)), ln(PPL(base))): 99.95%
+Mean ln(PPL(Q)/PPL(base)) : 0.002521 ± 0.000858
+Mean PPL(Q)/PPL(base) : 1.002524 ± 0.000860
+Mean PPL(Q)-PPL(base) : 0.014420 ± 0.005007
+
+====== KL divergence statistics ======
+Mean KLD: -0.000000 ± 0.000000
+Maximum KLD: 0.000057
+99.9% KLD: 0.000050
+99.0% KLD: 0.000037
+95.0% KLD: 0.000023
+90.0% KLD: 0.000015
+Median KLD: -0.000000
+10.0% KLD: -0.000016
+ 5.0% KLD: -0.000023
+ 1.0% KLD: -0.000037
+ 0.1% KLD: -0.000052
+Minimum KLD: -0.000059
+
+====== Token probability statistics ======
+Mean Δp: 0.000 ± 0.000 %
+Maximum Δp: 0.005%
+99.9% Δp: 0.004%
+99.0% Δp: 0.002%
+95.0% Δp: 0.001%
+90.0% Δp: 0.000%
+75.0% Δp: 0.000%
+Median Δp: 0.000%
+25.0% Δp: 0.000%
+10.0% Δp: -0.000%
+ 5.0% Δp: -0.001%
+ 1.0% Δp: -0.002%
+ 0.1% Δp: -0.004%
+Minimum Δp: -0.006%
+RMS Δp : 0.001 ± 0.000 %
+Same top p: 100.000 ± 0.000 %
+
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/logs/baseline-393216.log b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/logs/baseline-393216.log
new file mode 100644
index 000000000000..3804abc55359
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/logs/baseline-393216.log
@@ -0,0 +1,99 @@
+0.00.076.697 I cmn common_param: common_params_print_info: verbosity = 3 (adjust with the `-lv N` CLI arg)
+0.00.169.000 W srv llama_server: -----------------
+0.00.169.002 W srv llama_server: CORS is set to allow all origins ('*') and no API key is set
+0.00.169.002 W srv llama_server: this can be a security risk (cross-origin attacks)
+0.00.169.002 W srv llama_server: more info: https://github.com/ggml-org/llama.cpp/pull/25655
+0.00.169.002 W srv llama_server: -----------------
+0.00.170.264 I srv load_model: loading model '/mnt/storage/models/qwen3.8/Qwen3.8-27B-AD-Q5_K_M.gguf'
+0.00.406.541 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
+0.00.406.545 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
+0.00.406.549 W model has unused tensor blk.64.attn_q.weight (size = 43253760 bytes) -- ignoring
+0.00.406.550 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
+0.00.406.551 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
+0.00.406.556 W model has unused tensor blk.64.attn_output.weight (size = 25804800 bytes) -- ignoring
+0.00.406.557 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
+0.00.406.558 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
+0.00.406.559 W model has unused tensor blk.64.ffn_gate.weight (size = 61276160 bytes) -- ignoring
+0.00.406.561 W model has unused tensor blk.64.ffn_down.weight (size = 61276160 bytes) -- ignoring
+0.00.406.562 W model has unused tensor blk.64.ffn_up.weight (size = 61276160 bytes) -- ignoring
+0.00.406.564 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
+0.00.406.566 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
+0.00.406.567 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
+0.00.406.570 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
+0.01.778.967 W llama_context: n_ctx_seq (393216) > n_ctx_train (262144) -- possible training context overflow
+0.01.850.066 W srv load_model: the slot context (393216) exceeds the training context of the model (262144) - using rope scaling to extend
+/mnt/storage/Projects/llama-cpp-turboquant/ggml/src/ggml-cuda/ggml-cuda.cu:114: CUDA error
+0.01.863.344 E CUDA error: out of memory
+0.01.863.347 E current device: 0, in function ggml_cuda_mul_mat_vec_q at /mnt/storage/Projects/llama-cpp-turboquant/ggml/src/ggml-cuda/mmvq.cu:1305
+0.01.863.347 E ggml_cuda_device_malloc((void **) &qc.ptr, q8_bytes, ctx.device)
+⚠️ warning: The current terminal doesn't support styling. Styled output might not appear as expected.
+[New LWP 1400401]
+[New LWP 1400400]
+[New LWP 1400399]
+[New LWP 1400398]
+[New LWP 1400397]
+[New LWP 1400396]
+[New LWP 1400395]
+[New LWP 1400394]
+[New LWP 1400393]
+[New LWP 1400392]
+[New LWP 1400391]
+[New LWP 1400390]
+[New LWP 1400389]
+[New LWP 1400388]
+[New LWP 1400387]
+[New LWP 1400386]
+[New LWP 1400385]
+[New LWP 1400384]
+[New LWP 1400383]
+[New LWP 1400382]
+[New LWP 1400381]
+[New LWP 1400380]
+[New LWP 1400379]
+[New LWP 1400378]
+[New LWP 1400377]
+[New LWP 1400374]
+[New LWP 1400373]
+[New LWP 1400369]
+[New LWP 1400368]
+[New LWP 1400367]
+
+This GDB supports auto-downloading debuginfo from the following URLs:
+
+Enable debuginfod for this session? (y or [n]) [answered N; input not from terminal]
+Debuginfod has been disabled.
+To make this setting permanent, add 'set debuginfod enabled off' to .gdbinit.
+[Thread debugging using libthread_db enabled]
+Using host libthread_db library "/usr/lib/x86_64-linux-gnu/libthread_db.so.1".
+__syscall_cancel_arch () at ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S:56
+⚠️ warning: 56 ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S: No such file or directory
+#0 __syscall_cancel_arch () at ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S:56
+56 in ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S
+#1 0x00007ca873ca061c in __internal_syscall_cancel (a1=, a2=, a3=, a4=, a5=0, a6=0, nr=61) at ./nptl/cancellation.c:49
+⚠️ warning: 49 ./nptl/cancellation.c: No such file or directory
+#2 __syscall_cancel (a1=, a2=, a3=, a4=, a5=a5@entry=0, a6=a6@entry=0, nr=61) at ./nptl/cancellation.c:75
+75 in ./nptl/cancellation.c
+#3 0x00007ca873d1cd4f in __GI___wait4 (pid=, stat_loc=, options=, usage=) at ../sysdeps/unix/sysv/linux/wait4.c:30
+⚠️ warning: 30 ../sysdeps/unix/sysv/linux/wait4.c: No such file or directory
+#4 0x00007ca8743150f3 in ggml_print_backtrace () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#5 0x00007ca8743152a6 in ggml_abort () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#6 0x00007ca863130c25 in ggml_cuda_error(char const*, char const*, char const*, int, char const*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#7 0x00007ca8632d5c6e in ggml_cuda_mul_mat_vec_q(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor const*, ggml_tensor*, ggml_cuda_mm_fusion_args_host const*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#8 0x00007ca8631400d0 in ggml_cuda_mul_mat(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#9 0x00007ca86314a2f2 in ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context*, ggml_cgraph*, bool, bool, unsigned long) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#10 0x00007ca86314c16f in ggml_backend_cuda_graph_compute(ggml_backend*, ggml_cgraph*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#11 0x00007ca8743362ff in ggml_backend_sched_compute_splits(ggml_backend_sched*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#12 0x00007ca8730fbd90 in llama_context::graph_compute(ggml_cgraph*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#13 0x00007ca873103e78 in llama_context::process_ubatch(llama_ubatch const&, llm_graph_type, llama_memory_context_i*, ggml_status&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#14 0x00007ca873109878 in llama_context::decode(llama_batch const&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#15 0x00007ca87310b652 in llama_decode () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#16 0x00007ca87384db27 in common_context_can_seq_rm(llama_context*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-common.so.0
+#17 0x00007ca8745e4dca in server_context_impl::load_model(common_params&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#18 0x00007ca874504385 in llama_server(common_params&, int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#19 0x00007ca87450689b in llama_server(int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#20 0x00007ca873c2a601 in __libc_start_call_main (main=main@entry=0x589b44c242f0 , argc=argc@entry=39, argv=argv@entry=0x7ffe14089a18) at ../sysdeps/nptl/libc_start_call_main.h:59
+⚠️ warning: 59 ../sysdeps/nptl/libc_start_call_main.h: No such file or directory
+#21 0x00007ca873c2a718 in __libc_start_main_impl (main=0x589b44c242f0 , argc=39, argv=0x7ffe14089a18, init=, fini=, rtld_fini=, stack_end=0x7ffe14089a08) at ../csu/libc-start.c:360
+⚠️ warning: 360 ../csu/libc-start.c: No such file or directory
+#22 0x0000589b44c24325 in _start ()
+[Inferior 1 (process 1400365) detached]
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.csv b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.csv
new file mode 100644
index 000000000000..eb4d89d1a62d
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.csv
@@ -0,0 +1,36 @@
+context_capacity,arena_mib,streaming_status,streaming_vram_used_mib,streaming_process_rss_mib,streaming_system_ram_used_mib,baseline_status,baseline_vram_used_mib,baseline_process_rss_mib,baseline_system_ram_used_mib,baseline_error
+131072,8192,ok,28969,4536.75,67244.12890625,ok,24693,1261.2421875,67314.92578125,
+262144,8192,ok,29001,7838.8984375,67331.44921875,ok,28408,1331.30078125,67195.4765625,
+393216,8192,ok,28923,11140.91796875,69211.67578125,failed,,,,"server exited with status -6: #0 __syscall_cancel_arch () at ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S:56
+56 in ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S
+#1 0x00007ca873ca061c in __internal_syscall_cancel (a1=, a2=, a3=, a4=, a5=0, a6=0, nr=61) at ./nptl/cancellation.c:49
+⚠️ warning: 49 ./nptl/cancellation.c: No such file or directory
+#2 __syscall_cancel (a1=, a2=, a3=, a4=, a5=a5@entry=0, a6=a6@entry=0, nr=61) at ./nptl/cancellation.c:75
+75 in ./nptl/cancellation.c
+#3 0x00007ca873d1cd4f in __GI___wait4 (pid=, stat_loc=, options=, usage=) at ../sysdeps/unix/sysv/linux/wait4.c:30
+⚠️ warning: 30 ../sysdeps/unix/sysv/linux/wait4.c: No such file or directory
+#4 0x00007ca8743150f3 in ggml_print_backtrace () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#5 0x00007ca8743152a6 in ggml_abort () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#6 0x00007ca863130c25 in ggml_cuda_error(char const*, char const*, char const*, int, char const*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#7 0x00007ca8632d5c6e in ggml_cuda_mul_mat_vec_q(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor const*, ggml_tensor*, ggml_cuda_mm_fusion_args_host const*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#8 0x00007ca8631400d0 in ggml_cuda_mul_mat(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#9 0x00007ca86314a2f2 in ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context*, ggml_cgraph*, bool, bool, unsigned long) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#10 0x00007ca86314c16f in ggml_backend_cuda_graph_compute(ggml_backend*, ggml_cgraph*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0
+#11 0x00007ca8743362ff in ggml_backend_sched_compute_splits(ggml_backend_sched*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0
+#12 0x00007ca8730fbd90 in llama_context::graph_compute(ggml_cgraph*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#13 0x00007ca873103e78 in llama_context::process_ubatch(llama_ubatch const&, llm_graph_type, llama_memory_context_i*, ggml_status&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#14 0x00007ca873109878 in llama_context::decode(llama_batch const&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#15 0x00007ca87310b652 in llama_decode () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0
+#16 0x00007ca87384db27 in common_context_can_seq_rm(llama_context*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-common.so.0
+#17 0x00007ca8745e4dca in server_context_impl::load_model(common_params&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#18 0x00007ca874504385 in llama_server(common_params&, int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#19 0x00007ca87450689b in llama_server(int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so
+#20 0x00007ca873c2a601 in __libc_start_call_main (main=main@entry=0x589b44c242f0 , argc=argc@entry=39, argv=argv@entry=0x7ffe14089a18) at ../sysdeps/nptl/libc_start_call_main.h:59
+⚠️ warning: 59 ../sysdeps/nptl/libc_start_call_main.h: No such file or directory
+#21 0x00007ca873c2a718 in __libc_start_main_impl (main=0x589b44c242f0 , argc=39, argv=0x7ffe14089a18, init=, fini=, rtld_fini=, stack_end=0x7ffe14089a08) at ../csu/libc-start.c:360
+⚠️ warning: 360 ../csu/libc-start.c: No such file or directory
+#22 0x0000589b44c24325 in _start ()
+[Inferior 1 (process 1400365) detached]"
+524288,8192,ok,28923,14443.046875,72585.37109375,,,,,
+655360,8192,ok,28994,17745.04296875,75746.796875,,,,,
+786432,8192,ok,28859,21047.0390625,79153.69921875,,,,,
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.jsonl b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.jsonl
new file mode 100644
index 000000000000..bbe747816ce2
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-memory/results.jsonl
@@ -0,0 +1,6 @@
+{"context_capacity": 131072, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28969, "streaming_process_rss_mib": 4536.75, "streaming_system_ram_used_mib": 67244.12890625, "baseline_status": "ok", "baseline_vram_used_mib": 24693, "baseline_process_rss_mib": 1261.2421875, "baseline_system_ram_used_mib": 67314.92578125}
+{"context_capacity": 262144, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 29001, "streaming_process_rss_mib": 7838.8984375, "streaming_system_ram_used_mib": 67331.44921875, "baseline_status": "ok", "baseline_vram_used_mib": 28408, "baseline_process_rss_mib": 1331.30078125, "baseline_system_ram_used_mib": 67195.4765625}
+{"context_capacity": 393216, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28923, "streaming_process_rss_mib": 11140.91796875, "streaming_system_ram_used_mib": 69211.67578125, "baseline_status": "failed", "baseline_error": "server exited with status -6: #0 __syscall_cancel_arch () at ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S:56\n56\tin ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S\n#1 0x00007ca873ca061c in __internal_syscall_cancel (a1=, a2=, a3=, a4=, a5=0, a6=0, nr=61) at ./nptl/cancellation.c:49\n\u26a0\ufe0f warning: 49\t./nptl/cancellation.c: No such file or directory\n#2 __syscall_cancel (a1=, a2=, a3=, a4=, a5=a5@entry=0, a6=a6@entry=0, nr=61) at ./nptl/cancellation.c:75\n75\tin ./nptl/cancellation.c\n#3 0x00007ca873d1cd4f in __GI___wait4 (pid=, stat_loc=, options=, usage=) at ../sysdeps/unix/sysv/linux/wait4.c:30\n\u26a0\ufe0f warning: 30\t../sysdeps/unix/sysv/linux/wait4.c: No such file or directory\n#4 0x00007ca8743150f3 in ggml_print_backtrace () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0\n#5 0x00007ca8743152a6 in ggml_abort () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0\n#6 0x00007ca863130c25 in ggml_cuda_error(char const*, char const*, char const*, int, char const*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0\n#7 0x00007ca8632d5c6e in ggml_cuda_mul_mat_vec_q(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor const*, ggml_tensor*, ggml_cuda_mm_fusion_args_host const*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0\n#8 0x00007ca8631400d0 in ggml_cuda_mul_mat(ggml_backend_cuda_context&, ggml_tensor const*, ggml_tensor const*, ggml_tensor*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0\n#9 0x00007ca86314a2f2 in ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context*, ggml_cgraph*, bool, bool, unsigned long) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0\n#10 0x00007ca86314c16f in ggml_backend_cuda_graph_compute(ggml_backend*, ggml_cgraph*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-cuda.so.0\n#11 0x00007ca8743362ff in ggml_backend_sched_compute_splits(ggml_backend_sched*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libggml-base.so.0\n#12 0x00007ca8730fbd90 in llama_context::graph_compute(ggml_cgraph*, bool) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0\n#13 0x00007ca873103e78 in llama_context::process_ubatch(llama_ubatch const&, llm_graph_type, llama_memory_context_i*, ggml_status&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0\n#14 0x00007ca873109878 in llama_context::decode(llama_batch const&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0\n#15 0x00007ca87310b652 in llama_decode () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama.so.0\n#16 0x00007ca87384db27 in common_context_can_seq_rm(llama_context*) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-common.so.0\n#17 0x00007ca8745e4dca in server_context_impl::load_model(common_params&) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so\n#18 0x00007ca874504385 in llama_server(common_params&, int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so\n#19 0x00007ca87450689b in llama_server(int, char**) () from /mnt/storage/Projects/llama-cpp-turboquant/build/bin/libllama-server-impl.so\n#20 0x00007ca873c2a601 in __libc_start_call_main (main=main@entry=0x589b44c242f0 , argc=argc@entry=39, argv=argv@entry=0x7ffe14089a18) at ../sysdeps/nptl/libc_start_call_main.h:59\n\u26a0\ufe0f warning: 59\t../sysdeps/nptl/libc_start_call_main.h: No such file or directory\n#21 0x00007ca873c2a718 in __libc_start_main_impl (main=0x589b44c242f0 , argc=39, argv=0x7ffe14089a18, init=, fini=, rtld_fini=, stack_end=0x7ffe14089a08) at ../csu/libc-start.c:360\n\u26a0\ufe0f warning: 360\t../csu/libc-start.c: No such file or directory\n#22 0x0000589b44c24325 in _start ()\n[Inferior 1 (process 1400365) detached]"}
+{"context_capacity": 524288, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28923, "streaming_process_rss_mib": 14443.046875, "streaming_system_ram_used_mib": 72585.37109375}
+{"context_capacity": 655360, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28994, "streaming_process_rss_mib": 17745.04296875, "streaming_system_ram_used_mib": 75746.796875}
+{"context_capacity": 786432, "arena_mib": 8192, "streaming_status": "ok", "streaming_vram_used_mib": 28859, "streaming_process_rss_mib": 21047.0390625, "streaming_system_ram_used_mib": 79153.69921875}
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.csv b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.csv
new file mode 100644
index 000000000000..896c5f9d5965
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.csv
@@ -0,0 +1,6 @@
+context_capacity,prompt_tokens,decode_tokens,arena_mib,prefill_tps,decode_tps,prompt_ms,predicted_ms,wall_seconds,vram_before_mib,vram_after_mib,vram_free_after_mib,streaming_active,stream_first_active_tokens,stream_trace_samples,stream_max_active_pages,stream_min_resident_pages,stream_max_ring_slots,stream_repartitions
+8192,7936,256,8192,2595.072827828232,294.4838764280729,3058.103,862.526,4.074044303008122,29302,29332,2797,,,,,,,
+32768,32512,256,8192,2422.260177653771,260.71256644834557,13422.175,974.253,14.550552501008497,29403,29525,2603,,,,,,,
+57344,57088,256,8192,2094.0615410822757,227.46955196720052,27261.854,1094.652,28.514191365989973,29507,29731,2397,,,,,,,
+81920,81664,256,8192,1786.1198861672272,213.91599333660102,45721.455,1187.382,47.07472077899729,29603,29922,2206,,,,,,,
+106496,106240,256,8192,1567.6110313189618,191.63852447389945,67771.914,1325.412,69.26823750100448,29716,30208,1921,,,,,,,
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.jsonl b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.jsonl
new file mode 100644
index 000000000000..47fcde305d73
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-mtp-throughput/results.jsonl
@@ -0,0 +1,7 @@
+{"arena_backoff_mib": 64, "arena_retries": 8, "arena_step_mib": 32, "baseline_vram_total_mib": 32607, "baseline_vram_used_mib": 1413, "batch_size": 256, "cache_type_k": "q8_0", "cache_type_v": "turbo4", "capacities": [8192, 32768, 57344, 81920, 106496, 131072], "context_step": 24576, "cuda_visible_devices": null, "decode_tokens": 256, "extra_server_args": ["--spec-type", "draft-mtp", "--spec-chain", "8", "--spec-draft-p-min", "0", "--gdn-replay"], "fill_token_id": null, "fixed_arena_mib": 8192, "flash_attention": true, "gpu_index": 0, "max_arena_mib": null, "max_context": 131072, "min_context": 8192, "model": "/mnt/storage/models/qwen3.8/Qwen3.8-27B-AD-Q5_K_M.gguf", "parallel": 1, "probe_arena_mib": 1536, "probe_arena_step_mib": 256, "prompt_suffix": "The capital of France is", "revision": "d1783633ad54", "server": "/mnt/storage/Projects/llama-cpp-turboquant/build/bin/llama-server", "timestamp": "2026-09-05T23:44:57.389954+00:00", "trace_kv_stream": false, "type": "metadata", "ubatch_size": 256, "uvm": false}
+{"arena_mib": 8192, "context_capacity": 8192, "decode_tokens": 256, "decode_tps": 294.4838764280729, "fill_token_id": 760, "predicted_ms": 862.526, "prefill_tps": 2595.072827828232, "prompt_ms": 3058.103, "prompt_tokens": 7936, "status": "ok", "type": "measurement", "vram_after_mib": 29332, "vram_before_mib": 29302, "vram_free_after_mib": 2797, "wall_seconds": 4.074044303008122}
+{"arena_mib": 8192, "context_capacity": 32768, "decode_tokens": 256, "decode_tps": 260.71256644834557, "fill_token_id": 760, "predicted_ms": 974.253, "prefill_tps": 2422.260177653771, "prompt_ms": 13422.175, "prompt_tokens": 32512, "status": "ok", "type": "measurement", "vram_after_mib": 29525, "vram_before_mib": 29403, "vram_free_after_mib": 2603, "wall_seconds": 14.550552501008497}
+{"arena_mib": 8192, "context_capacity": 57344, "decode_tokens": 256, "decode_tps": 227.46955196720052, "fill_token_id": 760, "predicted_ms": 1094.652, "prefill_tps": 2094.0615410822757, "prompt_ms": 27261.854, "prompt_tokens": 57088, "status": "ok", "type": "measurement", "vram_after_mib": 29731, "vram_before_mib": 29507, "vram_free_after_mib": 2397, "wall_seconds": 28.514191365989973}
+{"arena_mib": 8192, "context_capacity": 81920, "decode_tokens": 256, "decode_tps": 213.91599333660102, "fill_token_id": 760, "predicted_ms": 1187.382, "prefill_tps": 1786.1198861672272, "prompt_ms": 45721.455, "prompt_tokens": 81664, "status": "ok", "type": "measurement", "vram_after_mib": 29922, "vram_before_mib": 29603, "vram_free_after_mib": 2206, "wall_seconds": 47.07472077899729}
+{"arena_mib": 8192, "context_capacity": 106496, "decode_tokens": 256, "decode_tps": 191.63852447389945, "fill_token_id": 760, "predicted_ms": 1325.412, "prefill_tps": 1567.6110313189618, "prompt_ms": 67771.914, "prompt_tokens": 106240, "status": "ok", "type": "measurement", "vram_after_mib": 30208, "vram_before_mib": 29716, "vram_free_after_mib": 1921, "wall_seconds": 69.26823750100448}
+{"context_capacity": 131072, "error": "GPU memory did not return to baseline: 1573 MiB used, baseline 1413 MiB", "status": "failed", "type": "point_failure"}
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.csv b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.csv
new file mode 100644
index 000000000000..327c85e312dc
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.csv
@@ -0,0 +1,18 @@
+context_capacity,prompt_tokens,decode_tokens,arena_mib,prefill_tps,decode_tps,prompt_ms,predicted_ms,wall_seconds,vram_before_mib,vram_after_mib,vram_free_after_mib,streaming_active,stream_first_active_tokens,stream_trace_samples,stream_max_active_pages,stream_min_resident_pages,stream_max_ring_slots,stream_repartitions
+8192,7936,256,8192,2759.0148620370887,59.46466010604221,2876.389,4305.078,7.3351924840098945,28813,28824,3304,,,,,,,
+24576,24320,256,8192,2604.7710795008907,52.56594716342034,9336.713,4870.073,14.363954145010212,28794,28888,3240,,,,,,,
+40960,40704,256,8192,2396.4251440951884,47.311776289222806,16985.3,5410.915,22.551607003988465,28796,28954,3174,,,,,,,
+57344,57088,256,8192,2155.9608514549845,42.82034173643511,26479.145,5978.467,32.61641234300623,28796,29012,3116,,,,,,,
+73728,73472,256,8192,1942.911530356988,39.58309721345819,37815.412,6467.407,44.447617318000994,28792,29081,3047,,,,,,,
+90112,89856,256,8192,1773.4569063747938,36.4232172969306,50667.146,7028.484,57.85852407698985,28795,29141,2987,,,,,,,
+106496,106240,256,8192,1622.5403104440097,33.62829905436172,65477.572,7612.636,73.25458675299888,28791,29201,2927,,,,,,,
+122880,122624,256,8192,1504.8216781893486,31.548987505491805,81487.396,8114.365,89.77208317398618,28789,29274,2854,,,,,,,
+139264,139008,256,8192,1407.0912975895553,29.676208224506077,98791.031,8626.439,107.58944605600846,28796,29336,2792,,,,,,,
+155648,155392,256,8192,1313.5149951034814,27.74285537486937,118302.418,9227.601,127.70674044400221,28796,29402,2726,,,,,,,
+172032,171776,256,8192,1241.868564533947,26.271534576777377,138320.596,9744.387,148.2359546860098,28796,29463,2665,,,,,,,
+188416,188160,256,8192,1171.4413433339246,24.845046009434324,160622.639,10303.865,171.10501635199762,28793,29527,2602,,,,,,,
+204800,204544,256,8192,1115.0339324509255,23.695057201811817,183441.951,10803.941,194.42584469100984,28795,29591,2537,,,,,,,
+221184,220928,256,8192,1063.11862630722,22.580322219433985,207811.24,11337.305,219.33679267199477,28794,29652,2476,,,,,,,
+237568,237312,256,8192,1014.1556100911681,21.587939695102396,233999.593,11858.473,246.04247540001234,28792,29721,2407,,,,,,,
+253952,253696,256,8192,967.4973023198612,20.796553491172677,262218.819,12309.732,274.7197408189968,28795,29776,2352,,,,,,,
+262144,261888,256,8192,946.4032281179243,20.524834448369017,276719.259,12472.695,289.3867558280035,28786,29821,2307,,,,,,,
diff --git a/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.jsonl b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.jsonl
new file mode 100644
index 000000000000..bcc031e5af07
--- /dev/null
+++ b/benchmarks/results/kv-stream-pr-evidence/qwen3.8-27b-throughput/results.jsonl
@@ -0,0 +1,18 @@
+{"arena_backoff_mib": 64, "arena_retries": 8, "arena_step_mib": 32, "baseline_vram_total_mib": 32607, "baseline_vram_used_mib": 1575, "batch_size": 256, "cache_type_k": "q8_0", "cache_type_v": "turbo4", "capacities": [8192, 24576, 40960, 57344, 73728, 90112, 106496, 122880, 139264, 155648, 172032, 188416, 204800, 221184, 237568, 253952, 262144], "context_step": 16384, "cuda_visible_devices": null, "decode_tokens": 256, "extra_server_args": [], "fill_token_id": null, "fixed_arena_mib": 8192, "flash_attention": true, "gpu_index": 0, "max_arena_mib": null, "max_context": 262144, "min_context": 8192, "model": "/mnt/storage/models/qwen3.8/Qwen3.8-27B-AD-Q5_K_M.gguf", "parallel": 1, "probe_arena_mib": 1536, "probe_arena_step_mib": 256, "prompt_suffix": "The capital of France is", "revision": "179e89ff7e16", "server": "/mnt/storage/Projects/llama-cpp-turboquant/build/bin/llama-server", "timestamp": "2026-09-05T22:07:46.915575+00:00", "trace_kv_stream": false, "type": "metadata", "ubatch_size": 256, "uvm": false}
+{"arena_mib": 8192, "context_capacity": 8192, "decode_tokens": 256, "decode_tps": 59.46466010604221, "fill_token_id": 760, "predicted_ms": 4305.078, "prefill_tps": 2759.0148620370887, "prompt_ms": 2876.389, "prompt_tokens": 7936, "status": "ok", "type": "measurement", "vram_after_mib": 28824, "vram_before_mib": 28813, "vram_free_after_mib": 3304, "wall_seconds": 7.3351924840098945}
+{"arena_mib": 8192, "context_capacity": 24576, "decode_tokens": 256, "decode_tps": 52.56594716342034, "fill_token_id": 760, "predicted_ms": 4870.073, "prefill_tps": 2604.7710795008907, "prompt_ms": 9336.713, "prompt_tokens": 24320, "status": "ok", "type": "measurement", "vram_after_mib": 28888, "vram_before_mib": 28794, "vram_free_after_mib": 3240, "wall_seconds": 14.363954145010212}
+{"arena_mib": 8192, "context_capacity": 40960, "decode_tokens": 256, "decode_tps": 47.311776289222806, "fill_token_id": 760, "predicted_ms": 5410.915, "prefill_tps": 2396.4251440951884, "prompt_ms": 16985.3, "prompt_tokens": 40704, "status": "ok", "type": "measurement", "vram_after_mib": 28954, "vram_before_mib": 28796, "vram_free_after_mib": 3174, "wall_seconds": 22.551607003988465}
+{"arena_mib": 8192, "context_capacity": 57344, "decode_tokens": 256, "decode_tps": 42.82034173643511, "fill_token_id": 760, "predicted_ms": 5978.467, "prefill_tps": 2155.9608514549845, "prompt_ms": 26479.145, "prompt_tokens": 57088, "status": "ok", "type": "measurement", "vram_after_mib": 29012, "vram_before_mib": 28796, "vram_free_after_mib": 3116, "wall_seconds": 32.61641234300623}
+{"arena_mib": 8192, "context_capacity": 73728, "decode_tokens": 256, "decode_tps": 39.58309721345819, "fill_token_id": 760, "predicted_ms": 6467.407, "prefill_tps": 1942.911530356988, "prompt_ms": 37815.412, "prompt_tokens": 73472, "status": "ok", "type": "measurement", "vram_after_mib": 29081, "vram_before_mib": 28792, "vram_free_after_mib": 3047, "wall_seconds": 44.447617318000994}
+{"arena_mib": 8192, "context_capacity": 90112, "decode_tokens": 256, "decode_tps": 36.4232172969306, "fill_token_id": 760, "predicted_ms": 7028.484, "prefill_tps": 1773.4569063747938, "prompt_ms": 50667.146, "prompt_tokens": 89856, "status": "ok", "type": "measurement", "vram_after_mib": 29141, "vram_before_mib": 28795, "vram_free_after_mib": 2987, "wall_seconds": 57.85852407698985}
+{"arena_mib": 8192, "context_capacity": 106496, "decode_tokens": 256, "decode_tps": 33.62829905436172, "fill_token_id": 760, "predicted_ms": 7612.636, "prefill_tps": 1622.5403104440097, "prompt_ms": 65477.572, "prompt_tokens": 106240, "status": "ok", "type": "measurement", "vram_after_mib": 29201, "vram_before_mib": 28791, "vram_free_after_mib": 2927, "wall_seconds": 73.25458675299888}
+{"arena_mib": 8192, "context_capacity": 122880, "decode_tokens": 256, "decode_tps": 31.548987505491805, "fill_token_id": 760, "predicted_ms": 8114.365, "prefill_tps": 1504.8216781893486, "prompt_ms": 81487.396, "prompt_tokens": 122624, "status": "ok", "type": "measurement", "vram_after_mib": 29274, "vram_before_mib": 28789, "vram_free_after_mib": 2854, "wall_seconds": 89.77208317398618}
+{"arena_mib": 8192, "context_capacity": 139264, "decode_tokens": 256, "decode_tps": 29.676208224506077, "fill_token_id": 760, "predicted_ms": 8626.439, "prefill_tps": 1407.0912975895553, "prompt_ms": 98791.031, "prompt_tokens": 139008, "status": "ok", "type": "measurement", "vram_after_mib": 29336, "vram_before_mib": 28796, "vram_free_after_mib": 2792, "wall_seconds": 107.58944605600846}
+{"arena_mib": 8192, "context_capacity": 155648, "decode_tokens": 256, "decode_tps": 27.74285537486937, "fill_token_id": 760, "predicted_ms": 9227.601, "prefill_tps": 1313.5149951034814, "prompt_ms": 118302.418, "prompt_tokens": 155392, "status": "ok", "type": "measurement", "vram_after_mib": 29402, "vram_before_mib": 28796, "vram_free_after_mib": 2726, "wall_seconds": 127.70674044400221}
+{"arena_mib": 8192, "context_capacity": 172032, "decode_tokens": 256, "decode_tps": 26.271534576777377, "fill_token_id": 760, "predicted_ms": 9744.387, "prefill_tps": 1241.868564533947, "prompt_ms": 138320.596, "prompt_tokens": 171776, "status": "ok", "type": "measurement", "vram_after_mib": 29463, "vram_before_mib": 28796, "vram_free_after_mib": 2665, "wall_seconds": 148.2359546860098}
+{"arena_mib": 8192, "context_capacity": 188416, "decode_tokens": 256, "decode_tps": 24.845046009434324, "fill_token_id": 760, "predicted_ms": 10303.865, "prefill_tps": 1171.4413433339246, "prompt_ms": 160622.639, "prompt_tokens": 188160, "status": "ok", "type": "measurement", "vram_after_mib": 29527, "vram_before_mib": 28793, "vram_free_after_mib": 2602, "wall_seconds": 171.10501635199762}
+{"arena_mib": 8192, "context_capacity": 204800, "decode_tokens": 256, "decode_tps": 23.695057201811817, "fill_token_id": 760, "predicted_ms": 10803.941, "prefill_tps": 1115.0339324509255, "prompt_ms": 183441.951, "prompt_tokens": 204544, "status": "ok", "type": "measurement", "vram_after_mib": 29591, "vram_before_mib": 28795, "vram_free_after_mib": 2537, "wall_seconds": 194.42584469100984}
+{"arena_mib": 8192, "context_capacity": 221184, "decode_tokens": 256, "decode_tps": 22.580322219433985, "fill_token_id": 760, "predicted_ms": 11337.305, "prefill_tps": 1063.11862630722, "prompt_ms": 207811.24, "prompt_tokens": 220928, "status": "ok", "type": "measurement", "vram_after_mib": 29652, "vram_before_mib": 28794, "vram_free_after_mib": 2476, "wall_seconds": 219.33679267199477}
+{"arena_mib": 8192, "context_capacity": 237568, "decode_tokens": 256, "decode_tps": 21.587939695102396, "fill_token_id": 760, "predicted_ms": 11858.473, "prefill_tps": 1014.1556100911681, "prompt_ms": 233999.593, "prompt_tokens": 237312, "status": "ok", "type": "measurement", "vram_after_mib": 29721, "vram_before_mib": 28792, "vram_free_after_mib": 2407, "wall_seconds": 246.04247540001234}
+{"arena_mib": 8192, "context_capacity": 253952, "decode_tokens": 256, "decode_tps": 20.796553491172677, "fill_token_id": 760, "predicted_ms": 12309.732, "prefill_tps": 967.4973023198612, "prompt_ms": 262218.819, "prompt_tokens": 253696, "status": "ok", "type": "measurement", "vram_after_mib": 29776, "vram_before_mib": 28795, "vram_free_after_mib": 2352, "wall_seconds": 274.7197408189968}
+{"arena_mib": 8192, "context_capacity": 262144, "decode_tokens": 256, "decode_tps": 20.524834448369017, "fill_token_id": 760, "predicted_ms": 12472.695, "prefill_tps": 946.4032281179243, "prompt_ms": 276719.259, "prompt_tokens": 261888, "status": "ok", "type": "measurement", "vram_after_mib": 29821, "vram_before_mib": 28786, "vram_free_after_mib": 2307, "wall_seconds": 289.3867558280035}
diff --git a/benchmarks/test_benchmark_kv_stream.py b/benchmarks/test_benchmark_kv_stream.py
new file mode 100644
index 000000000000..fddf591d5df4
--- /dev/null
+++ b/benchmarks/test_benchmark_kv_stream.py
@@ -0,0 +1,212 @@
+#!/usr/bin/env python3
+"""Unit tests for the automatic adaptive KV benchmark driver."""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import os
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+
+SCRIPT = Path(__file__).with_name("benchmark_kv_stream.py")
+SPEC = importlib.util.spec_from_file_location("benchmark_kv_stream", SCRIPT)
+assert SPEC is not None and SPEC.loader is not None
+BENCHMARK = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = BENCHMARK
+SPEC.loader.exec_module(BENCHMARK)
+
+
+class BenchmarkKvStreamTest(unittest.TestCase):
+ def test_parse_token_count(self) -> None:
+ self.assertEqual(BENCHMARK.parse_token_count("192K"), 192 * 1024)
+ self.assertEqual(BENCHMARK.parse_token_count("262144"), 262144)
+ with self.assertRaises(argparse.ArgumentTypeError):
+ BENCHMARK.parse_token_count("bad")
+
+ def test_parse_args_resolves_launched_paths(self) -> None:
+ model = Path("models/model.gguf")
+ server = Path("build/bin/llama-server")
+ args = BENCHMARK.parse_args(
+ [
+ "--model", str(model),
+ "--server", str(server),
+ "--max-context", "8K",
+ "--batch-size", "768",
+ "--ubatch-size", "512",
+ ]
+ )
+ self.assertEqual(args.model, model.resolve())
+ self.assertEqual(args.server, server.resolve())
+ self.assertEqual(args.batch_size, 768)
+ self.assertEqual(args.ubatch_size, 512)
+ self.assertEqual(args.probe_arena_mib, 1536)
+
+ def test_validate_args_rejects_ubatch_larger_than_batch(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ model = root / "model.gguf"
+ server = root / "llama-server"
+ model.touch()
+ server.touch(mode=0o755)
+ args = BENCHMARK.parse_args(
+ [
+ "--model", str(model),
+ "--server", str(server),
+ "--max-context", "8K",
+ "--batch-size", "256",
+ "--ubatch-size", "512",
+ ]
+ )
+ with self.assertRaisesRegex(SystemExit, "must not exceed"):
+ BENCHMARK.validate_args(args)
+
+ def test_context_capacities_include_non_aligned_maximum(self) -> None:
+ self.assertEqual(
+ BENCHMARK.context_capacities(20000),
+ [8192, 16384, 20000],
+ )
+
+ def test_context_capacities_honor_custom_start_and_step(self) -> None:
+ self.assertEqual(
+ BENCHMARK.context_capacities(163840, 40960, 8192),
+ list(range(40960, 163841, 8192)),
+ )
+
+
+ def test_arena_estimate_uses_all_free_memory_and_rounds_down(self) -> None:
+ self.assertEqual(BENCHMARK.estimate_arena_mib(1536, 2028, 32), 3552)
+ self.assertEqual(
+ BENCHMARK.estimate_arena_mib(1536, 2028, 32, max_arena_mib=2048),
+ 2048,
+ )
+
+ def test_clean_server_env_removes_memory_policy_overrides(self) -> None:
+ inherited = {
+ "GGML_CUDA_KV_STREAM_FIXED_RING_SLOTS": "8",
+ "KEEP_ME": "yes",
+ }
+ with mock.patch.dict(os.environ, inherited, clear=True):
+ env = BENCHMARK.clean_server_env("2")
+ self.assertNotIn("GGML_CUDA_KV_STREAM_FIXED_RING_SLOTS", env)
+ self.assertEqual(env["KEEP_ME"], "yes")
+ self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "2")
+ traced = BENCHMARK.clean_server_env(None, trace_kv_stream=True)
+ self.assertEqual(traced["LLAMA_KV_STREAM_TRACE"], "1")
+
+ def test_server_command_uses_tested_configuration(self) -> None:
+ args = argparse.Namespace(
+ server=Path("/tmp/llama-server"),
+ model=Path("/tmp/model.gguf"),
+ port=12355,
+ extra_server_arg=["--verbosity", "3"],
+ cache_type_k="bf16",
+ cache_type_v="q8_0",
+ batch_size=768,
+ ubatch_size=512,
+ )
+ command = BENCHMARK.server_command(args, 131072, 2304)
+ self.assertEqual(command[0], "/tmp/llama-server")
+ self.assertIn("131072", command)
+ self.assertIn("2304", command)
+ self.assertEqual(command[command.index("-ctk") + 1], "bf16")
+ self.assertEqual(command[command.index("-ctv") + 1], "q8_0")
+ self.assertEqual(command[command.index("-b") + 1], "768")
+ self.assertEqual(command[command.index("-ub") + 1], "512")
+ self.assertEqual(command[command.index("-np") + 1], "1")
+ self.assertEqual(
+ command[command.index("--kv-stream-arena-mib") + 1], "2304"
+ )
+ self.assertEqual(command[command.index("--fit") + 1], "off")
+ self.assertNotIn("--kv-stream-stage-mib", command)
+ self.assertEqual(command[-2:], ["--verbosity", "3"])
+
+ def test_prepare_server_warms_a_full_physical_batch(self) -> None:
+ args = argparse.Namespace(
+ prompt_suffix="suffix",
+ fill_token_id=None,
+ ubatch_size=512,
+ request_timeout=30,
+ )
+ server = mock.Mock()
+ server.url.side_effect = lambda path: f"http://test{path}"
+ with mock.patch.object(
+ BENCHMARK,
+ "http_json",
+ side_effect=({"tokens": [42, 43]}, {"timings": {}}),
+ ) as http_json:
+ suffix, fill_token_id = BENCHMARK.prepare_server(args, server)
+ self.assertEqual(suffix, [42, 43])
+ self.assertEqual(fill_token_id, 42)
+ warmup_payload = http_json.call_args_list[1].args[1]
+ self.assertEqual(len(warmup_payload["prompt"]), 512)
+
+ def test_trace_parser_marks_only_pages_beyond_resident_partition(self) -> None:
+ log = (
+ "I kv_stream_adapt: active 65536, resident 256, ring 32, "
+ "samples 1, misses 0, copy busy 0.0%, peak 1\n"
+ "W kv_stream_adapt: adaptive KV partition: resident pages/layer "
+ "256 -> 248, ring slots 32 -> 160, miss 50.0%, copy busy 25.0%\n"
+ "I kv_stream_adapt: active 65792, resident 248, ring 160, "
+ "samples 2, misses 1, copy busy 25.0%, peak 10\n"
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "server.log"
+ path.write_text(log)
+ parsed = BENCHMARK.parse_kv_stream_trace(path)
+ self.assertTrue(parsed["streaming_active"])
+ self.assertEqual(parsed["stream_first_active_tokens"], 65792)
+ self.assertEqual(parsed["stream_trace_samples"], 2)
+ self.assertEqual(parsed["stream_repartitions"], 1)
+ self.assertEqual(parsed["stream_max_ring_slots"], 160)
+
+
+ def test_resume_rejects_changed_settings(self) -> None:
+
+ signature = {"model": "/tmp/model.gguf", "max_context": 16384}
+ BENCHMARK.validate_resume(signature.copy(), signature, Path("results.jsonl"))
+ with self.assertRaisesRegex(SystemExit, "different settings"):
+ BENCHMARK.validate_resume(
+ {"model": "/tmp/other.gguf", "max_context": 16384},
+ signature,
+ Path("results.jsonl"),
+ )
+
+ def test_csv_and_plot_accept_partial_sweep(self) -> None:
+ rows = {
+ 8192: {
+ "context_capacity": 8192,
+ "prompt_tokens": 7936,
+ "decode_tokens": 256,
+ "arena_mib": 3552,
+ "prefill_tps": 1400.0,
+ "decode_tps": 50.0,
+ },
+ 16384: {
+ "context_capacity": 16384,
+ "prompt_tokens": 16128,
+ "decode_tokens": 256,
+ "arena_mib": 3520,
+ "prefill_tps": 1300.0,
+ "decode_tps": 45.0,
+ },
+ }
+ try:
+ plt = BENCHMARK.require_matplotlib()
+ except SystemExit:
+ self.skipTest("Matplotlib is not installed")
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory)
+ BENCHMARK.write_csv(output / "results.csv", rows)
+ BENCHMARK.plot_results(output, rows, plt)
+ self.assertTrue((output / "results.csv").is_file())
+ self.assertTrue((output / "kv-stream-sweep.png").is_file())
+ self.assertTrue((output / "kv-stream-sweep.svg").is_file())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/benchmarks/test_kv_stream_serial_server.py b/benchmarks/test_kv_stream_serial_server.py
new file mode 100644
index 000000000000..42a7b1ebaa3f
--- /dev/null
+++ b/benchmarks/test_kv_stream_serial_server.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+
+import argparse
+import json
+from pathlib import Path
+import signal
+import subprocess
+import time
+import urllib.request
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def request(port: int, path: str, payload: dict | None, timeout: int = 600) -> dict:
+ data = None if payload is None else json.dumps(payload).encode()
+ req = urllib.request.Request(
+ f"http://127.0.0.1:{port}{path}", data=data,
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=timeout) as response:
+ return json.load(response)
+
+
+class Server:
+ def __init__(
+ self, model: Path, executable: Path, port: int,
+ arena_mib: int, cache_mib: int, log: Path,
+ ):
+ command = [
+ str(executable),
+ "-m", str(model), "--host", "127.0.0.1", "--port", str(port),
+ "--ctx-size", "8448", "-fa", "on", "-ctk", "q8_0", "-ctv", "q4_0",
+ "-ngl", "all", "-b", "256", "-ub", "256", "-np", "1",
+ "--no-mmproj", "--no-warmup", "--fit", "off",
+ "--reasoning-format", "none",
+ "--kv-stream-arena-mib", str(arena_mib),
+ "--cache-ram", str(cache_mib),
+ ]
+ self.log_file = log.open("wb")
+ self.process = subprocess.Popen(
+ command, stdout=self.log_file, stderr=subprocess.STDOUT)
+ deadline = time.monotonic() + 180
+ while time.monotonic() < deadline:
+ if self.process.poll() is not None:
+ self.log_file.close()
+ raise RuntimeError(f"server exited with {self.process.returncode}")
+ try:
+ if request(port, "/health", None, 2).get("status") == "ok":
+ self.port = port
+ return
+ except Exception:
+ time.sleep(0.25)
+ self.process.send_signal(signal.SIGINT)
+ self.process.wait(timeout=15)
+ self.log_file.close()
+ raise RuntimeError("server did not become ready")
+
+ def stop(self):
+ if self.process.poll() is None:
+ self.process.send_signal(signal.SIGINT)
+ self.process.wait(timeout=15)
+ self.log_file.close()
+
+
+def completion(server: Server, prompt: list[int], cache_prompt: bool) -> dict:
+ return request(server.port, "/completion", {
+ "prompt": prompt,
+ "n_predict": 16,
+ "ignore_eos": True,
+ "cache_prompt": cache_prompt,
+ "temperature": 0,
+ "seed": 1,
+ "reasoning_format": "none",
+ })
+
+
+def patterned(size: int, tokens: tuple[int, ...]) -> list[int]:
+ return [tokens[i % len(tokens)] for i in range(size)]
+
+
+def run_serial(
+ model: Path, executable: Path, port: int, arena_mib: int, output: Path,
+):
+ server = Server(
+ model, executable, port, arena_mib, 0, output / "serial.log")
+ try:
+ short = patterned(1024, (23066, 1000, 2000))
+ medium = patterned(4096, (23066, 3000, 4000, 5000))
+ streamed = patterned(6144, (23066, 6000, 7000, 8000, 9000))
+ short_first = completion(server, short, False)
+ medium_first = completion(server, medium, False)
+ streamed_result = completion(server, streamed, False)
+ short_second = completion(server, short, False)
+ medium_second = completion(server, medium, False)
+ serial_changed = (
+ short_second["content"] != short_first["content"] or
+ medium_second["content"] != medium_first["content"])
+ streamed_invalid = not streamed_result["content"].strip("/")
+ if serial_changed or streamed_invalid:
+ details = {
+ "short_first": short_first["content"],
+ "short_second": short_second["content"],
+ "medium_first": medium_first["content"],
+ "streamed": streamed_result["content"],
+ "medium_second": medium_second["content"],
+ }
+ raise RuntimeError(f"serial unrelated-prefill output changed: {json.dumps(details)}")
+ print("serial unrelated-prefill test: PASS", flush=True)
+ finally:
+ server.stop()
+
+
+def run_prompt_cache(
+ model: Path, executable: Path, port: int, arena_mib: int, output: Path,
+):
+ server = Server(
+ model, executable, port, arena_mib, 1536,
+ output / "prompt-cache.log")
+ try:
+ cached = patterned(4096, (23066, 1100, 2100, 3100))
+ unrelated = patterned(2048, (23066, 4100, 5100, 6100))
+ expected = completion(server, cached, True)["content"]
+ completion(server, unrelated, True)
+ restored = completion(server, cached, True)
+ if restored["content"] != expected:
+ raise RuntimeError("prompt-cache restore output changed")
+ if restored["timings"].get("cache_n", 0) == 0:
+ raise RuntimeError("prompt-cache restore did not reuse cached tokens")
+ print(f"prompt-cache restore test: PASS (cache_n={restored['timings']['cache_n']})", flush=True)
+ finally:
+ server.stop()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model", type=Path, required=True)
+ parser.add_argument(
+ "--server", type=Path,
+ default=ROOT / "build-kv-cuda/bin/llama-server")
+ parser.add_argument("--arena-mib", type=int, default=128)
+ parser.add_argument("--port", type=int, default=12358)
+ parser.add_argument("--output", type=Path, default=ROOT / "benchmarks/results/serial-server")
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=True)
+ run_serial(args.model, args.server, args.port, args.arena_mib, args.output)
+ run_prompt_cache(
+ args.model, args.server, args.port, args.arena_mib, args.output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/build-xcframework.sh b/build-xcframework.sh
index 697278d050c5..2119d3b87e11 100755
--- a/build-xcframework.sh
+++ b/build-xcframework.sh
@@ -17,7 +17,6 @@ LLAMA_BUILD_MTMD=ON
GGML_METAL=ON
GGML_METAL_EMBED_LIBRARY=ON
GGML_BLAS_DEFAULT=ON
-GGML_METAL_USE_BF16=ON
GGML_OPENMP=OFF
COMMON_C_FLAGS="-Wno-macro-redefined -Wno-shorten-64-to-32 -Wno-unused-command-line-argument -g"
@@ -44,7 +43,6 @@ COMMON_CMAKE_ARGS=(
-DGGML_METAL_EMBED_LIBRARY=${GGML_METAL_EMBED_LIBRARY}
-DGGML_BLAS_DEFAULT=${GGML_BLAS_DEFAULT}
-DGGML_METAL=${GGML_METAL}
- -DGGML_METAL_USE_BF16=${GGML_METAL_USE_BF16}
-DGGML_NATIVE=OFF
-DGGML_OPENMP=${GGML_OPENMP}
)
diff --git a/ci/run.sh b/ci/run.sh
index e4a34ff0acd8..68a95ec32333 100755
--- a/ci/run.sh
+++ b/ci/run.sh
@@ -10,6 +10,9 @@
# # with CUDA support
# GG_BUILD_CUDA=1 bash ./ci/run.sh ./tmp/results ./tmp/mnt
#
+# # with ROCm support
+# GG_BUILD_ROCM=1 GG_BUILD_AMDGPU_TARGETS=gfx1151 bash ./ci/run.sh ./tmp/results ./tmp/mnt
+#
# # with SYCL support
# GG_BUILD_SYCL=1 bash ./ci/run.sh ./tmp/results ./tmp/mnt
#
@@ -89,7 +92,7 @@ if [ ! -z ${GG_BUILD_CUDA} ]; then
fi
if [ ! -z ${GG_BUILD_ROCM} ]; then
- CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_HIP=ON"
+ CMAKE_EXTRA="${CMAKE_EXTRA} -DCMAKE_HIP_COMPILER=$(hipconfig -l)/clang -DGGML_HIP=ON -DGGML_HIP_ROCWMMA_FATTN=ON"
if [ -z ${GG_BUILD_AMDGPU_TARGETS} ]; then
echo "Missing GG_BUILD_AMDGPU_TARGETS, please set it to your GPU architecture (e.g. gfx90a, gfx1100, etc.)"
exit 1
diff --git a/common/arg.cpp b/common/arg.cpp
index cd1cd40d84cf..76e23cce08d4 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -25,10 +25,12 @@
#include
#include
+#include
#include
#include
#include
#include
+#include
#include
#include
#include
@@ -61,6 +63,7 @@ static std::initializer_list mmproj_examples = {
LLAMA_EXAMPLE_MTMD,
LLAMA_EXAMPLE_SERVER,
LLAMA_EXAMPLE_CLI,
+ LLAMA_EXAMPLE_TTS,
};
static std::string read_file(const std::string & fname) {
@@ -258,6 +261,13 @@ static void parse_tensor_buffer_overrides(const std::string & value, std::vector
if (buft) {
buft_list[ggml_backend_buft_name(buft)] = buft;
}
+ // Also offer the device's pinned host buffer, so a tensor can deliberately be left in host
+ // memory and read in place. Worth it only for a large tensor that is gathered from rather
+ // than streamed; whether the backend will accept one as a kernel input is its own decision.
+ auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
+ if (host_buft) {
+ buft_list[ggml_backend_buft_name(host_buft)] = host_buft;
+ }
}
for (const auto & override : string_split(value, ',')) {
@@ -363,12 +373,14 @@ static bool spec_types_is_default(const common_params & params) {
common_models_handler common_models_handler_init(const common_params & params, llama_example curr_ex) {
common_download_hf_plan plan;
common_download_hf_plan plan_spec;
- common_download_hf_plan plan_voc;
common_download_opts opts;
const bool spec_type_draft_mtp = std::find(params.speculative.types.begin(),
params.speculative.types.end(),
- COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end();
+ COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end() ||
+ std::find(params.speculative.types.begin(),
+ params.speculative.types.end(),
+ COMMON_SPECULATIVE_TYPE_DRAFT_MTP_ADAPTIVE) != params.speculative.types.end();
const bool spec_type_draft_dflash = std::find(params.speculative.types.begin(),
params.speculative.types.end(),
@@ -416,11 +428,7 @@ common_models_handler common_models_handler_init(const common_params & params, l
plan_spec = common_download_get_hf_plan(params.speculative.draft.mparams, opts_spec);
}
- if (!params.vocoder.model.hf_repo.empty()) {
- plan_voc = common_download_get_hf_plan(params.vocoder.model, opts);
- }
-
- return common_models_handler{plan, plan_spec, plan_voc, opts};
+ return common_models_handler{plan, plan_spec, opts};
}
bool common_models_handler_is_preset_repo(const common_models_handler & handler) {
@@ -470,7 +478,6 @@ void common_models_handler_apply(common_models_handler & handler, common_params
auto & plan = handler.plan;
auto & plan_spec = handler.plan_spec;
- auto & plan_voc = handler.plan_voc;
auto opts = handler.opts; // copy
opts.callback = callback;
@@ -485,7 +492,6 @@ void common_models_handler_apply(common_models_handler & handler, common_params
};
handle_url(params.model);
handle_url(params.mmproj);
- handle_url(params.vocoder.model);
handle_url(params.speculative.draft.mparams);
// optionally, if docker repo is set, resolve it
@@ -513,14 +519,6 @@ void common_models_handler_apply(common_models_handler & handler, common_params
task.opts = opts;
tasks.push_back(task);
}
- if (!params.vocoder.model.url.empty()) {
- common_download_task task;
- task.url = params.vocoder.model.url;
- task.local_path = params.vocoder.model.path;
- task.opts = opts;
- tasks.push_back(task);
- }
-
bool had_spec_url = false;
if (!params.speculative.draft.mparams.url.empty()) {
common_download_task task;
@@ -634,11 +632,6 @@ void common_models_handler_apply(common_models_handler & handler, common_params
had_spec_url = true;
}
- // handle vocoder plan (e.g. --hf-repo-v)
- if (!plan_voc.model_files.empty()) {
- add_tasks(plan_voc.model_files, plan_voc.primary, params.vocoder.model);
- }
-
if (!plan.model_files.empty()) {
add_tasks(plan.model_files, plan.primary, params.model);
}
@@ -852,6 +845,11 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context
// parse all CLI args now, so that -hf is available below for remote preset resolution
parse_cli_args();
+ if (params.moe_cache.mode == COMMON_MOE_CACHE_MODE_ON && !params.no_extra_bufts) {
+ LOG_INF("explicit MoE cache mode disables weight repacking\n");
+ params.no_extra_bufts = true;
+ }
+
postprocess_cpu_params(params.cpuparams, nullptr);
postprocess_cpu_params(params.cpuparams_batch, ¶ms.cpuparams);
@@ -1267,6 +1265,12 @@ bool common_params_parse(int argc, char ** argv, common_params & params, llama_e
common_params_print_completion(ctx_arg);
exit(0);
}
+
+ const bool adaptive_mtp = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP_ADAPTIVE) != params.speculative.types.end();
+ if (adaptive_mtp && (params.speculative.draft.n_min_adaptive < 1 || params.speculative.draft.n_min_adaptive > params.speculative.draft.n_max)) {
+ throw std::invalid_argument("error: --spec-draft-n-min-adaptive must be in [1, --spec-draft-n-max]");
+ }
+
params.lr.init();
} catch (const std::invalid_argument & ex) {
fprintf(stderr, "%s\n", ex.what());
@@ -1364,6 +1368,10 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.n_parallel = -1; // auto by default
} else if (ex == LLAMA_EXAMPLE_TOKENIZE) {
params.parse_special = true; // parse special tokens by default, like the old tokenize tool
+ } else if (ex == LLAMA_EXAMPLE_TTS) {
+ params.out_file = "output.wav";
+ params.sampling.penalty_repeat = 1.05f;
+ params.sampling.penalty_last_n = -1;
}
params.use_color = tty_can_use_colors();
@@ -1665,7 +1673,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
).set_env("LLAMA_ARG_CHECKPOINT_MIN_SPACING_NT").set_examples({LLAMA_EXAMPLE_SERVER}));
add_opt(common_arg(
{"-cram", "--cache-ram"}, "N",
- string_format("set the maximum cache size in MiB (default: %d, -1 - no limit, 0 - disable)"
+ string_format("set the maximum cache size in MiB (default: %d, -1 - half of the free host memory at startup, 0 - disable)"
"[(more info)](https://github.com/ggml-org/llama.cpp/pull/16391)", params.cache_ram_mib),
[](common_params & params, int value) {
params.cache_ram_mib = value;
@@ -2027,9 +2035,9 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
).set_sampling());
add_opt(common_arg(
{"--repeat-last-n"}, "N",
- string_format("last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)", params.sampling.penalty_last_n),
+ string_format("last n tokens to consider for penalize (default: %d, 0 = disabled)", params.sampling.penalty_last_n),
[](common_params & params, int value) {
- if (value < -1) {
+ if (value < 0) {
throw std::runtime_error(string_format("error: invalid repeat-last-n = %d\n", value));
}
params.sampling.penalty_last_n = value;
@@ -2100,9 +2108,9 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
).set_sampling());
add_opt(common_arg(
{"--dry-penalty-last-n"}, "N",
- string_format("set DRY penalty for the last n tokens (default: %d, 0 = disable, -1 = context size)", params.sampling.dry_penalty_last_n),
+ string_format("set DRY penalty for the last n tokens (default: %d, 0 = disable)", params.sampling.dry_penalty_last_n),
[](common_params & params, int value) {
- if (value < -1) {
+ if (value < 0) {
throw std::runtime_error(string_format("error: invalid dry-penalty-last-n = %d\n", value));
}
params.sampling.dry_penalty_last_n = value;
@@ -2369,6 +2377,16 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.no_kv_offload = !value;
}
).set_env("LLAMA_ARG_KV_OFFLOAD"));
+ add_opt(common_arg(
+ {"--kv-stream-arena-mib", "--kv-stream-stage-mib"}, "N",
+ string_format("shared CUDA arena for block-streaming KV and phase compute buffers in MiB; 0 disables it (default: %u)", params.kv_stream_arena_mib),
+ [](common_params & params, int value) {
+ if (value < 0) {
+ throw std::invalid_argument("KV stream arena size must be non-negative");
+ }
+ params.kv_stream_arena_mib = value;
+ }
+ ).set_env("LLAMA_ARG_KV_STREAM_ARENA_MIB"));
add_opt(common_arg(
{"--repack"},
{"-nr", "--no-repack"},
@@ -2507,6 +2525,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
string_format("number of parallel sequences to decode (default: %d)", params.n_parallel),
[](common_params & params, int value) {
params.n_parallel = value;
+ params.n_parallel_explicit = true;
}
).set_env("LLAMA_ARG_N_PARALLEL"));
}
@@ -2625,13 +2644,15 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
add_opt(common_arg(
{"-lm", "--load-mode"}, "MODE",
"model loading mode (default: mmap)\n"
+ "- auto: mmap\n"
"- none: no special loading mode\n"
"- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)\n"
"- mlock: force system to keep model in RAM rather than swapping or compressing\n"
"- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing\n"
"- dio: use DirectIO if available\n",
[](common_params & params, const std::string & value) {
- /**/ if (value == "none") { params.load_mode = LLAMA_LOAD_MODE_NONE; }
+ /**/ if (value == "auto") { params.load_mode = LLAMA_LOAD_MODE_AUTO; }
+ else if (value == "none") { params.load_mode = LLAMA_LOAD_MODE_NONE; }
else if (value == "mmap") { params.load_mode = LLAMA_LOAD_MODE_MMAP; }
else if (value == "mlock") { params.load_mode = LLAMA_LOAD_MODE_MLOCK; }
else if (value == "mmap+mlock") { params.load_mode = LLAMA_LOAD_MODE_MMAP_MLOCK; }
@@ -2639,6 +2660,19 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
else { throw std::invalid_argument("invalid value"); }
}
).set_env("LLAMA_ARG_LOAD_MODE"));
+ add_opt(common_arg(
+ {"--tensor-read-lazy"}, "MODE",
+ "on-demand reading of certain tensors, for example per-layer embeddings (default: auto)\n"
+ "- on: read the rows of such tensors from disk on demand instead of keeping them resident (requires mmap)\n"
+ "- auto: on, but only for tensors larger than 4 GiB\n"
+ "- off: always keep them resident",
+ [](common_params & params, const std::string & value) {
+ /**/ if (value == "on") { params.tensor_read_lazy = LLAMA_TENSOR_READ_LAZY_ON; }
+ else if (value == "auto") { params.tensor_read_lazy = LLAMA_TENSOR_READ_LAZY_AUTO; }
+ else if (value == "off") { params.tensor_read_lazy = LLAMA_TENSOR_READ_LAZY_OFF; }
+ else { throw std::invalid_argument("invalid value"); }
+ }
+ ).set_env("LLAMA_ARG_TENSOR_READ_LAZY"));
add_opt(common_arg(
{"--numa"}, "TYPE",
"attempt optimizations that help on some NUMA systems\n"
@@ -2698,6 +2732,41 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
}
}
).set_env("LLAMA_ARG_N_CPU_MOE"));
+ add_opt(common_arg(
+ {"--moe-cache"}, "MODE",
+ "adaptively cache the hottest CPU-resident MoE experts in spare VRAM "
+ "(default: auto; auto = preserve weight repacking; on = automatic budget without weight repacking; "
+ "soft = try spare VRAM first, evict experts only as needed; "
+ "off/0 = disabled; N = VRAM budget in MiB per device without weight repacking)",
+ [](common_params & params, const std::string & value) {
+ params.moe_cache.mode_explicit = true;
+ params.moe_cache.fit_selected = false;
+
+ if (value == "off" || value == "0") {
+ params.moe_cache.mode = COMMON_MOE_CACHE_MODE_OFF;
+ params.moe_cache.budget_mib = 0;
+ } else if (value == "auto") {
+ params.moe_cache.mode = COMMON_MOE_CACHE_MODE_AUTO;
+ params.moe_cache.budget_mib = 0;
+ } else if (value == "soft") {
+ params.moe_cache.mode = COMMON_MOE_CACHE_MODE_SOFT;
+ params.moe_cache.budget_mib = 0;
+ } else if (value == "on") {
+ params.moe_cache.mode = COMMON_MOE_CACHE_MODE_ON;
+ params.moe_cache.budget_mib = 0;
+ } else {
+ char * end = nullptr;
+ errno = 0;
+ const long long budget_mb = strtoll(value.c_str(), &end, 10);
+ if (errno != 0 || end == value.c_str() || *end != '\0' ||
+ budget_mb <= 0 || budget_mb > 1024 * 1024) {
+ throw std::invalid_argument("expected auto, on, off, 0, or a positive MiB budget");
+ }
+ params.moe_cache.mode = COMMON_MOE_CACHE_MODE_ON;
+ params.moe_cache.budget_mib = (size_t)budget_mb;
+ }
+ }
+ ).set_env("LLAMA_ARG_MOE_CACHE"));
GGML_ASSERT(params.n_gpu_layers < 0); // string_format would need to be extended for a default >= 0
add_opt(common_arg(
{"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",
@@ -2751,7 +2820,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
const std::regex regex{ R"([,/]+)" };
std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
std::vector split_arg{ it, {} };
- if (split_arg.size() >= llama_max_devices()) {
+ if (split_arg.size() > llama_max_devices()) {
throw std::invalid_argument(
string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices())
);
@@ -2817,7 +2886,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
const std::regex regex{ R"([,/]+)" };
std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
std::vector split_arg{ it, {} };
- if (split_arg.size() >= llama_max_devices()) {
+ if (split_arg.size() > llama_max_devices()) {
throw std::invalid_argument(
string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices())
);
@@ -2987,20 +3056,6 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.model.hf_file = value;
}
).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_DOWNLOAD, LLAMA_EXAMPLE_TOKENIZE}).set_env("LLAMA_ARG_HF_FILE"));
- add_opt(common_arg(
- {"-hfv", "-hfrv", "--hf-repo-v"}, "/[:quant]",
- "Hugging Face model repository for the vocoder model (default: unused)",
- [](common_params & params, const std::string & value) {
- params.vocoder.model.hf_repo = value;
- }
- ).set_env("LLAMA_ARG_HF_REPO_V"));
- add_opt(common_arg(
- {"-hffv", "--hf-file-v"}, "FILE",
- "Hugging Face model file for the vocoder model (default: unused)",
- [](common_params & params, const std::string & value) {
- params.vocoder.model.hf_file = value;
- }
- ).set_env("LLAMA_ARG_HF_FILE_V"));
add_opt(common_arg(
{"-hft", "--hf-token"}, "TOKEN",
"Hugging Face access token (default: value from HF_TOKEN environment variable)",
@@ -3739,6 +3794,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
}
}
).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_COMPLETION, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_REASONING"));
+ add_opt(common_arg(
+ {"--reasoning-effort"}, "LEVEL",
+ "reasoning effort level given to the chat template: 'default' to keep the template default,\n"
+ "or a level such as 'minimal', 'low', 'medium', 'high', 'xhigh' or 'max' (default: default)",
+ [](common_params & params, const std::string & value) {
+ if (value == "default") {
+ params.default_template_kwargs.erase("reasoning_effort");
+ } else {
+ params.default_template_kwargs["reasoning_effort"] = json(value).dump();
+ }
+ }
+ ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_COMPLETION, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_REASONING_EFFORT"));
add_opt(common_arg(
{"--reasoning-budget"}, "N",
"token budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget (default: -1)",
@@ -4167,6 +4234,34 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
}
}
).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_CPU_MOE"));
+ add_opt(common_arg(
+ {"--eagle3"},
+ "use EAGLE3 speculative decoding with the draft model",
+ [](common_params & params) {
+ params.speculative.draft.eagle3 = true;
+ }
+ ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}));
+ add_opt(common_arg(
+ {"--dflash"},
+ "use DFlash speculative decoding with the draft model",
+ [](common_params & params) {
+ params.speculative.draft.dflash = true;
+ }
+ ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}));
+ add_opt(common_arg(
+ {"--dflash-defer-injection"}, "<0|1>",
+ "DFlash deferred encoder KV injection (default: 1, 0 = per-chunk injection for higher acceptance on some models)",
+ [](common_params & params, int value) {
+ params.speculative.draft.dflash_defer_injection = value;
+ }
+ ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_DFLASH_DEFER_INJECTION"));
+ add_opt(common_arg(
+ {"-cd", "--ctx-size-draft"}, "N",
+ string_format("size of the prompt context for the draft model (default: %d, 0 = loaded from model)", params.speculative.draft.n_ctx),
+ [](common_params & params, int value) {
+ params.speculative.draft.n_ctx = value;
+ }
+ ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_CTX"));
add_opt(common_arg(
{"--spec-draft-n-max"}, "N",
@@ -4183,6 +4278,44 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
}
).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_MIN"));
+ add_opt(common_arg(
+ {"--spec-draft-n-min-adaptive"}, "N",
+ string_format("minimum adaptive MTP draft depth; the depth starts here and never drops below it (default: %d)", params.speculative.draft.n_min_adaptive),
+ [](common_params & params, int value) {
+ params.speculative.draft.n_min_adaptive = value;
+ }
+ ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_N_MIN_ADAPTIVE"));
+
+ add_opt(common_arg(
+ {"--spec-chain"}, "0|1|N",
+ "chained MTP drafting: all draft tokens in one GPU decode (default: off). Use --spec-chain N to enable and set depth (e.g. --spec-chain 8).",
+ [](common_params & params, const std::string & value) {
+ if (is_truthy(value)) {
+ params.speculative.draft.chain = true;
+ } else if (is_falsey(value)) {
+ params.speculative.draft.chain = false;
+ } else {
+ int n = std::stoi(value);
+ if (n < 1) throw std::invalid_argument("spec-chain depth must be >= 1");
+ params.speculative.draft.chain = true;
+ params.speculative.draft.n_max = n;
+ }
+ }
+ ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_CHAIN"));
+
+ add_opt(common_arg(
+ {"--gdn-replay"},
+ "[EXPERIMENTAL] for Gated DeltaNet models (Qwen3.5/3.5-MoE) with MTP rollback enabled: "
+ "record small per-token ingredients and replay them to reconstruct rolled-back state, "
+ "instead of eagerly storing a full state snapshot for every retained draft position "
+ "(default: off). Reduces VRAM and lets rollback avoid a full graph rebuild's worth of "
+ "redundant snapshot bandwidth; only implemented for GDN/KDA recurrent layers and the "
+ "CPU/CUDA backends so far.",
+ [](common_params & params) {
+ params.gdn_replay = true;
+ }
+ ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_GDN_REPLAY"));
+
add_opt(common_arg(
{"--spec-draft-p-split", "--draft-p-split"}, "P",
string_format("speculative decoding split probability (default: %.2f)", (double)params.speculative.draft.p_split),
@@ -4421,24 +4554,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
//
add_opt(common_arg(
- {"-mv", "--model-vocoder"}, "FNAME",
- "vocoder model for audio generation (default: unused)",
+ {"--tts-lang"}, "FNAME",
+ "language (ISO 639-1) for audio generation\n"
+ "see tts/README.md for per-model usage notes",
[](common_params & params, const std::string & value) {
- params.vocoder.model.path = value;
- }
- ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
- add_opt(common_arg(
- {"--tts-use-guide-tokens"},
- "Use guide tokens to improve TTS word recall",
- [](common_params & params) {
- params.vocoder.use_guide_tokens = true;
+ params.tts_lang = value;
}
- ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
+ ).set_examples({LLAMA_EXAMPLE_TTS}));
add_opt(common_arg(
{"--tts-speaker-file"}, "FNAME",
"speaker file path for audio generation",
[](common_params & params, const std::string & value) {
- params.vocoder.speaker_file = value;
+ params.tts_speaker_file = value;
}
).set_examples({LLAMA_EXAMPLE_TTS}));
@@ -4558,16 +4685,6 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
).set_examples({LLAMA_EXAMPLE_DEBUG}));
// presets
- add_opt(common_arg(
- {"--tts-oute-default"},
- string_format("use default OuteTTS models (note: can download weights from the internet)"),
- [](common_params & params) {
- params.model.hf_repo = "OuteAI/OuteTTS-0.2-500M-GGUF";
- params.model.hf_file = "OuteTTS-0.2-500M-Q8_0.gguf";
- params.vocoder.model.hf_repo = "ggml-org/WavTokenizer";
- params.vocoder.model.hf_file = "WavTokenizer-Large-75-F16.gguf";
- }
- ).set_examples({LLAMA_EXAMPLE_TTS}));
add_opt(common_arg(
{"--embd-gemma-default"},
diff --git a/common/arg.h b/common/arg.h
index 8f609e356fe2..44b9e887cfb9 100644
--- a/common/arg.h
+++ b/common/arg.h
@@ -137,7 +137,6 @@ void common_params_add_preset_options(std::vector & args);
struct common_models_handler {
common_download_hf_plan plan;
common_download_hf_plan plan_spec;
- common_download_hf_plan plan_voc;
common_download_opts opts;
};
diff --git a/common/chat.cpp b/common/chat.cpp
index 2b013a9b0bff..a4b217091c30 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -920,6 +920,10 @@ static std::string common_chat_template_direct_apply_impl(
bool enabled = inp["preserve_reasoning"].get();
jinja::caps_apply_preserve_reasoning(ctx, enabled);
}
+ if (inp.contains("reasoning_effort") && inp["reasoning_effort"].is_string() && !inp["reasoning_effort"].empty()) {
+ std::string reasoning_effort = inp["reasoning_effort"].get();
+ jinja::caps_apply_reasoning_effort(ctx, reasoning_effort);
+ }
jinja::global_from_json(ctx, inp, inputs.mark_input);
@@ -1900,7 +1904,7 @@ static common_chat_params common_chat_params_init_lfm2(const common_chat_templat
auto reasoning = p.eps();
if (extract_reasoning) {
- // Allow optional whitespace before - some models emit a
+ // Allow optional whitespace before — some models emit a
// newline between the generation prompt and the thinking tag.
reasoning = p.optional(p.space() + THINK_START + p.reasoning(p.until(THINK_END)) + THINK_END);
}
@@ -2258,7 +2262,7 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
}
if (extract_reasoning && inputs.enable_thinking) {
- // Allow optional whitespace before - some models emit a
+ // Allow optional whitespace before — some models emit a
// newline between the generation prompt and the thinking tag.
reasoning = p.optional(p.space() + THINK_START + p.reasoning(p.until(THINK_END)) + THINK_END);
reasoning_with_tc = THINK_START +
@@ -2650,6 +2654,119 @@ static common_chat_params common_chat_params_init_cohere2moe(const common_chat_t
return data;
}
+// Inkling / TML typed-content-block parser: <|end_message|> separates blocks within a turn,
+// <|content_model_end_sampling|> is the sole end-of-generation token (mirrors sglang TmlDetector).
+static common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl,
+ const autoparser::generation_params & inputs) {
+ common_chat_params data;
+
+ const std::string MSG_MODEL = "<|message_model|>";
+ const std::string MSG_USER = "<|message_user|>";
+ const std::string MSG_SYSTEM = "<|message_system|>";
+ const std::string MSG_TOOL = "<|message_tool|>";
+ const std::string THINK = "<|content_thinking|>";
+ const std::string TEXT = "<|content_text|>";
+ const std::string END_MESSAGE = "<|end_message|>";
+ const std::string END_SAMPLING = "<|content_model_end_sampling|>";
+ const std::string INVOKE_TOOL = "<|content_invoke_tool_json|>";
+
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
+ data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
+ data.supports_thinking = true;
+ data.thinking_start_tag = THINK;
+ data.thinking_end_tags = {END_MESSAGE};
+ data.preserved_tokens = {
+ MSG_MODEL, MSG_USER, MSG_SYSTEM, MSG_TOOL,
+ THINK, TEXT, END_MESSAGE, END_SAMPLING, INVOKE_TOOL,
+ };
+
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
+ data.message_delimiters = {
+ { COMMON_CHAT_ROLE_ASSISTANT, MSG_MODEL },
+ { COMMON_CHAT_ROLE_USER, MSG_USER },
+ { COMMON_CHAT_ROLE_SYSTEM, MSG_SYSTEM },
+ { COMMON_CHAT_ROLE_TOOL, MSG_TOOL },
+ };
+
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
+
+ if (inputs.has_continuation()) {
+ const auto & msg = inputs.continue_msg;
+
+ data.generation_prompt = MSG_MODEL + THINK + msg.reasoning_content;
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
+ data.generation_prompt += END_MESSAGE + TEXT + msg.render_content();
+ }
+
+ data.prompt += data.generation_prompt;
+ }
+
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
+ auto generation_prompt = p.literal(MSG_MODEL);
+ auto end = p.end();
+
+ // thinking block; may also reappear mid-turn (after content), so it is both an optional
+ // prefix and a choice inside the block loops. With reasoning_format=NONE keep it
+ // (markers included) inline as content
+ common_peg_parser reasoning_block = p.eps();
+ if (extract_reasoning) {
+ reasoning_block = p.literal(THINK) +
+ p.reasoning(p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING })) +
+ p.optional(p.literal(END_MESSAGE));
+ } else {
+ reasoning_block = p.content(p.literal(THINK) +
+ p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING }) +
+ p.optional(p.literal(END_MESSAGE)));
+ }
+ auto reasoning = p.optional(reasoning_block);
+
+ // TML re-emits <|message_model|> before each content block; a turn may contain several
+ // text blocks (one per content part), so the block repeats and bodies concatenate.
+ // THINK stops the content scan so a mid-turn thinking block is never leaked as text
+ auto text_block = p.optional(p.literal(MSG_MODEL)) +
+ p.optional(p.literal(TEXT)) +
+ p.content(p.until_one_of({ THINK, END_MESSAGE, END_SAMPLING })) +
+ p.optional(p.literal(END_MESSAGE));
+ auto text_content = p.one_or_more(p.choice({ reasoning_block, text_block }));
+
+ if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
+ return generation_prompt + reasoning + text_content +
+ p.optional(p.literal(END_SAMPLING)) + end;
+ }
+
+ // each call is its own block (role opener + bare name echo + JSON section);
+ // force_tool_calls=true makes the JSON section required so a pure-text answer fails the
+ // block cleanly; parallel calls are separate blocks, hence repeat + parallel=false
+ auto tool_section = p.standard_json_tools(
+ INVOKE_TOOL, END_MESSAGE, inputs.tools, /* parallel_tool_calls = */ false,
+ /* force_tool_calls = */ true,
+ /* name_key = */ "name",
+ /* args_key = */ "args",
+ /* array_wrapped = */ false);
+ // the name-echo scan must stop at any block marker: a greedy until(INVOKE_TOOL) returns
+ // NEED_MORE_INPUT mid-stream, which choice() treats as a match and shadows the text branch
+ auto tool_block = p.optional(p.literal(MSG_MODEL)) +
+ p.until_one_of({ INVOKE_TOOL, TEXT, THINK, END_MESSAGE, END_SAMPLING }) +
+ tool_section;
+ auto tool_calls = inputs.parallel_tool_calls ? p.one_or_more(tool_block) : tool_block;
+ // turns may interleave narration, thinking and calls; parse block-by-block (tool block
+ // first) since a whole-body choice would let the text branch swallow tool blocks into
+ // visible content
+ auto mixed_body = p.one_or_more(p.choice({ tool_block, reasoning_block, text_block }));
+ auto body = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED
+ ? tool_calls
+ : mixed_body;
+
+ return generation_prompt + reasoning + body +
+ p.optional(p.literal(END_SAMPLING)) + end;
+ });
+
+ data.parser = parser.save();
+
+ return data;
+}
+
static common_chat_params common_chat_params_init_minimax_m3(const common_chat_template & tmpl,
const autoparser::generation_params & inputs) {
common_chat_params data;
@@ -3273,288 +3390,145 @@ static common_chat_params common_chat_params_init_minicpm5(const common_chat_tem
return data;
}
-// Inkling / TML typed-content-block parser: <|end_message|> separates blocks within a turn,
-// <|content_model_end_sampling|> is the sole end-of-generation token (mirrors sglang TmlDetector).
-static common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl,
- const autoparser::generation_params & inputs) {
+// An assistant turn is rendered as one or more messages, each
+// "<|start|>assistant to=<|message|>{content}{END}" where END is
+// <|eom|> (more messages follow) or <|eot|> (end of turn):
+// - chain-of-thought: to=self, terminated by <|eom|>
+// - final answer: to=user, terminated by <|eot|>
+// The generation prompt is just "<|start|>assistant"; the model emits its own
+// " to=...<|message|>".
+static common_chat_params common_chat_params_init_muse_glimmer(const common_chat_template & tmpl,
+ const autoparser::generation_params & inputs) {
common_chat_params data;
- const std::string MSG_MODEL = "<|message_model|>";
- const std::string MSG_USER = "<|message_user|>";
- const std::string MSG_SYSTEM = "<|message_system|>";
- const std::string MSG_TOOL = "<|message_tool|>";
- const std::string THINK = "<|content_thinking|>";
- const std::string TEXT = "<|content_text|>";
- const std::string END_MESSAGE = "<|end_message|>";
- const std::string END_SAMPLING = "<|content_model_end_sampling|>";
- const std::string INVOKE_TOOL = "<|content_invoke_tool_json|>";
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
+ data.generation_prompt = "<|start|>assistant";
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
+ data.supports_thinking = true;
- data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
- data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
- data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
- data.supports_thinking = true;
- data.thinking_start_tag = THINK;
- data.thinking_end_tags = {END_MESSAGE};
- data.preserved_tokens = {
- MSG_MODEL, MSG_USER, MSG_SYSTEM, MSG_TOOL,
- THINK, TEXT, END_MESSAGE, END_SAMPLING, INVOKE_TOOL,
+ data.preserved_tokens = {
+ "<|start|>", "<|message|>", "<|eom|>", "<|eot|>",
+ // ATEM tool-call markup emitted on " to=" turns.
+ "", "",
+ "", "",
};
- auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
data.message_delimiters = {
- { COMMON_CHAT_ROLE_ASSISTANT, MSG_MODEL },
- { COMMON_CHAT_ROLE_USER, MSG_USER },
- { COMMON_CHAT_ROLE_SYSTEM, MSG_SYSTEM },
- { COMMON_CHAT_ROLE_TOOL, MSG_TOOL },
+ { COMMON_CHAT_ROLE_ASSISTANT, "<|start|>assistant" },
+ { COMMON_CHAT_ROLE_USER, "<|start|>user" },
+ { COMMON_CHAT_ROLE_SYSTEM, "<|start|>system" },
+ { COMMON_CHAT_ROLE_TOOL, "<|start|>tool" },
};
- auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
-
if (inputs.has_continuation()) {
const auto & msg = inputs.continue_msg;
- data.generation_prompt = MSG_MODEL + THINK + msg.reasoning_content;
+ data.generation_prompt = "<|start|>assistant to=self<|message|>" + msg.reasoning_content;
if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
- data.generation_prompt += END_MESSAGE + TEXT + msg.render_content();
+ data.generation_prompt += "<|eom|><|start|>assistant to=user<|message|>" + msg.render_content();
}
data.prompt += data.generation_prompt;
}
- auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
- auto generation_prompt = p.literal(MSG_MODEL);
- auto end = p.end();
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
- // thinking block; may also reappear mid-turn (after content), so it is both an optional
- // prefix and a choice inside the block loops. With reasoning_format=NONE keep it
- // (markers included) inline as content
- common_peg_parser reasoning_block = p.eps();
- if (extract_reasoning) {
- reasoning_block = p.literal(THINK) +
- p.reasoning(p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING })) +
- p.optional(p.literal(END_MESSAGE));
- } else {
- reasoning_block = p.content(p.literal(THINK) +
- p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING }) +
- p.optional(p.literal(END_MESSAGE)));
- }
- auto reasoning = p.optional(reasoning_block);
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
+ // Constrained grammar whenever tools are offered.
+ auto include_grammar = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
- // TML re-emits <|message_model|> before each content block; a turn may contain several
- // text blocks (one per content part), so the block repeats and bodies concatenate.
- // THINK stops the content scan so a mid-turn thinking block is never leaked as text
- auto text_block = p.optional(p.literal(MSG_MODEL)) +
- p.optional(p.literal(TEXT)) +
- p.content(p.until_one_of({ THINK, END_MESSAGE, END_SAMPLING })) +
- p.optional(p.literal(END_MESSAGE));
- auto text_content = p.one_or_more(p.choice({ reasoning_block, text_block }));
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
+ auto start = p.rule("start", p.literal("<|start|>assistant"));
- if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
- return generation_prompt + reasoning + text_content +
- p.optional(p.literal(END_SAMPLING)) + end;
+ if (!extract_reasoning && !include_grammar) {
+ return start + p.content(p.rest());
}
- // each call is its own block (role opener + bare name echo + JSON section);
- // force_tool_calls=true makes the JSON section required so a pure-text answer fails the
- // block cleanly; parallel calls are separate blocks, hence repeat + parallel=false
- auto tool_section = p.standard_json_tools(
- INVOKE_TOOL, END_MESSAGE, inputs.tools, /* parallel_tool_calls = */ false,
- /* force_tool_calls = */ true,
- /* name_key = */ "name",
- /* args_key = */ "args",
- /* array_wrapped = */ false);
- // the name-echo scan must stop at any block marker: a greedy until(INVOKE_TOOL) returns
- // NEED_MORE_INPUT mid-stream, which choice() treats as a match and shadows the text branch
- auto tool_block = p.optional(p.literal(MSG_MODEL)) +
- p.until_one_of({ INVOKE_TOOL, TEXT, THINK, END_MESSAGE, END_SAMPLING }) +
- tool_section;
- auto tool_calls = inputs.parallel_tool_calls ? p.one_or_more(tool_block) : tool_block;
- // turns may interleave narration, thinking and calls; parse block-by-block (tool block
- // first) since a whole-body choice would let the text branch swallow tool blocks into
- // visible content
- auto mixed_body = p.one_or_more(p.choice({ tool_block, reasoning_block, text_block }));
- auto body = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED
- ? tool_calls
- : mixed_body;
-
- return generation_prompt + reasoning + body +
- p.optional(p.literal(END_SAMPLING)) + end;
- });
-
- data.parser = parser.save();
-
- return data;
-}
-
-static common_chat_params common_chat_params_init_laguna(const common_chat_template & tmpl,
- const autoparser::generation_params & inputs) {
- common_chat_params data;
-
- data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
- data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
- data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
- data.supports_thinking = true;
- data.thinking_start_tag = "";
- data.thinking_end_tags = {""};
- data.preserved_tokens = {
- "", "",
- "", "",
- "", "",
- "", "",
- "", "",
- };
-
- //
ends the assistant turn. The single eot token (24) handles
- // this when sampled directly, but the model occasionally emits the
- // multi-token spelling; register it as a stop so generation always halts.
- data.additional_stops.push_back("");
-
- const std::string THINK_START = "";
- const std::string THINK_END = "";
- const std::string CALL_START = "";
- const std::string CALL_END = "";
- const std::string KEY_START = "";
- const std::string KEY_END = "";
- const std::string VAL_START = "";
- const std::string VAL_END = "";
-
- auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
- auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
- auto include_grammar = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
-
- auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
- auto end = p.end();
-
- // The framework prepends data.generation_prompt to the parsed output:
- // "\n" followed by the opening (thinking enabled) or
- // (disabled). Consume it, then capture reasoning. The model's
- // output therefore starts with the reasoning text (no leading ).
- const std::string GEN_PROMPT = "\n";
- auto head = p.eps();
- if (extract_reasoning && inputs.enable_thinking) {
- // The model normally closes reasoning with before a tool
- // call, but sometimes emits directly without it.
- // Terminate reasoning on whichever marker comes first so the call is
- // not swallowed into reasoning_content; consume if present.
- head = p.literal(GEN_PROMPT + THINK_START) +
- p.reasoning(p.until_one_of({ THINK_END, CALL_START })) +
- p.optional(p.literal(THINK_END));
- } else if (extract_reasoning) {
- head = p.literal(GEN_PROMPT + THINK_END);
+ if (extract_reasoning) {
+ p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>"));
} else {
- head = p.literal(GEN_PROMPT) +
- p.optional(p.literal(THINK_START)) + p.optional(p.literal(THINK_END));
+ p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>"));
}
+ auto analysis = p.ref("analysis");
- if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
- return head + p.content(p.until_one_of({ "" })) +
- p.optional(p.literal("")) + p.space() + end;
- }
+ auto recipient = p.optional(p.literal(" to=user"));
+ auto final_msg = p.rule("final", recipient + p.literal("<|message|>") + p.content(p.until("<|eot|>")));
- auto tool_choice = p.choice();
- foreach_function(inputs.tools, [&](const json & tool) {
- const auto & function = tool.at("function");
- std::string name = function.at("name");
- auto params = function.contains("parameters") ? function.at("parameters") : json::object();
- const auto & props = params.contains("properties") ? params.at("properties") : json::object();
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
+ auto string_value = p.ac(
+ p.tool_arg_string_value(p.until("")) + p.tool_arg_close(p.literal("")),
+ "");
- std::set required;
- if (params.contains("required")) {
- params.at("required").get_to(required);
- }
- auto schema_info = common_schema_info();
- schema_info.resolve_refs(params);
+ auto tool_choice = p.choice();
+ foreach_function(inputs.tools, [&](const json & tool) {
+ const auto & function = tool.at("function");
+ const std::string name = function.at("name");
+ auto params = function.contains("parameters") ? function.at("parameters") : json::object();
- std::vector required_parsers;
- std::vector optional_parsers;
- for (const auto & [param_name, param_schema] : props.items()) {
- bool is_required = required.find(param_name) != required.end();
- bool is_string = schema_info.resolves_to_string(param_schema);
-
- // name\nVALUE
- auto arg = p.tool_arg(
- p.tool_arg_open(
- p.literal(KEY_START) + p.tool_arg_name(p.literal(param_name)) + p.literal(KEY_END) +
- p.space() + p.literal(VAL_START)) +
- (is_string
- ? p.tool_arg_string_value(p.until(VAL_END))
- : p.tool_arg_json_value(p.schema(p.json(),
- "tool-" + name + "-arg-" + param_name + "-schema",
- param_schema, false))) +
- p.tool_arg_close(p.literal(VAL_END)));
-
- auto named_arg = p.rule("tool-" + name + "-arg-" + param_name, arg);
- if (is_required) {
- required_parsers.push_back(named_arg);
- } else {
- optional_parsers.push_back(named_arg);
- }
- }
+ auto args = p.eps();
+ if (params.contains("properties") && params.at("properties").is_object() && !params.at("properties").empty()) {
+ auto schema_info = common_schema_info();
+ schema_info.resolve_refs(params);
- common_peg_parser args_seq = p.eps();
- for (size_t i = 0; i < required_parsers.size(); i++) {
- if (i > 0) {
- args_seq = args_seq + p.space();
- }
- args_seq = args_seq + required_parsers[i];
- }
- if (!optional_parsers.empty()) {
- common_peg_parser any_opt = p.choice();
- for (const auto & opt : optional_parsers) {
- any_opt |= opt;
+ auto arg_choice = p.choice();
+ for (const auto & [prop_name, prop_schema] : params.at("properties").items()) {
+ auto value_parser = p.eps();
+ if (schema_info.resolves_to_string(prop_schema)) {
+ value_parser = string_value;
+ } else {
+ value_parser = p.tool_arg_json_value(
+ p.schema(p.json(), "tool-" + name + "-arg-" + prop_name + "-schema", prop_schema, false))
+ + p.tool_arg_close(p.literal(""));
+ }
+
+ auto arg_rule = p.tool_arg(
+ p.tool_arg_open(p.literal("")) +
+ value_parser);
+
+ arg_choice |= arg_rule;
+ }
+ args = p.zero_or_more(arg_choice + p.space());
}
- args_seq = args_seq + p.repeat(p.space() + any_opt, 0, -1);
- }
- // name\n {args}
- auto func_parser = p.tool(
- p.tool_open(p.literal(CALL_START) + p.tool_name(p.literal(name)) + p.literal("\n")) +
- args_seq + p.space() +
- p.tool_close(p.literal(CALL_END)));
+ auto tool_parser = p.tool(
+ p.tool_open(p.literal(" to=") + p.until("<|message|>") +
+ p.literal("<|message|>") + p.space() +
+ p.literal("") + p.space())
+ << p.tool_args(args)
+ << p.tool_close(p.literal("") + p.space() + p.literal("")));
- tool_choice |= p.rule("tool-" + name, func_parser);
- });
+ tool_choice |= p.rule("tool-" + name, tool_parser);
+ });
- auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
- auto max_calls = inputs.parallel_tool_calls ? -1 : 1;
- // Mirror the kimi_k2 structure: each tool is followed by optional
- // whitespace, and the trigger rule ends with an optional
- // exit marker. This lets the (lazy) trigger rule COMPLETE once the model
- // emits the turn-end, so the grammar disengages instead of offering
- // another indefinitely (the parallel=true / max_calls=-1
- // loop). Space is a suffix (not prefix) to avoid ambiguity with the exit.
- auto tool_calls = p.rule("tool-calls",
- p.trigger_rule("tool-call",
- p.repeat(tool_choice + p.space(), min_calls, max_calls) +
- p.optional(p.literal(""))));
+ auto tool_calls = inputs.parallel_tool_calls
+ ? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice))
+ : p.trigger_rule("tool-call", tool_choice);
- auto content_before_tools = p.content(p.until(CALL_START));
- // After the tool call(s) the model may emit trailing text (Laguna is
- // wrapper-less, so a repetitive model can ramble past the final call).
- // Absorb anything up to the turn-end as content so a stray trailing
- // fragment does not fail the whole parse — mirrors the reference
- // implementation, which extracts the calls and ignores the remainder.
- auto trailing = p.content(p.until_one_of({ "" }));
+ if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
+ return p.zero_or_more(start + analysis) + start + tool_calls;
+ }
+ return p.zero_or_more(start + analysis) + start + (tool_calls | final_msg);
+ }
- return head + content_before_tools + tool_calls + trailing +
- p.optional(p.literal("")) + p.space() + end;
+ return p.zero_or_more(start + analysis) + start + final_msg;
});
data.parser = parser.save();
if (include_grammar) {
- data.grammar_lazy = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
+ data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
foreach_function(inputs.tools, [&](const json & tool) {
const auto & function = tool.at("function");
- auto schema = function.at("parameters");
+ auto schema = function.contains("parameters") ? function.at("parameters") : json::object();
builder.resolve_refs(schema);
});
parser.build_grammar(builder, data.grammar_lazy);
});
data.grammar_triggers = {
- { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "" }
+ { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
+ "<\\|start\\|>assistant( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" },
};
}
@@ -3583,22 +3557,18 @@ std::optional common_chat_try_specialized_template(
return common_chat_params_init_ministral_3(tmpl, params);
}
- // Laguna (poolside) - GLM-4-MoE-style tool calls with /
- // pairs, plus / role tags (distinct from GLM's
- // <|assistant|>). Covers both Laguna-XS.2 and Laguna-M.1.
- if (src.find("") != std::string::npos &&
- src.find("") != std::string::npos &&
- src.find("") != std::string::npos) {
- LOG_DBG("Using specialized template: Laguna\n");
- return common_chat_params_init_laguna(tmpl, params);
- }
-
// GPT-OSS - has unique channel-based structure that needs dedicated handler
if (src.find("<|channel|>") != std::string::npos) {
LOG_DBG("Using specialized template: GPT-OSS\n");
return common_chat_params_init_gpt_oss(tmpl, params);
}
+ // Muse Glimmer format using " to=" recipients and <|eom|>/<|eot|> message terminators.
+ if (src.find("") != std::string::npos && src.find("<|eom|>") != std::string::npos) {
+ LOG_DBG("Using specialized template: Muse Glimmer\n");
+ return common_chat_params_init_muse_glimmer(tmpl, params);
+ }
+
// Functionary v3.2 - uses recipient-based format with >>>recipient\n{content}
// Detection: template has ">>>all" for content and ">>>" prefix for tool calls
if (src.find(">>>all") != std::string::npos && src.find(">>>${recipient}") != std::string::npos) {
diff --git a/common/common.cpp b/common/common.cpp
index d11d4fd61dc4..3b50f27703e5 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -1242,15 +1242,60 @@ common_init_result::common_init_result(common_params & params, bool model_only)
auto mparams = common_model_params_to_llama(params);
auto cparams = common_context_params_to_llama(params);
- if (params.fit_params) {
+ if (params.fit_params && !common_params_should_fit_device_memory(params)) {
+ COM_INF("%s", "skipping device-memory auto-fit because a shared KV/compute arena is explicitly configured\n");
+ }
+ if (common_params_should_fit_device_memory(params)) {
COM_TRC("%s", "fitting params to device memory ...\n");
COM_TRC("%s", "(for bugs during this step try to reproduce them with -fit off, or provide --verbose logs if the bug only occurs with -fit on)\n");
- common_fit_params(params.model.path.c_str(), &mparams, &cparams,
+ // Snapshot the pre-fit state so a failed fit can be rolled back to a
+ // documented fallback instead of continuing with an unproven placement.
+ const llama_model_params mparams_before = mparams;
+ const llama_context_params cparams_before = cparams;
+ const std::vector tensor_split_before(
+ params.tensor_split, params.tensor_split + llama_max_devices());
+ const std::vector tbo_before =
+ params.tensor_buft_overrides;
+ const common_moe_cache_params moe_cache_before = params.moe_cache;
+
+ const common_params_fit_status fit_status = common_fit_params(
+ params.model.path.c_str(), &mparams, &cparams,
params.tensor_split,
params.tensor_buft_overrides.data(),
+ ¶ms.moe_cache,
params.fit_params_target.data(),
params.fit_params_min_ctx,
params.verbosity >= LOG_LEVEL_DEBUG ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_ERROR);
+ if (fit_status == COMMON_PARAMS_FIT_STATUS_ERROR) {
+ throw std::runtime_error(
+ "failed to fit parameters to device memory (hard error); retry with -fit off");
+ }
+ if (fit_status != COMMON_PARAMS_FIT_STATUS_SUCCESS) {
+ COM_ERR("%s", "fit could not prove a viable placement; restoring the pre-fit parameters\n");
+ mparams = mparams_before;
+ cparams = cparams_before;
+ std::copy(tensor_split_before.begin(), tensor_split_before.end(), params.tensor_split);
+ params.tensor_buft_overrides = tbo_before;
+ params.moe_cache = moe_cache_before;
+ // Re-point at the restored arrays (the override vector may have moved).
+ mparams.tensor_split = params.tensor_split;
+ mparams.tensor_buft_overrides = params.tensor_buft_overrides.empty()
+ ? nullptr : params.tensor_buft_overrides.data();
+ }
+ }
+
+ if (params.moe_cache.mode_explicit || params.moe_cache.fit_selected) {
+ const char * mode = params.moe_cache.mode == COMMON_MOE_CACHE_MODE_OFF ? "off" :
+ params.moe_cache.mode == COMMON_MOE_CACHE_MODE_AUTO ? "auto" :
+ params.moe_cache.mode == COMMON_MOE_CACHE_MODE_SOFT ? "soft" : "on";
+ const char * placement = params.moe_cache.fit_selected ? " placement=cache-aware-fit" : "";
+ if (params.moe_cache.mode == COMMON_MOE_CACHE_MODE_OFF) {
+ COM_INF("%s", "MoE cache: mode=off\n");
+ } else if (params.moe_cache.budget_mib > 0) {
+ COM_INF("MoE cache: mode=%s budget=%zu MiB/device%s; use -lv 4 for resolved backend state, actual pools, and statistics\n", mode, params.moe_cache.budget_mib, placement);
+ } else {
+ COM_INF("MoE cache: mode=%s budget=free-minus-reserve%s; use -lv 4 for resolved backend state, actual pools, and statistics\n", mode, placement);
+ }
}
llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
@@ -1308,23 +1353,12 @@ common_init_result::common_init_result(common_params & params, bool model_only)
params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
}
- //if (params.sampling.penalty_last_n == -1) {
- // LOG_TRC("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
- // params.sampling.penalty_last_n = llama_n_ctx(lctx);
- //}
-
- //if (params.sampling.dry_penalty_last_n == -1) {
- // LOG_TRC("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
- // params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
- //}
-
// init the backend samplers as part of the context creation
pimpl->samplers.resize(cparams.n_seq_max);
pimpl->samplers_seq_config.resize(cparams.n_seq_max);
- const int32_t n_ctx = cparams.n_ctx > 0 ? (int32_t) cparams.n_ctx : llama_model_n_ctx_train(model);
for (int i = 0; i < (int) cparams.n_seq_max; ++i) {
- pimpl->samplers[i].reset(common_sampler_init(model, params.sampling, n_ctx));
+ pimpl->samplers[i].reset(common_sampler_init(model, params.sampling));
pimpl->samplers_seq_config[i] = { i, common_sampler_get(pimpl->samplers[i].get()) };
}
@@ -1622,6 +1656,7 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
mparams.main_gpu = params.main_gpu;
mparams.split_mode = params.split_mode;
mparams.load_mode = params.load_mode;
+ mparams.tensor_read_lazy = params.tensor_read_lazy;
mparams.tensor_split = params.tensor_split;
mparams.check_tensors = params.check_tensors;
mparams.use_extra_bufts = !params.no_extra_bufts;
@@ -1644,7 +1679,8 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
mparams.progress_callback = params.load_progress_callback;
mparams.progress_callback_user_data = params.load_progress_callback_user_data;
mparams.no_alloc = params.no_alloc;
- mparams.load_mtp = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end();
+ mparams.load_mtp = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end() ||
+ std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP_ADAPTIVE) != params.speculative.types.end();
return mparams;
}
@@ -1656,9 +1692,17 @@ struct llama_context_params common_context_params_to_llama(const common_params &
cparams.n_seq_max = params.n_parallel;
cparams.n_outputs_max = params.n_outputs_max;
cparams.n_rs_seq = params.speculative.need_n_rs_seq();
+ cparams.gdn_replay = params.gdn_replay;
cparams.n_outputs_max = std::max(params.n_outputs_max, 0);
cparams.n_batch = params.n_batch;
cparams.n_ubatch = params.n_ubatch;
+
+ if (cparams.n_rs_seq > 0) {
+ const uint32_t n_batch_min = cparams.n_rs_seq + 2;
+ cparams.n_batch = std::max(cparams.n_batch, n_batch_min);
+ cparams.n_ubatch = std::max(cparams.n_ubatch, n_batch_min);
+ }
+
cparams.n_threads = params.cpuparams.n_threads;
cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
@@ -1684,10 +1728,31 @@ struct llama_context_params common_context_params_to_llama(const common_params &
cparams.type_k = params.cache_type_k;
cparams.type_v = params.cache_type_v;
+ cparams.kv_stream_arena_mib = params.kv_stream_arena_mib;
+
+ if (params.moe_cache.mode_explicit) {
+ switch (params.moe_cache.mode) {
+ case COMMON_MOE_CACHE_MODE_OFF:
+ cparams.moe_cache_mode = LLAMA_MOE_CACHE_MODE_OFF;
+ break;
+ case COMMON_MOE_CACHE_MODE_AUTO:
+ cparams.moe_cache_mode = LLAMA_MOE_CACHE_MODE_AUTO;
+ break;
+ case COMMON_MOE_CACHE_MODE_ON:
+ case COMMON_MOE_CACHE_MODE_SOFT:
+ cparams.moe_cache_mode = LLAMA_MOE_CACHE_MODE_ON;
+ break;
+ }
+ }
+ cparams.moe_cache_budget_mib = params.moe_cache.budget_mib;
return cparams;
}
+bool common_params_should_fit_device_memory(const common_params & params) {
+ return params.fit_params && params.kv_stream_arena_mib == 0;
+}
+
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const common_cpu_params & params) {
struct ggml_threadpool_params tpp;
diff --git a/common/common.h b/common/common.h
index f3f27bf812c9..0ee2fe38f297 100644
--- a/common/common.h
+++ b/common/common.h
@@ -172,6 +172,7 @@ enum common_speculative_type {
COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE, // standalone draft model speculative decoding
COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, // Eagle3 speculative decoding
COMMON_SPECULATIVE_TYPE_DRAFT_MTP, // Multi-token prediction
+ COMMON_SPECULATIVE_TYPE_DRAFT_MTP_ADAPTIVE, // MTP with adaptive draft depth
COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, // DFlash speculative decoding
COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, // DSpark speculative decoding (DFlash + Markov head)
COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, // simple self-speculative decoding based on n-grams
@@ -235,14 +236,14 @@ struct common_params_sampling {
float temp = 0.80f; // <= 0.0 to sample greedily, 0.0 to not output probabilities
float dynatemp_range = 0.00f; // 0.0 = disabled
float dynatemp_exponent = 1.00f; // controls how entropy maps to temperature in dynamic temperature sampler
- int32_t penalty_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
+ int32_t penalty_last_n = 64; // last n tokens to penalize (0 = disable penalty)
float penalty_repeat = 1.00f; // 1.0 = disabled
float penalty_freq = 0.00f; // 0.0 = disabled
float penalty_present = 0.00f; // 0.0 = disabled
float dry_multiplier = 0.0f; // 0.0 = disabled; DRY repetition penalty for tokens extending repetition:
float dry_base = 1.75f; // 0.0 = disabled; multiplier * base ^ (length of sequence before token - allowed length)
int32_t dry_allowed_length = 2; // tokens extending repetitions beyond this receive penalty
- int32_t dry_penalty_last_n = -1; // how many tokens to scan for repetitions (0 = disable penalty, -1 = context size)
+ int32_t dry_penalty_last_n = 64; // how many tokens to scan for repetitions (0 = disable penalty)
float adaptive_target = -1.0f; // select tokens near this probability (valid range 0.0 to 1.0; negative = disabled)
float adaptive_decay = 0.90f; // EMA decay for adaptation; history ≈ 1/(1-decay) tokens (0.0 - 0.99)
int32_t mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
@@ -324,10 +325,12 @@ struct common_params_model {
struct common_params_speculative_draft {
int32_t n_max = 3; // maximum number of tokens to draft during speculative decoding
int32_t n_min = 0; // minimum number of draft tokens to use for speculative decoding
+ int32_t n_min_adaptive = 3; // minimum adaptive MTP draft depth (also the starting depth)
float p_split = 0.1f; // speculative decoding split probability
float p_min = 0.0f; // minimum speculative decoding probability (greedy)
+ bool chain = false; // chained drafting: all n_max tokens in one GPU decode (MTP only)
bool backend_sampling = true; // offload draft sampling to the backend (default: on)
common_params_model mparams;
@@ -346,6 +349,12 @@ struct common_params_speculative_draft {
std::vector devices; // devices to use for offloading
std::vector tensor_buft_overrides;
+
+ bool eagle3 = false; // use EAGLE3 speculative decoding
+ bool dflash = false; // use DFlash speculative decoding
+ bool dflash_defer_injection = true; // defer encoder KV injection to draft time (set false for higher acceptance on some models)
+ int32_t n_ctx = 0; // draft context size
+
};
struct common_params_speculative_ngram_mod {
@@ -385,21 +394,15 @@ struct common_params_speculative {
uint32_t need_n_rs_seq() const {
bool needs_rs_seq = std::any_of(types.begin(), types.end(), [&](auto t) {
- return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK;
+ return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP ||
+ t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP_ADAPTIVE ||
+ t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK;
});
return needs_rs_seq ? draft.n_max : 0u;
}
};
-struct common_params_vocoder {
- struct common_params_model model;
-
- std::string speaker_file; // speaker file path
-
- bool use_guide_tokens = false; // enable guide tokens to improve TTS accuracy
-};
-
struct common_params_diffusion {
int32_t steps = 128;
bool visual_mode = false;
@@ -464,6 +467,20 @@ struct lr_opt {
struct ggml_opt_optimizer_params common_opt_lr_pars(void * userdata);
+enum common_moe_cache_mode {
+ COMMON_MOE_CACHE_MODE_OFF,
+ COMMON_MOE_CACHE_MODE_AUTO,
+ COMMON_MOE_CACHE_MODE_ON,
+ COMMON_MOE_CACHE_MODE_SOFT,
+};
+
+struct common_moe_cache_params {
+ common_moe_cache_mode mode = COMMON_MOE_CACHE_MODE_AUTO;
+ size_t budget_mib = 0;
+ bool mode_explicit = false;
+ bool fit_selected = false;
+};
+
struct common_params {
int32_t n_predict = -1; // max. number of new tokens to predict, -1 == no limit
int32_t n_ctx = 0; // context size, 0 == context the model was trained with
@@ -472,8 +489,10 @@ struct common_params {
int32_t n_keep = 0; // number of tokens to keep from initial prompt
int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited)
int32_t n_parallel = 1; // number of parallel sequences to decode
+ bool n_parallel_explicit = false; // true if -np/--parallel was passed on the command line
int32_t n_sequences = 1; // number of sequences to decode
int32_t n_outputs_max = 0; // max outputs in a batch (0 = n_batch)
+ bool gdn_replay = false; // DRC: ingredient-replay rollback for GDN models instead of full K-snapshots [EXPERIMENTAL]
int32_t grp_attn_n = 1; // group-attention factor
int32_t grp_attn_w = 512; // group-attention width
int32_t n_print = -1; // print token count every n tokens (-1 = disabled)
@@ -501,6 +520,8 @@ struct common_params {
enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER; // how to split the model across GPUs
enum llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP; // how to load the model
+ enum llama_tensor_read_lazy tensor_read_lazy = LLAMA_TENSOR_READ_LAZY_AUTO; // on-demand reading of tensors marked by the arch
+
common_cpu_params cpuparams;
common_cpu_params cpuparams_batch;
@@ -516,7 +537,6 @@ struct common_params {
struct common_params_sampling sampling;
struct common_params_speculative speculative;
- struct common_params_vocoder vocoder;
struct common_params_diffusion diffusion;
struct common_params_decision decision;
@@ -598,12 +618,14 @@ struct common_params {
bool check_tensors = false; // validate tensor data
bool no_op_offload = false; // globally disable offload host tensor operations to device
bool no_extra_bufts = false; // disable extra buffer types (used for weight repacking)
+ common_moe_cache_params moe_cache;
bool no_host = false; // bypass host buffer allowing extra buffers to be used
bool single_turn = false; // single turn chat conversation
ggml_type cache_type_k = GGML_TYPE_F16; // KV cache data type for the K
ggml_type cache_type_v = GGML_TYPE_F16; // KV cache data type for the V
+ uint32_t kv_stream_arena_mib = 0; // shared CUDA KV + compute arena, 0 = disabled [EXPERIMENTAL]
common_conversation_mode conversation_mode = COMMON_CONVERSATION_MODE_AUTO;
@@ -762,6 +784,10 @@ struct common_params {
void * load_progress_callback_user_data = NULL;
bool no_alloc = false; // Don't allocate model buffers
+ // TTS params
+ std::string tts_lang = "";
+ std::string tts_speaker_file = "";
+
bool is_gen_docs = false; // whether we are running inside llama-gen-docs
};
@@ -957,6 +983,8 @@ struct llama_model_params common_model_params_to_llama ( common_params
struct llama_context_params common_context_params_to_llama(const common_params & params);
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const common_cpu_params & params);
+bool common_params_should_fit_device_memory(const common_params & params);
+
// clear LoRA adapters from context, then apply new list of adapters
void common_set_adapter_lora(struct llama_context * ctx, std::vector & lora);
diff --git a/common/fit.cpp b/common/fit.cpp
index c82d066ad444..229e017f6d3e 100644
--- a/common/fit.cpp
+++ b/common/fit.cpp
@@ -1,14 +1,17 @@
#include "fit.h"
+#include "common.h"
#include "log.h"
+#include "../ggml/src/ggml-backend-moe-cache.h"
#include "../src/llama-ext.h"
+#include
#include
#include
-#include
#include
#include
+#include
#include
#include
@@ -26,6 +29,276 @@ class common_params_fit_exception : public std::runtime_error {
using std::runtime_error::runtime_error;
};
+const char * common_moe_cache_tensor_override_pattern() {
+ return "blk\\.\\d+\\.ffn_(up|down|gate_up|gate)_(ch|)exps";
+}
+
+struct common_moe_cache_fit_pool {
+ ggml_type type = GGML_TYPE_COUNT;
+ size_t expert_size = 0;
+ size_t pool_bytes = 0;
+ size_t tensor_bytes = 0;
+ size_t scratch_bytes = 0;
+};
+
+common_moe_cache_fit_result common_moe_cache_plan_fit(
+ const std::vector & device_inputs,
+ const std::vector & shapes,
+ size_t reserve_bytes,
+ size_t budget_bytes,
+ int min_devices,
+ size_t minimum_slab_bytes) {
+ common_moe_cache_fit_result result;
+
+ for (const common_moe_cache_fit_device_input & input : device_inputs) {
+ if (input.physical_device < 0 || input.free_bytes < 0 || input.used_bytes > INT64_MAX) {
+ result.reason = "device memory accounting overflowed";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+
+ size_t device_index = result.devices.size();
+ for (size_t candidate = 0; candidate < result.devices.size(); candidate++) {
+ if (result.devices[candidate].physical_device == input.physical_device) {
+ device_index = candidate;
+ break;
+ }
+ }
+ if (device_index == result.devices.size()) {
+ common_moe_cache_fit_device device;
+ device.physical_device = input.physical_device;
+ device.compute_capability = input.compute_capability;
+ device.free_bytes = input.free_bytes;
+ result.devices.push_back(device);
+ }
+
+ common_moe_cache_fit_device & device = result.devices[device_index];
+ device.free_bytes = std::min(device.free_bytes, input.free_bytes);
+ device.compute_capability = std::min(device.compute_capability, input.compute_capability);
+ if ((int64_t)input.used_bytes > INT64_MAX - device.used_bytes) {
+ result.reason = "device memory accounting overflowed";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ device.used_bytes += (int64_t)input.used_bytes;
+ }
+ if (result.devices.empty()) {
+ result.reason = "no selected device satisfies the cache hardware policy";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+
+ for (common_moe_cache_fit_device & device : result.devices) {
+ const int64_t projected_free = device.free_bytes - device.used_bytes;
+ if (projected_free <= 0 || (uint64_t)projected_free <= reserve_bytes) {
+ continue;
+ }
+ device.cache_bytes = (size_t)projected_free - reserve_bytes;
+ if (budget_bytes > 0) {
+ device.cache_bytes = std::min(device.cache_bytes, budget_bytes);
+ }
+ }
+
+ std::vector pools;
+ for (const common_moe_cache_fit_shape_input & shape : shapes) {
+ if (shape.tensor_bytes == 0 || shape.tensor_bytes > SIZE_MAX - result.expert_bytes) {
+ result.reason = "the routed expert tensor inventory overflowed";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ result.expert_bytes += shape.tensor_bytes;
+ if (!shape.cacheable) {
+ continue;
+ }
+ bool found = false;
+ for (common_moe_cache_fit_pool & pool : pools) {
+ if (pool.type == shape.type && pool.expert_size == shape.expert_size) {
+ pool.pool_bytes = std::max(pool.pool_bytes, shape.pool_bytes);
+ pool.tensor_bytes += shape.tensor_bytes;
+ pool.scratch_bytes = std::max(pool.scratch_bytes, shape.scratch_bytes);
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ pools.push_back({shape.type, shape.expert_size, shape.pool_bytes,
+ shape.tensor_bytes, shape.scratch_bytes});
+ }
+ }
+
+ size_t scratch_bytes = 0;
+ size_t supported_bytes = 0;
+ for (const common_moe_cache_fit_pool & pool : pools) {
+ if (pool.tensor_bytes < pool.pool_bytes) {
+ continue;
+ }
+ supported_bytes += pool.tensor_bytes;
+ scratch_bytes = std::max(scratch_bytes, pool.scratch_bytes);
+ }
+ if (supported_bytes == 0) {
+ result.reason = "no routed expert shape is cacheable";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ if (supported_bytes != result.expert_bytes) {
+ result.reason = "some routed expert weights would remain permanently uncached";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+
+ size_t minimum_pool_bytes = 0;
+ for (const common_moe_cache_fit_pool & pool : pools) {
+ if (pool.tensor_bytes < pool.pool_bytes) {
+ continue;
+ }
+ if (pool.pool_bytes > SIZE_MAX - minimum_pool_bytes) {
+ result.reason = "the minimum cache pool inventory overflowed";
+ return result;
+ }
+ minimum_pool_bytes += pool.pool_bytes;
+ }
+ minimum_pool_bytes = std::max(minimum_pool_bytes, minimum_slab_bytes);
+ if (minimum_pool_bytes > SIZE_MAX - scratch_bytes) {
+ result.reason = "the minimum cache pool inventory overflowed";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ result.minimum_device_bytes = scratch_bytes + minimum_pool_bytes;
+
+ int useful_devices = 0;
+ for (const common_moe_cache_fit_device & device : result.devices) {
+ if (device.cache_bytes < result.minimum_device_bytes) {
+ continue;
+ }
+ useful_devices++;
+ if (device.cache_bytes > SIZE_MAX - result.cache_bytes) {
+ result.cache_bytes = SIZE_MAX;
+ } else {
+ result.cache_bytes += device.cache_bytes;
+ }
+ }
+ if (useful_devices < min_devices) {
+ result.reason = "too few devices can hold the minimum expert pools";
+ LOG_INF("%s: MoE cache fit: %s (useful=%d, min=%d, min_device_bytes=%zu MiB)\n", __func__,
+ result.reason.c_str(), useful_devices, min_devices,
+ result.minimum_device_bytes >> 20);
+ return result;
+ }
+
+ result.feasible = true;
+ result.reason = "cache pools are feasible";
+ return result;
+}
+
+static common_moe_cache_fit_result common_moe_cache_evaluate_fit(
+ const common_moe_cache_params * params,
+ const std::vector & tensors,
+ const std::vector & devices,
+ const std::vector & memory,
+ const std::vector & margins) {
+ common_moe_cache_fit_result result;
+ if (!params || params->mode == COMMON_MOE_CACHE_MODE_OFF) {
+ result.reason = "disabled";
+ return result;
+ }
+ // Probe the provider that owns the fitted devices; fall back to the
+ // thread's active provider (first registered) when no device is given.
+ ggml_moe_cache_api api = ggml_moe_cache_active();
+ if (!devices.empty()) {
+ const ggml_moe_cache_api owned =
+ ggml_moe_cache_get(ggml_backend_dev_backend_reg(devices[0]));
+ if (owned.owner) {
+ api = owned;
+ }
+ }
+ if (!api.query_config || !api.query_device || !api.query_shape) {
+ result.reason = "no cache provider is loaded";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+
+ int automatic = -1;
+ if (params->mode_explicit) {
+ automatic = params->mode == COMMON_MOE_CACHE_MODE_AUTO ? 1 : 0;
+ }
+ ggml_moe_cache_config config = {};
+ if (!api.query_config(automatic, params->budget_mib, &config)) {
+ result.reason = "the cache provider is disabled";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ if (tensors.empty()) {
+ result.reason = "the model has no routed expert weight tensors";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ if (memory.size() != devices.size() + 1 || margins.size() != devices.size()) {
+ result.reason = "the fitted device inventory changed";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+
+ std::vector device_inputs;
+ size_t min_expert_bytes = 0;
+ for (size_t index = 0; index < devices.size(); index++) {
+ ggml_moe_cache_device_caps caps = {};
+ if (!api.query_device(devices[index], &config, &caps)) {
+ continue;
+ }
+ if (margins[index] < 0 || memory[index].free < margins[index]) {
+ result.reason = "the fitted device margin exceeds free memory";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ device_inputs.push_back({caps.physical_device, caps.compute_capability,
+ memory[index].free - margins[index], memory[index].mb.total()});
+ min_expert_bytes = std::max(min_expert_bytes, caps.min_expert_bytes);
+ }
+
+ std::vector shape_inputs;
+ shape_inputs.reserve(tensors.size());
+ for (const llama_moe_tensor_info & tensor : tensors) {
+ if (tensor.n_expert <= 0 || tensor.expert_size == 0 ||
+ (uint64_t)tensor.n_expert > SIZE_MAX / tensor.expert_size) {
+ result.reason = "the model has an invalid routed expert tensor size";
+ LOG_INF("%s: MoE cache fit: %s\n", __func__, result.reason.c_str());
+ return result;
+ }
+ const size_t tensor_bytes = (size_t)tensor.n_expert * tensor.expert_size;
+ ggml_moe_cache_shape_caps caps = {};
+ const bool cacheable = tensor.expert_size >= min_expert_bytes &&
+ api.query_shape(tensor.type, tensor.n_input, tensor.n_output,
+ tensor.n_expert, tensor.expert_size, &caps);
+ shape_inputs.push_back({tensor.type, tensor.expert_size, tensor_bytes,
+ caps.scratch_bytes, caps.pool_bytes, cacheable});
+ }
+
+ return common_moe_cache_plan_fit(
+ device_inputs, shape_inputs, config.reserve_bytes, config.budget_bytes,
+ config.min_devices, config.minimum_slab_bytes);
+}
+
+struct common_fit_logger_guard {
+ ggml_log_callback original_callback;
+ void * original_user_data;
+ ggml_log_level min_level;
+
+ explicit common_fit_logger_guard(ggml_log_level min_level) : min_level(min_level) {
+ llama_log_get(&original_callback, &original_user_data);
+ llama_log_set(callback, this);
+ }
+
+ ~common_fit_logger_guard() {
+ llama_log_set(original_callback, original_user_data);
+ }
+
+ static void callback(ggml_log_level level, const char * text, void * user_data) {
+ const common_fit_logger_guard * guard = (const common_fit_logger_guard *) user_data;
+ const ggml_log_level level_eff = level >= guard->min_level ? level : GGML_LOG_LEVEL_DEBUG;
+ guard->original_callback(level_eff, text, guard->original_user_data);
+ }
+};
+
static std::vector common_get_device_memory_data_impl(
const char * path_model,
const llama_model_params * mparams,
@@ -34,45 +307,34 @@ static std::vector common_get_device_memory_data_impl(
uint32_t & hp_ngl,
uint32_t & hp_n_ctx_train,
uint32_t & hp_n_expert,
- ggml_log_level log_level) {
- struct user_data_t {
- struct {
- ggml_log_callback callback;
- void * user_data;
- } original_logger;
- ggml_log_level min_level; // prints below this log level go to debug log
- };
- user_data_t ud;
- llama_log_get(&ud.original_logger.callback, &ud.original_logger.user_data);
- ud.min_level = log_level;
-
- llama_log_set([](ggml_log_level level, const char * text, void * user_data) {
- const user_data_t * ud = (const user_data_t *) user_data;
- const ggml_log_level level_eff = level >= ud->min_level ? level : GGML_LOG_LEVEL_DEBUG;
- ud->original_logger.callback(level_eff, text, ud->original_logger.user_data);
- }, &ud);
+ ggml_log_level log_level,
+ std::vector * moe_tensors = nullptr,
+ llama_context * ctx_parent = nullptr) {
+ common_fit_logger_guard logger_guard(log_level);
llama_model_params mparams_copy = *mparams;
mparams_copy.no_alloc = true;
mparams_copy.load_mode = LLAMA_LOAD_MODE_NONE;
- llama_model * model = llama_model_load_from_file(path_model, mparams_copy);
+ llama_model_ptr model(llama_model_load_from_file(path_model, mparams_copy));
if (model == nullptr) {
- llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
throw std::runtime_error("failed to load model");
}
- llama_context * ctx = llama_init_from_model(model, *cparams);
+ llama_context_params cparams_copy = *cparams;
+ if (ctx_parent != nullptr) {
+ cparams_copy.ctx_other = ctx_parent;
+ }
+
+ llama_context_ptr ctx(llama_init_from_model(model.get(), cparams_copy));
if (ctx == nullptr) {
- llama_model_free(model);
- llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
throw std::runtime_error("failed to create llama_context from model");
}
- const size_t nd = llama_model_n_devices(model);
+ const size_t nd = llama_model_n_devices(model.get());
std::vector ret(nd + 1);
- llama_memory_breakdown memory_breakdown = llama_get_memory_breakdown(ctx);
+ llama_memory_breakdown memory_breakdown = llama_get_memory_breakdown(ctx.get());
for (const auto & [buft, mb] : memory_breakdown) {
if (ggml_backend_buft_is_host(buft)) {
@@ -87,7 +349,7 @@ static std::vector common_get_device_memory_data_impl(
continue;
}
for (size_t i = 0; i < nd; i++) {
- if (dev == llama_model_get_device(model, i)) {
+ if (dev == llama_model_get_device(model.get(), i)) {
ret[i].mb.model += mb.model;
ret[i].mb.context += mb.context;
ret[i].mb.compute += mb.compute;
@@ -108,7 +370,7 @@ static std::vector common_get_device_memory_data_impl(
ret.back().total = total;
}
for (size_t i = 0; i < nd; i++) {
- ggml_backend_dev_t dev = llama_model_get_device(model, i);
+ ggml_backend_dev_t dev = llama_model_get_device(model.get(), i);
size_t free;
size_t total;
@@ -132,19 +394,25 @@ static std::vector common_get_device_memory_data_impl(
}
devs.clear();
- for (int i = 0; i < llama_model_n_devices(model); i++) {
- devs.push_back(llama_model_get_device(model, i));
+ for (int i = 0; i < llama_model_n_devices(model.get()); i++) {
+ devs.push_back(llama_model_get_device(model.get(), i));
}
- hp_ngl = llama_model_n_layer(model) + llama_model_n_layer_nextn(model);
- hp_n_ctx_train = llama_model_n_ctx_train(model);
- hp_n_expert = llama_model_n_expert(model);
-
- common_memory_breakdown_print(ctx);
+ hp_ngl = llama_model_n_layer(model.get());
+ if (mparams->load_mtp) {
+ hp_ngl += llama_model_n_layer_nextn(model.get());
+ }
+ hp_n_ctx_train = llama_model_n_ctx_train(model.get());
+ hp_n_expert = llama_model_n_expert(model.get());
+
+ if (moe_tensors) {
+ const size_t count = llama_model_get_moe_tensor_info(model.get(), nullptr, 0);
+ moe_tensors->resize(count);
+ const size_t written = llama_model_get_moe_tensor_info(model.get(), moe_tensors->data(), moe_tensors->size());
+ GGML_ASSERT(written == count);
+ }
- llama_free(ctx);
- llama_model_free(model);
- llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
+ common_memory_breakdown_print(ctx.get());
return ret;
}
@@ -172,10 +440,53 @@ common_device_memory_data_vec common_get_device_memory_data(
return ret;
}
+common_device_memory_data_vec common_get_device_memory_data_with_parent(
+ const char * path_model,
+ const llama_model_params * mparams,
+ const llama_context_params * cparams,
+ const char * path_parent,
+ const llama_model_params * mparams_parent,
+ const llama_context_params * cparams_parent,
+ std::vector & devs,
+ uint32_t & hp_ngl,
+ uint32_t & hp_n_ctx_train,
+ uint32_t & hp_n_expert,
+ ggml_log_level log_level) {
+ common_fit_logger_guard logger_guard(log_level);
+
+ llama_model_params mparams_parent_copy = *mparams_parent;
+ mparams_parent_copy.no_alloc = true;
+ mparams_parent_copy.load_mode = LLAMA_LOAD_MODE_NONE;
+
+ llama_model_ptr model_parent(llama_model_load_from_file(path_parent, mparams_parent_copy));
+ if (model_parent == nullptr) {
+ throw std::runtime_error("failed to load parent model");
+ }
+
+ llama_context_ptr ctx_parent(llama_init_from_model(model_parent.get(), *cparams_parent));
+ if (ctx_parent == nullptr) {
+ throw std::runtime_error("failed to create parent llama_context");
+ }
+
+ std::vector impl = common_get_device_memory_data_impl(
+ path_model, mparams, cparams, devs, hp_ngl, hp_n_ctx_train, hp_n_expert,
+ log_level, nullptr, ctx_parent.get());
+
+ common_device_memory_data_vec ret(impl.size());
+ for (size_t i = 0; i < impl.size(); i++) {
+ ret[i].total = impl[i].total;
+ ret[i].free = impl[i].free;
+ ret[i].model = impl[i].mb.model;
+ ret[i].context = impl[i].mb.context;
+ ret[i].compute = impl[i].mb.compute;
+ }
+ return ret;
+}
+
static void common_params_fit_impl(
const char * path_model, struct llama_model_params * mparams, struct llama_context_params * cparams,
float * tensor_split, struct llama_model_tensor_buft_override * tensor_buft_overrides,
- size_t * margins_s, uint32_t n_ctx_min, enum ggml_log_level log_level) {
+ common_moe_cache_params * moe_cache, size_t * margins_s, uint32_t n_ctx_min, enum ggml_log_level log_level) {
if (mparams->split_mode == LLAMA_SPLIT_MODE_TENSOR) {
throw common_params_fit_exception("llama_params_fit is not implemented for SPLIT_MODE_TENSOR, abort");
}
@@ -187,13 +498,28 @@ static void common_params_fit_impl(
uint32_t hp_ngl = 0; // hparams.n_gpu_layers
uint32_t hp_nct = 0; // hparams.n_ctx_train
uint32_t hp_nex = 0; // hparams.n_expert
+ std::vector moe_tensors;
+
+ if (moe_cache) {
+ moe_cache->fit_selected = false;
+ }
// step 1: get data for default parameters and check whether any changes are necessary in the first place
LOG_TRC("%s: getting device memory data for initial parameters:\n", __func__);
- const dmds_t dmds_full = common_get_device_memory_data_impl(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
+ const dmds_t dmds_full = common_get_device_memory_data_impl(
+ path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex,
+ log_level, &moe_tensors);
const size_t nd = devs.size(); // number of devices
+ auto log_stock_fit = [&] {
+ if (moe_cache && moe_cache->mode != COMMON_MOE_CACHE_MODE_OFF &&
+ !moe_tensors.empty() &&
+ (!mparams->tensor_buft_overrides || !mparams->tensor_buft_overrides[0].pattern)) {
+ LOG_INF("%s: MoE cache fit kept stock placement because the complete model already meets the fit targets\n", __func__);
+ }
+ };
+
std::vector margins; // this function uses int64_t rather than size_t for memory sizes to more conveniently handle deficits
margins.reserve(nd);
if (nd == 0) {
@@ -267,6 +593,7 @@ static void common_params_fit_impl(
if (projected_free_per_device[0] >= margins[0]) {
LOG_TRC("%s: will leave %" PRId64 " >= %" PRId64 " MiB of free device memory, no changes needed\n",
__func__, projected_free_per_device[0]/MiB, margins[0]/MiB);
+ log_stock_fit();
return;
}
} else {
@@ -279,6 +606,7 @@ static void common_params_fit_impl(
}
if (!changes_needed) {
LOG_TRC("%s: targets for free memory can be met on all devices, no changes needed\n", __func__);
+ log_stock_fit();
return;
}
}
@@ -523,11 +851,63 @@ static void common_params_fit_impl(
return ret;
};
+ auto set_cache_layer_split = [&](const std::vector & layers,
+ llama_model_params & candidate, float * split,
+ llama_model_tensor_buft_override * overrides) {
+ GGML_ASSERT(layers.size() == nd);
+ std::fill(split, split + llama_max_devices(), 0.0f);
+ candidate.n_gpu_layers = 0;
+ for (size_t id = 0; id < nd; id++) {
+ if ((uint64_t)candidate.n_gpu_layers + layers[id] > INT32_MAX) {
+ throw std::runtime_error("cache candidate layer count overflowed");
+ }
+ candidate.n_gpu_layers += layers[id];
+ if (nd > 1) {
+ split[id] = layers[id];
+ }
+ }
+ candidate.tensor_split = split;
+ overrides[0] = {common_moe_cache_tensor_override_pattern(), ggml_backend_cpu_buffer_type()};
+ overrides[1] = {nullptr, nullptr};
+ candidate.tensor_buft_overrides = overrides;
+ candidate.use_extra_bufts = false;
+ };
+
+ auto get_cache_candidate_memory = [&](const std::vector & layers,
+ dmds_t & candidate_memory) {
+ std::vector candidate_split(llama_max_devices(), 0.0f);
+ std::vector candidate_overrides(ntbo, {nullptr, nullptr});
+ llama_model_params candidate = *mparams;
+ set_cache_layer_split(layers, candidate, candidate_split.data(), candidate_overrides.data());
+
+ std::vector candidate_devs;
+ uint32_t candidate_ngl = 0;
+ uint32_t candidate_nct = 0;
+ uint32_t candidate_nex = 0;
+ candidate_memory = common_get_device_memory_data_impl(
+ path_model, &candidate, cparams, candidate_devs,
+ candidate_ngl, candidate_nct, candidate_nex, log_level);
+ if (candidate_devs != devs || candidate_memory.size() != nd + 1) {
+ return false;
+ }
+ for (size_t id = 0; id < nd; id++) {
+ if (candidate_memory[id].mb.total() > INT64_MAX ||
+ candidate_memory[id].free - (int64_t)candidate_memory[id].mb.total() < margins[id]) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ std::vector cache_layers;
+ dmds_t cache_memory;
+ bool cache_candidate_valid = false;
+ bool cache_candidate_main = false;
+
int64_t global_surplus_cpu_moe = 0;
if (hp_nex > 0) {
- const static std::string pattern_moe_all = "blk\\.\\d+\\.ffn_(up|down|gate_up|gate)_(ch|)exps"; // matches all MoE tensors
ggml_backend_buffer_type_t cpu_buft = ggml_backend_cpu_buffer_type();
- tensor_buft_overrides[0] = {pattern_moe_all.c_str(), cpu_buft};
+ tensor_buft_overrides[0] = {common_moe_cache_tensor_override_pattern(), cpu_buft};
tensor_buft_overrides[1] = {nullptr, nullptr};
mparams->tensor_buft_overrides = tensor_buft_overrides;
@@ -636,6 +1016,35 @@ static void common_params_fit_impl(
"%s: - %s: %2" PRIu32 " layers, %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
__func__, dev_names[id].c_str(), ngl_per_device[id].n_layer, mem[id]/MiB, projected_margin/MiB);
}
+
+ if (hp_nex > 0 && global_surplus_cpu_moe > 0 && moe_cache &&
+ moe_cache->mode != COMMON_MOE_CACHE_MODE_OFF && !moe_tensors.empty()) {
+ std::vector dense_layers(nd, 0);
+ uint64_t assigned_layers = 0;
+ for (size_t id = 0; id < nd; id++) {
+ dense_layers[id] = ngl_per_device[id].n_layer;
+ assigned_layers += dense_layers[id];
+ }
+
+ const uint64_t required_layers = (uint64_t)hp_ngl + 1;
+ if (assigned_layers == required_layers) {
+ const int main_gpu = mparams->main_gpu;
+ if (main_gpu >= 0 && main_gpu < (int)nd && required_layers <= UINT32_MAX) {
+ std::vector main_layers(nd, 0);
+ main_layers[main_gpu] = (uint32_t)required_layers;
+ if (get_cache_candidate_memory(main_layers, cache_memory)) {
+ cache_layers = std::move(main_layers);
+ cache_candidate_valid = true;
+ cache_candidate_main = true;
+ }
+ }
+ if (!cache_candidate_valid && get_cache_candidate_memory(dense_layers, cache_memory)) {
+ cache_layers = std::move(dense_layers);
+ cache_candidate_valid = true;
+ }
+ }
+ }
+
if (hp_nex == 0 || global_surplus_cpu_moe <= 0) {
set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
return;
@@ -782,6 +1191,216 @@ static void common_params_fit_impl(
__func__, dev_names[id].c_str(), ngl_per_device[id].n_layer, ngl_per_device[id].n_part, mem[id]/MiB, projected_margin/MiB);
}
+ bool stock_spills_experts = false;
+ for (const ngl_t & layers : ngl_per_device) {
+ if (layers.n_part > 0) {
+ stock_spills_experts = true;
+ break;
+ }
+ }
+
+ if (moe_cache && moe_cache->mode != COMMON_MOE_CACHE_MODE_OFF) {
+ if (!stock_spills_experts) {
+ LOG_INF("%s: MoE cache fit kept stock placement because all routed expert weights fit in VRAM\n", __func__);
+ } else if (moe_cache->mode == COMMON_MOE_CACHE_MODE_SOFT) {
+ // Step 1: try spare-VRAM (stock placement, no expert eviction)
+ common_moe_cache_fit_result soft_fit = common_moe_cache_evaluate_fit(
+ moe_cache, moe_tensors, devs, dmds_full, margins);
+ if (soft_fit.feasible) {
+ moe_cache->fit_selected = true;
+
+ const double coverage = soft_fit.expert_bytes > 0
+ ? 100.0 * (double)std::min(soft_fit.cache_bytes, soft_fit.expert_bytes) /
+ (double)soft_fit.expert_bytes
+ : 0.0;
+ LOG_INF("%s: MoE cache soft mode selected stock placement with %" PRId64 " MiB projected cache capacity for %" PRId64 " MiB of routed expert weights (up to %.1f%% coverage, no expert eviction)\n",
+ __func__,
+ (int64_t)(soft_fit.cache_bytes / MiB), (int64_t)(soft_fit.expert_bytes / MiB), coverage);
+ for (const common_moe_cache_fit_device & device : soft_fit.devices) {
+ LOG_INF("%s: MoE cache fit CUDA%d leaves %" PRId64 " MiB after reserve; minimum complete pool set is %" PRId64 " MiB\n",
+ __func__, device.physical_device, (int64_t)(device.cache_bytes / MiB),
+ (int64_t)(soft_fit.minimum_device_bytes / MiB));
+ }
+ } else if (cache_candidate_valid) {
+ // Step 2: spare-VRAM insufficient, try partial expert eviction
+ // Binary search for minimum evicted layers where cache pools fit
+ LOG_INF("%s: MoE cache soft mode: spare-VRAM insufficient (%s), searching for minimum expert eviction\n",
+ __func__, soft_fit.reason.c_str());
+
+ const int total_layers = (int)(hp_ngl + 1);
+ static std::vector pattern_strings;
+ pattern_strings.clear();
+ pattern_strings.reserve(total_layers);
+
+ // Per-layer routed-expert bytes from tensor metadata. Evicting
+ // layers in ascending footprint order makes the search minimize
+ // the bytes evicted, not just the number of prefix layers.
+ std::vector layer_bytes(total_layers, 0);
+ for (const llama_moe_tensor_info & tensor : moe_tensors) {
+ if (tensor.layer >= 0 && tensor.layer < total_layers &&
+ tensor.n_expert > 0 && tensor.expert_size > 0 &&
+ (uint64_t)tensor.n_expert <= (uint64_t)(INT64_MAX / (int64_t)tensor.expert_size)) {
+ layer_bytes[tensor.layer] +=
+ (int64_t)tensor.n_expert * (int64_t)tensor.expert_size;
+ }
+ }
+ std::vector order(total_layers);
+ for (int i = 0; i < total_layers; i++) {
+ order[i] = i;
+ }
+ std::stable_sort(order.begin(), order.end(), [&](int a, int b) {
+ return layer_bytes[a] != layer_bytes[b]
+ ? layer_bytes[a] < layer_bytes[b] : a < b;
+ });
+
+ int lo = 0, hi = total_layers;
+ int best_n_evict = -1;
+ int64_t best_evicted_bytes = 0;
+ dmds_t best_memory;
+ common_moe_cache_fit_result best_cache_fit;
+
+ while (lo <= hi) {
+ const int mid = lo + (hi - lo) / 2;
+
+ // Build candidate: all layers on main GPU, the 'mid'
+ // smallest-footprint layers' experts moved to CPU
+ std::vector candidate_split(llama_max_devices(), 0.0f);
+ std::vector candidate_overrides(ntbo, {nullptr, nullptr});
+ llama_model_params candidate = *mparams;
+
+ candidate.n_gpu_layers = 0;
+ for (size_t id = 0; id < nd; id++) {
+ if ((uint64_t)candidate.n_gpu_layers + cache_layers[id] > INT32_MAX) break;
+ candidate.n_gpu_layers += cache_layers[id];
+ if (nd > 1) candidate_split[id] = (float)cache_layers[id];
+ }
+ candidate.tensor_split = candidate_split.data();
+
+ // Per-layer overrides: evict the chosen layers' experts to CPU
+ pattern_strings.clear();
+ int n_overrides = 0;
+ for (int i = 0; i < mid && n_overrides < (int)ntbo - 1; i++) {
+ pattern_strings.push_back(llm_ffn_exps_block_regex(order[i]));
+ candidate_overrides[n_overrides++] = {pattern_strings.back().c_str(), ggml_backend_cpu_buffer_type()};
+ }
+ candidate_overrides[n_overrides] = {nullptr, nullptr};
+ candidate.tensor_buft_overrides = candidate_overrides.data();
+ candidate.use_extra_bufts = false;
+
+ // Evaluate memory and cache for this candidate
+ std::vector candidate_devs;
+ uint32_t c_ngl = 0, c_nct = 0, c_nex = 0;
+ dmds_t candidate_memory = common_get_device_memory_data_impl(
+ path_model, &candidate, cparams, candidate_devs,
+ c_ngl, c_nct, c_nex, log_level);
+
+ bool candidate_valid = (candidate_devs == devs && candidate_memory.size() == nd + 1);
+ if (candidate_valid) {
+ for (size_t id = 0; id < nd; id++) {
+ if (candidate_memory[id].mb.total() > INT64_MAX ||
+ candidate_memory[id].free - (int64_t)candidate_memory[id].mb.total() < margins[id]) {
+ candidate_valid = false;
+ break;
+ }
+ }
+ }
+
+ if (candidate_valid) {
+ common_moe_cache_fit_result cf = common_moe_cache_evaluate_fit(
+ moe_cache, moe_tensors, devs, candidate_memory, margins);
+ if (cf.feasible) {
+ best_n_evict = mid;
+ best_evicted_bytes = 0;
+ for (int i = 0; i < mid; i++) {
+ best_evicted_bytes += layer_bytes[order[i]];
+ }
+ best_memory = std::move(candidate_memory);
+ best_cache_fit = cf;
+ hi = mid - 1; // Try fewer evictions
+ } else {
+ lo = mid + 1; // Need more evictions
+ }
+ } else {
+ lo = mid + 1;
+ }
+ }
+
+ if (best_n_evict >= 0) {
+ // Apply the best placement with minimal expert eviction
+ std::fill(tensor_split, tensor_split + llama_max_devices(), 0.0f);
+ mparams->n_gpu_layers = 0;
+ for (size_t id = 0; id < nd; id++) {
+ mparams->n_gpu_layers += cache_layers[id];
+ if (nd > 1) tensor_split[id] = (float)cache_layers[id];
+ }
+ mparams->tensor_split = tensor_split;
+
+ // Generate final per-layer overrides
+ pattern_strings.clear();
+ int n_overrides = 0;
+ for (int i = 0; i < best_n_evict && n_overrides < (int)ntbo - 1; i++) {
+ pattern_strings.push_back(llm_ffn_exps_block_regex(order[i]));
+ tensor_buft_overrides[n_overrides++] = {pattern_strings.back().c_str(), ggml_backend_cpu_buffer_type()};
+ }
+ tensor_buft_overrides[n_overrides] = {nullptr, nullptr};
+ mparams->tensor_buft_overrides = tensor_buft_overrides;
+ mparams->use_extra_bufts = false;
+ moe_cache->fit_selected = true;
+
+ const int n_kept = total_layers - best_n_evict;
+ const double coverage = best_cache_fit.expert_bytes > 0
+ ? 100.0 * (double)std::min(best_cache_fit.cache_bytes, best_cache_fit.expert_bytes) /
+ (double)best_cache_fit.expert_bytes
+ : 0.0;
+ const int64_t kept_bytes = best_cache_fit.expert_bytes > (size_t)best_evicted_bytes
+ ? (int64_t)best_cache_fit.expert_bytes - best_evicted_bytes : 0;
+ LOG_INF("%s: MoE cache soft mode selected partial-eviction placement: %d/%d layers keep experts GPU-resident, "
+ "%" PRId64 " MiB of %" PRId64 " MiB routed expert bytes evicted (%" PRId64 " MiB kept), "
+ "%" PRId64 " MiB projected cache capacity (up to %.1f%% coverage)\n",
+ __func__, n_kept, total_layers,
+ (int64_t)(best_evicted_bytes / MiB), (int64_t)(best_cache_fit.expert_bytes / MiB),
+ (int64_t)(kept_bytes / MiB),
+ (int64_t)(best_cache_fit.cache_bytes / MiB), coverage);
+ for (const common_moe_cache_fit_device & device : best_cache_fit.devices) {
+ LOG_INF("%s: MoE cache fit CUDA%d leaves %" PRId64 " MiB after reserve; minimum complete pool set is %" PRId64 " MiB\n",
+ __func__, device.physical_device, (int64_t)(device.cache_bytes / MiB),
+ (int64_t)(best_cache_fit.minimum_device_bytes / MiB));
+ }
+ return;
+ }
+ LOG_INF("%s: MoE cache soft mode kept stock placement (partial eviction could not fit cache pools)\n",
+ __func__);
+ } else {
+ LOG_INF("%s: MoE cache soft mode kept stock placement (spare-VRAM insufficient): %s\n",
+ __func__, soft_fit.reason.c_str());
+ }
+ } else if (!cache_candidate_valid) {
+ LOG_INF("%s: MoE cache fit kept stock placement because canonical dense weights do not meet the fit targets\n", __func__);
+ } else {
+ common_moe_cache_fit_result cache_fit = common_moe_cache_evaluate_fit(
+ moe_cache, moe_tensors, devs, cache_memory, margins);
+ if (cache_fit.feasible) {
+ set_cache_layer_split(cache_layers, *mparams, tensor_split, tensor_buft_overrides);
+ moe_cache->fit_selected = true;
+
+ const double coverage = cache_fit.expert_bytes > 0
+ ? 100.0 * (double)std::min(cache_fit.cache_bytes, cache_fit.expert_bytes) /
+ (double)cache_fit.expert_bytes
+ : 0.0;
+ LOG_INF("%s: MoE cache fit selected %s dense placement with %" PRId64 " MiB projected cache capacity for %" PRId64 " MiB of routed expert weights (up to %.1f%% coverage)\n",
+ __func__, cache_candidate_main ? "main-device" : "packed",
+ (int64_t)(cache_fit.cache_bytes / MiB), (int64_t)(cache_fit.expert_bytes / MiB), coverage);
+ for (const common_moe_cache_fit_device & device : cache_fit.devices) {
+ LOG_INF("%s: MoE cache fit CUDA%d leaves %" PRId64 " MiB after reserve; minimum complete pool set is %" PRId64 " MiB\n",
+ __func__, device.physical_device, (int64_t)(device.cache_bytes / MiB),
+ (int64_t)(cache_fit.minimum_device_bytes / MiB));
+ }
+ return;
+ }
+ LOG_INF("%s: MoE cache fit kept stock placement: %s\n", __func__, cache_fit.reason.c_str());
+ }
+ }
+
set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
}
@@ -791,13 +1410,14 @@ enum common_params_fit_status common_fit_params(
llama_context_params * cparams,
float * tensor_split,
llama_model_tensor_buft_override * tensor_buft_overrides,
+ common_moe_cache_params * moe_cache,
size_t * margins,
uint32_t n_ctx_min,
ggml_log_level log_level) {
const int64_t t0_us = llama_time_us();
common_params_fit_status status = COMMON_PARAMS_FIT_STATUS_SUCCESS;
try {
- common_params_fit_impl(path_model, mparams, cparams, tensor_split, tensor_buft_overrides, margins, n_ctx_min, log_level);
+ common_params_fit_impl(path_model, mparams, cparams, tensor_split, tensor_buft_overrides, moe_cache, margins, n_ctx_min, log_level);
LOG_TRC("%s: successfully fit params to free device memory\n", __func__);
} catch (const common_params_fit_exception & e) {
LOG_WRN("%s: failed to fit params to free device memory: %s\n", __func__, e.what());
diff --git a/common/fit.h b/common/fit.h
index 208fc30694e0..3337904a43c6 100644
--- a/common/fit.h
+++ b/common/fit.h
@@ -3,8 +3,55 @@
#include "ggml.h"
#include "llama.h"
+#include
+#include
#include
+struct common_moe_cache_params;
+
+const char * common_moe_cache_tensor_override_pattern();
+
+struct common_moe_cache_fit_device_input {
+ int physical_device = -1;
+ int compute_capability = 0;
+ int64_t free_bytes = 0;
+ size_t used_bytes = 0;
+};
+
+struct common_moe_cache_fit_shape_input {
+ enum ggml_type type = GGML_TYPE_COUNT;
+ size_t expert_size = 0;
+ size_t tensor_bytes = 0;
+ size_t scratch_bytes = 0;
+ size_t pool_bytes = 0;
+ bool cacheable = false;
+};
+
+struct common_moe_cache_fit_device {
+ int physical_device = -1;
+ int compute_capability = 0;
+ int64_t free_bytes = 0;
+ int64_t used_bytes = 0;
+ size_t cache_bytes = 0;
+};
+
+struct common_moe_cache_fit_result {
+ bool feasible = false;
+ std::string reason;
+ std::vector devices;
+ size_t expert_bytes = 0;
+ size_t cache_bytes = 0;
+ size_t minimum_device_bytes = 0;
+};
+
+common_moe_cache_fit_result common_moe_cache_plan_fit(
+ const std::vector & devices,
+ const std::vector & shapes,
+ size_t reserve_bytes,
+ size_t budget_bytes,
+ int min_devices,
+ size_t minimum_slab_bytes = 0);
+
enum common_params_fit_status {
COMMON_PARAMS_FIT_STATUS_SUCCESS = 0, // found allocations that are projected to fit
COMMON_PARAMS_FIT_STATUS_FAILURE = 1, // could not find allocations that are projected to fit
@@ -22,6 +69,7 @@ common_params_fit_status common_fit_params(
llama_context_params * cparams,
float * tensor_split, // writable buffer for tensor split, needs at least llama_max_devices elements
llama_model_tensor_buft_override * tensor_buft_overrides, // writable buffer for overrides, needs at least llama_max_tensor_buft_overrides elements
+ common_moe_cache_params * moe_cache,
size_t * margins, // margins of memory to leave per device in bytes
uint32_t n_ctx_min, // minimum context size to set when trying to reduce memory use
ggml_log_level log_level); // minimum log level to print during fitting, lower levels go to debug log
@@ -54,3 +102,17 @@ common_device_memory_data_vec common_get_device_memory_data(
uint32_t & hp_n_ctx_train,
uint32_t & hp_n_expert,
ggml_log_level log_level);
+
+// Load a parent model + context with no_alloc, then return the per-device memory breakdown of a child model + context.
+common_device_memory_data_vec common_get_device_memory_data_with_parent(
+ const char * path_model,
+ const llama_model_params * mparams,
+ const llama_context_params * cparams,
+ const char * path_parent,
+ const llama_model_params * mparams_parent,
+ const llama_context_params * cparams_parent,
+ std::vector & devs,
+ uint32_t & hp_ngl,
+ uint32_t & hp_n_ctx_train,
+ uint32_t & hp_n_expert,
+ ggml_log_level log_level);
diff --git a/common/jinja/caps.cpp b/common/jinja/caps.cpp
index cdd7ccfa26ee..fb97909edf9d 100644
--- a/common/jinja/caps.cpp
+++ b/common/jinja/caps.cpp
@@ -17,7 +17,7 @@ namespace jinja {
using caps_json_fn = std::function;
using caps_ctx_fn = std::function;
-using caps_analyze_fn = std::function;
+using caps_analyze_fn = std::function;
void caps_apply_preserve_reasoning(jinja::context & ctx, bool enabled) {
ctx.set_val("preserve_thinking", mk_val(enabled));
@@ -26,6 +26,12 @@ void caps_apply_preserve_reasoning(jinja::context & ctx, bool enabled) {
ctx.set_val("drop_thinking", mk_val(!enabled));
}
+void caps_apply_reasoning_effort(jinja::context & ctx, const std::string & effort) {
+ value var = mk_val(effort); // bind to the same value for stats
+ ctx.set_val("reasoning_effort", var);
+ ctx.set_val("reasoning_strength", var);
+}
+
static void caps_try_execute(jinja::program & prog,
const caps_json_fn & messages_fn,
const caps_ctx_fn & ctx_fn,
@@ -62,7 +68,7 @@ static void caps_try_execute(jinja::program & prog,
// ignore exceptions during capability analysis
}
- analyze_fn(success, messages, tools, result);
+ analyze_fn(ctx, success, messages, tools, result);
}
// for debugging only
@@ -87,6 +93,7 @@ std::map caps::to_map() const {
{"supports_parallel_tool_calls", supports_parallel_tool_calls},
{"supports_system_role", supports_system_role},
{"supports_preserve_reasoning", supports_preserve_reasoning},
+ {"supports_reasoning_effort", supports_reasoning_effort},
{"supports_object_arguments", supports_object_arguments},
};
}
@@ -124,7 +131,7 @@ caps caps_get(jinja::program & prog) {
},
nullptr, // ctx_fn
nullptr, // tools_fn
- [&](bool success, value & messages, value &, const std::string &) {
+ [&](context &, bool success, value & messages, value &, const std::string &) {
auto & content = messages->at(0)->at("content");
caps_print_stats(content, "messages[0].content");
if (has_op(content, "selectattr") || has_op(content, "array_access")) {
@@ -158,7 +165,7 @@ caps caps_get(jinja::program & prog) {
},
nullptr, // ctx_fn
nullptr, // tools_fn
- [&](bool, value & messages, value &, const std::string &) {
+ [&](context &, bool, value & messages, value &, const std::string &) {
auto & content = messages->at(0)->at("content");
caps_print_stats(content, "messages[0].content");
if (!content->stats.used) {
@@ -234,7 +241,7 @@ caps caps_get(jinja::program & prog) {
},
});
},
- [&](bool success, value & messages, value & tools, const std::string &) {
+ [&](context &, bool success, value & messages, value & tools, const std::string &) {
if (!success) {
return; // Nothing can be inferred
}
@@ -327,7 +334,7 @@ caps caps_get(jinja::program & prog) {
},
});
},
- [&](bool success, value & messages, value & tools, const std::string &) {
+ [&](context &, bool success, value & messages, value & tools, const std::string &) {
if (!success) {
result.supports_tool_calls = false;
result.supports_tools = false;
@@ -429,7 +436,7 @@ caps caps_get(jinja::program & prog) {
},
});
},
- [&](bool success, value & messages, value &, const std::string &) {
+ [&](context &, bool success, value & messages, value &, const std::string &) {
if (!success) {
result.supports_parallel_tool_calls = false;
return;
@@ -486,7 +493,7 @@ caps caps_get(jinja::program & prog) {
caps_apply_preserve_reasoning(ctx, true);
},
nullptr, // tools_fn
- [&](bool, value &, value &, const std::string & output) {
+ [&](context &, bool, value &, value &, const std::string & output) {
// note: we cannot use stats here because the reasoning_content may be used for "if" condition test, but not actually outputted in the final result
if (output.find(reasoning_placeholder) != std::string::npos) {
result.supports_preserve_reasoning = true;
@@ -494,6 +501,32 @@ caps caps_get(jinja::program & prog) {
}
);
+ JJ_DEBUG("%s\n", ">>> Running capability check: reasoning effort");
+
+ // case: reasoning effort level
+ caps_try_execute(
+ prog,
+ [&]() {
+ // messages
+ return json::array({
+ {
+ {"role", "user"},
+ {"content", "User message"}
+ },
+ });
+ },
+ [&](context & ctx) {
+ ctx.set_val("enable_thinking", mk_val(true));
+ caps_apply_reasoning_effort(ctx, "low");
+ },
+ nullptr, // tools_fn
+ [&](context & ctx, bool, value &, value &, const std::string &) {
+ value effort = ctx.get_val("reasoning_effort");
+ caps_print_stats(effort, "reasoning_effort");
+ result.supports_reasoning_effort = effort->stats.used;
+ }
+ );
+
JJ_DEBUG("%s\n", result.to_string().c_str());
return result;
diff --git a/common/jinja/caps.h b/common/jinja/caps.h
index a290cd7da627..b81dd95f2ed6 100644
--- a/common/jinja/caps.h
+++ b/common/jinja/caps.h
@@ -16,6 +16,9 @@ struct caps {
// supports preserve reasoning trace in the full history, not just the last assistant message
bool supports_preserve_reasoning = false;
+ // supports reasoning effort levels
+ bool supports_reasoning_effort = false;
+
// one of the 2 content capabilities must be true
bool supports_string_content = true;
bool supports_typed_content = false;
@@ -32,5 +35,6 @@ struct caps {
caps caps_get(jinja::program & prog);
void caps_apply_preserve_reasoning(jinja::context & ctx, bool enabled);
+void caps_apply_reasoning_effort(jinja::context & ctx, const std::string & effort);
} // namespace jinja
diff --git a/common/sampling.cpp b/common/sampling.cpp
index ba5504ed0118..ec9c885ddf18 100644
--- a/common/sampling.cpp
+++ b/common/sampling.cpp
@@ -186,8 +186,7 @@ std::string common_params_sampling::print() const {
struct common_sampler * common_sampler_init(
const struct llama_model * model,
- struct common_params_sampling & params,
- int32_t n_ctx) {
+ struct common_params_sampling & params) {
if (!std::isfinite(params.penalty_repeat) ||
params.penalty_repeat <= 0.0f ||
!std::isfinite(1.0f/params.penalty_repeat)) {
@@ -199,10 +198,6 @@ struct common_sampler * common_sampler_init(
if (!std::isfinite(params.penalty_present)) {
throw std::invalid_argument("penalty_present must be finite");
}
- if (params.penalty_last_n == -1) {
- params.penalty_last_n = n_ctx > 0 ? n_ctx : llama_model_n_ctx_train(model);
- }
-
const llama_vocab * vocab = llama_model_get_vocab(model);
llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
@@ -355,7 +350,7 @@ struct common_sampler * common_sampler_init(
for (const auto & str : params.dry_sequence_breakers) {
c_breakers.push_back(str.c_str());
}
- samplers.push_back(llama_sampler_init_dry(vocab, llama_model_n_ctx_train(model), params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
+ samplers.push_back(llama_sampler_init_dry(vocab, params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
}
break;
case COMMON_SAMPLER_TYPE_TOP_K:
diff --git a/common/sampling.h b/common/sampling.h
index 6b5bcfa0345e..cb90d4ae7acf 100644
--- a/common/sampling.h
+++ b/common/sampling.h
@@ -39,8 +39,7 @@ struct common_sampler;
// note: can mutate params in some cases
struct common_sampler * common_sampler_init(
const struct llama_model * model,
- struct common_params_sampling & params,
- int32_t n_ctx = 0);
+ struct common_params_sampling & params);
void common_sampler_free(struct common_sampler * gsmpl);
@@ -69,10 +68,8 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co
// generalized version of common_sampler_sample
//
-// will cross-reference greedy-argmax target tokens with a batch of draft tokens and accept those that match
-// (draft positions use raw-logit argmax so stochastic params like temperature do not break MTP / greedy drafts)
-// then samples the next continuation token with the full chain when all drafts matched
-// if the target disagrees at some point, we stop and return the accepted tokens up to now
+// will cross-reference the sampled tokens with a batch of draft tokens and accept those that match
+// if the sampler disagrees at some point, we stop and return the accepted tokens up to now
//
// common_sampler_sample_n(gsmpl, ctx, { idx }, {});
//
diff --git a/common/speculative-adaptive.h b/common/speculative-adaptive.h
new file mode 100644
index 000000000000..644664c6a318
--- /dev/null
+++ b/common/speculative-adaptive.h
@@ -0,0 +1,92 @@
+#pragma once
+
+#include
+
+// Adaptive draft depth controller for MTP speculative decoding (draft-mtp-adaptive).
+//
+// Hysteresis state machine with a climb counter and a weighted drop-pressure
+// accumulator. The depth N climbs one step after N_CLIMB(N) consecutive verifies
+// that accepted every drafted token. The climb cost is low at the floor and at
+// depth, high in the middle: 2 at depth 1, 4 at depth 2, 6 at depth 3, then
+// 5/4/3/2 from depth 4 upward. Getting from the floor to depth 3 needs only 6
+// full accepts, but pushing past 3 (where prose acceptance collapses) costs 6
+// full accepts of 3-token drafts, which predictable content clears quickly and
+// marginal content never does. Any miss adds (n_draft - n_accepted) to a
+// drop-pressure accumulator; when it reaches depth * 5 the depth drops one step
+// and the pressure resets. A near miss (n_draft-1) adds 1, a total miss adds
+// n_draft, so high depths fall quickly while low depths hold. The drop budget
+// scales with depth but never drops below 20, so shallow depths shed bad content
+// quickly without collapsing to the floor on a few bad rounds; deep depths hold
+// a little longer. At the floor no pressure accumulates at all. The depth starts
+// at the floor max(1, --spec-draft-n-min-adaptive) and stays in
+// [floor, n_max]; --spec-draft-n-max bounds the upper end of the adaptive
+// range.
+struct common_speculative_adaptive {
+ int n_cur = 0; // current adaptive draft depth N
+ int n_climb = 0; // consecutive verifies that accepted every drafted token
+ int n_drop = 0; // accumulated drop pressure: sum of (n_draft - n_accepted)
+
+ // consecutive full accepts needed to climb one step from depth N; low at the
+ // floor and at depth, high in the middle where acceptance is marginal
+ static int climb_threshold(int depth) {
+ switch (depth) {
+ case 1: return 2;
+ case 2: return 4;
+ case 3: return 6;
+ case 4: return 5;
+ case 5: return 4;
+ case 6: return 3;
+ default: return 2; // depth >= 7
+ }
+ }
+
+ // accumulated (n_draft - n_accepted) needed to drop one step from depth N;
+ // scaled by depth, with a floor so shallow depths do not collapse too fast
+ static int drop_pressure(int depth) {
+ return std::max(depth * 5, 20);
+ }
+
+ // reset to the floor max(1, n_min_adaptive), bounded by the ceiling n_max;
+ // the controller climbs from there once acceptance feedback arrives
+ void reset(int n_max, int n_min_adaptive) {
+ const int cap = std::max(1, n_max);
+ const int floor = std::max(1, n_min_adaptive);
+
+ n_cur = std::min(floor, cap);
+ n_climb = 0;
+ n_drop = 0;
+ }
+
+ // feed one verification result: n_draft is the number of tokens this
+ // implementation drafted, n_accepted the number the target accepted
+ void update(int n_draft, int n_accepted, int n_max, int n_min_adaptive) {
+ if (n_draft <= 0) {
+ return;
+ }
+
+ const int cap = std::max(1, n_max);
+ const int floor = std::max(1, n_min_adaptive);
+
+ if (n_accepted == n_draft) {
+ n_drop = 0;
+
+ // full acceptance: reset the drop pressure, accumulate the climb streak
+ if (n_cur < cap && ++n_climb >= climb_threshold(n_cur)) {
+ n_cur++;
+ n_climb = 0;
+ }
+ } else {
+ n_climb = 0;
+
+ // any miss adds (n_draft - n_accepted) to the drop pressure; drop one
+ // step when the accumulated pressure reaches the depth-scaled budget
+ if (n_cur > floor) {
+ n_drop += n_draft - n_accepted;
+ if (n_drop >= drop_pressure(n_cur)) {
+ n_cur--;
+ n_drop = 0;
+ }
+ }
+ }
+ }
+};
diff --git a/common/speculative.cpp b/common/speculative.cpp
index 9281e8ba7b03..d716c17f55cf 100644
--- a/common/speculative.cpp
+++ b/common/speculative.cpp
@@ -8,11 +8,13 @@
#include "ngram-map.h"
#include "ngram-mod.h"
#include "sampling.h"
+#include "speculative-adaptive.h"
#include "../src/llama-ext.h" // staging API: llama_set_embeddings_nextn / llama_get_embeddings_nextn_ith (used by MTP)
#include
#include
+#include
#include
#include
#include