Skip to content

Truncate prompt if longer than context + n_predict - #78

Closed
matthew-mcallister wants to merge 1 commit into
ggml-org:masterfrom
matthew-mcallister:context-overflow
Closed

matthew-mcallister wants to merge 1 commit into
ggml-org:masterfrom
matthew-mcallister:context-overflow

Conversation

@matthew-mcallister

Copy link
Copy Markdown

I think this is an improvement over the current behavior of outputting nothing at all when the prompt is too long. It's slightly ugly to see the truncated prompt in the terminal, but it is helpful to see exactly what was included in the prompt so you can tell what was truncated.

Maybe there's a better solution, IDK, just throwing a PR your way.

@ggerganov

Copy link
Copy Markdown
Member

I have a better solution in mind. Will close this for now

@ggerganov ggerganov closed this Mar 19, 2023
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
* Faster q6_0 on AVX2

PP-512 goes up by 3.4%.

* q6_0: this is slightly better

---------

Co-authored-by: Iwan Kawrakow <[email protected]>
LifesLight pushed a commit to LifesLight/custom.llama.cpp that referenced this pull request May 2, 2026
…nt (ggml-org#78)

Post-attention V-padded reshape in build_attn was using hparams.n_head_kv(il),
but cur returned from build_attn_mha has shape (n_embd_head * n_head, n_tokens) —
n_head is the Q-head count. On GQA models where n_head != n_head_kv (e.g.
Qwen2.5-0.5B with head_dim=64 padded → 128, n_head=14, n_head_kv=2), the
reshape element count fails the assertion in ggml_reshape_3d and the process
aborts.

Symptom: GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2) at ggml.c:3656.

Reported and diagnosed by @bingh0 in TheTom#78. Verified
locally on Qwen2.5-7B (head_dim=128, no padding, regression check passes) and
on AMD MI300X with Qwen2.5-0.5B (head_dim=64, was crashing pre-fix).

Three sites fixed (lines 2285, 2412, 2532 — same idiom in three build_attn
overloads).

Closes ggml-org#78. Likely also closes ggml-org#108 (speculative decoding hits the same
assertion).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
LifesLight pushed a commit to LifesLight/custom.llama.cpp that referenced this pull request May 2, 2026
fix: build_attn V-padded reshape uses Q-head count, not KV-head count (ggml-org#78)
Jcfunk pushed a commit to Jcfunk/llama.cpp that referenced this pull request May 13, 2026
…nt (ggml-org#78)

Post-attention V-padded reshape in build_attn was using hparams.n_head_kv(il),
but cur returned from build_attn_mha has shape (n_embd_head * n_head, n_tokens) —
n_head is the Q-head count. On GQA models where n_head != n_head_kv (e.g.
Qwen2.5-0.5B with head_dim=64 padded → 128, n_head=14, n_head_kv=2), the
reshape element count fails the assertion in ggml_reshape_3d and the process
aborts.

Symptom: GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2) at ggml.c:3656.

Reported and diagnosed by @bingh0 in TheTom#78. Verified
locally on Qwen2.5-7B (head_dim=128, no padding, regression check passes) and
on AMD MI300X with Qwen2.5-0.5B (head_dim=64, was crashing pre-fix).

Three sites fixed (lines 2285, 2412, 2532 — same idiom in three build_attn
overloads).

Closes ggml-org#78. Likely also closes ggml-org#108 (speculative decoding hits the same
assertion).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jimbothigpen added a commit to jimbothigpen/af-engn that referenced this pull request May 21, 2026
Port the layer-adaptive KV precision block from TheTom's TQ-KV state
(5aeb2fd llama-kv-cache.cpp lines 267-326) plus mode 7 from
da4a02e. Steps 1-4's cumulative ports landed everything else recon/08
§Step 5 intended; Step 5 is reduced to this single block (gap analysis
in body).

Modes:
- 0 = uniform (default, no behavior change)
- 1 = q8_0 K+V for first 4 + last 4 layers (turbo K+V outer-protection)
- 2 = q8_0 K+V for last 8 layers
- 5 = first2+last2 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged)
- 6 = last8 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged)
- 7 = Boundary V (recommended): first2+last2 V=q8_0, rest V=TURBOQ3_0
      (K unchanged)

Yggdrasil adjustments:
- TURBO2_0 (TQ-KV slot 42) substituted with TURBOQ3_0 in the "middle"
  slot of modes 5/6/7. TURBOQ2_0 is deferred per phase-1 scope; when
  it lands, restore TURBO2_0 -> TURBOQ2_0 in those three branches to
  recover TQ-KV's original compression ratios.
- TQ-KV's auto-enable on V=TURBO2_0 is intentionally dropped per
  recon/08 §Step 5 validation ("Boundary V default-off — no behavioral
  change without explicit flag"). Mode 0 stays the default.
- Banner LLAMA_LOG_INFO uses a per-constructor-call local flag, not a
  static, because fit-probe + real construction each invoke the
  constructor; logger output is suppressed during the probe pass.

Gap analysis (recon/08 §Step 5 commits, post-Step-3 cumulative-port
state):
- f2b3936 Metal asymmetric K/V: SKIP — Metal-only, no Metal backend.
- 0fa61d7 PR ggml-org#115 auto-asymmetric merge: already absorbed via Step 3
  (5aeb2fd). fattn-vec.cuh has K_is_turbo/V_is_turbo; is_kv_compat
  permits asymmetric pairs of {TURBOQ3_0, TURBOQ4_0, Q8_0, F16, BF16}.
- b6f8e7f ggml-org#78 GQA reshape fix: N/A — targets padded_v_head /
  orig_v_head block in build_attn that doesn't exist in yggdrasil
  (mainline post-April refactor never had it).
- e9f05a9 64-elem WHT + MLA Q rotation: partially absorbed (CUDA
  kernel supports group_size {128,64,32}); ggml_turbo_wht C-API stays
  3-arg with hardcoded group_size=128 + assert ne[0]%128==0. The
  K-only build_attn Q rotation + %64 fallback are MLA-only; Phase 1
  baseline (Qwen3.5-9B head_dim=128) doesn't exercise them.
- 53ca939 MLA inverse WHT group_size from K: MLA-only.

Deferred to a future phase that adds an MLA model (DeepSeek-V2 head_dim
192, GLM-4.7 head_dim 576): C-API extension of ggml_turbo_wht to take
explicit group_size, Q rotation in inp_attn_k build_attn, %64 fallback,
53ca939's K-derived inverse-WHT guard.

PPL parity gate (Qwen3.5-9B-BF16, 32-chunk c=512, eval-shared wikitext):

| Backend | mode    | PPL    |
|---------|---------|--------|
| ROCm    | default | 7.5939 | (= session 11, bit-identical: no regression)
| Vulkan  | default | 7.6065 | (= session 11, bit-identical: no regression)

Cross-backend Δ = +0.17% (well within <0.5% threshold per design
decision ggml-org#9).

Mode 7 activation spot-check (4-chunk):
| Backend | mode | PPL    |
|---------|------|--------|
| ROCm    | 0    | 8.2261 |
| ROCm    | 7    | 8.1180 | (-1.31%; boundary q8_0-V improves quality)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request May 22, 2026
…nt (ggml-org#78)

Post-attention V-padded reshape in build_attn was using hparams.n_head_kv(il),
but cur returned from build_attn_mha has shape (n_embd_head * n_head, n_tokens) —
n_head is the Q-head count. On GQA models where n_head != n_head_kv (e.g.
Qwen2.5-0.5B with head_dim=64 padded → 128, n_head=14, n_head_kv=2), the
reshape element count fails the assertion in ggml_reshape_3d and the process
aborts.

Symptom: GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2) at ggml.c:3656.

Reported and diagnosed by @bingh0 in TheTom#78. Verified
locally on Qwen2.5-7B (head_dim=128, no padding, regression check passes) and
on AMD MI300X with Qwen2.5-0.5B (head_dim=64, was crashing pre-fix).

Three sites fixed (lines 2285, 2412, 2532 — same idiom in three build_attn
overloads).

Closes ggml-org#78. Likely also closes ggml-org#108 (speculative decoding hits the same
assertion).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jimbothigpen added a commit to jimbothigpen/af-engn that referenced this pull request May 25, 2026
Port the layer-adaptive KV precision block from TheTom's TQ-KV state
(5aeb2fd llama-kv-cache.cpp lines 267-326) plus mode 7 from
da4a02e. Steps 1-4's cumulative ports landed everything else recon/08
§Step 5 intended; Step 5 is reduced to this single block (gap analysis
in body).

Modes:
- 0 = uniform (default, no behavior change)
- 1 = q8_0 K+V for first 4 + last 4 layers (turbo K+V outer-protection)
- 2 = q8_0 K+V for last 8 layers
- 5 = first2+last2 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged)
- 6 = last8 V=TURBOQ4_0, rest V=TURBOQ3_0 (K unchanged)
- 7 = Boundary V (recommended): first2+last2 V=q8_0, rest V=TURBOQ3_0
      (K unchanged)

Yggdrasil adjustments:
- TURBO2_0 (TQ-KV slot 42) substituted with TURBOQ3_0 in the "middle"
  slot of modes 5/6/7. TURBOQ2_0 is deferred per phase-1 scope; when
  it lands, restore TURBO2_0 -> TURBOQ2_0 in those three branches to
  recover TQ-KV's original compression ratios.
- TQ-KV's auto-enable on V=TURBO2_0 is intentionally dropped per
  recon/08 §Step 5 validation ("Boundary V default-off — no behavioral
  change without explicit flag"). Mode 0 stays the default.
- Banner LLAMA_LOG_INFO uses a per-constructor-call local flag, not a
  static, because fit-probe + real construction each invoke the
  constructor; logger output is suppressed during the probe pass.

Gap analysis (recon/08 §Step 5 commits, post-Step-3 cumulative-port
state):
- f2b3936 Metal asymmetric K/V: SKIP — Metal-only, no Metal backend.
- 0fa61d7 PR ggml-org#115 auto-asymmetric merge: already absorbed via Step 3
  (5aeb2fd). fattn-vec.cuh has K_is_turbo/V_is_turbo; is_kv_compat
  permits asymmetric pairs of {TURBOQ3_0, TURBOQ4_0, Q8_0, F16, BF16}.
- b6f8e7f ggml-org#78 GQA reshape fix: N/A — targets padded_v_head /
  orig_v_head block in build_attn that doesn't exist in yggdrasil
  (mainline post-April refactor never had it).
- e9f05a9 64-elem WHT + MLA Q rotation: partially absorbed (CUDA
  kernel supports group_size {128,64,32}); ggml_turbo_wht C-API stays
  3-arg with hardcoded group_size=128 + assert ne[0]%128==0. The
  K-only build_attn Q rotation + %64 fallback are MLA-only; Phase 1
  baseline (Qwen3.5-9B head_dim=128) doesn't exercise them.
- 53ca939 MLA inverse WHT group_size from K: MLA-only.

Deferred to a future phase that adds an MLA model (DeepSeek-V2 head_dim
192, GLM-4.7 head_dim 576): C-API extension of ggml_turbo_wht to take
explicit group_size, Q rotation in inp_attn_k build_attn, %64 fallback,
53ca939's K-derived inverse-WHT guard.

PPL parity gate (Qwen3.5-9B-BF16, 32-chunk c=512, eval-shared wikitext):

| Backend | mode    | PPL    |
|---------|---------|--------|
| ROCm    | default | 7.5939 | (= session 11, bit-identical: no regression)
| Vulkan  | default | 7.6065 | (= session 11, bit-identical: no regression)

Cross-backend Δ = +0.17% (well within <0.5% threshold per design
decision ggml-org#9).

Mode 7 activation spot-check (4-chunk):
| Backend | mode | PPL    |
|---------|------|--------|
| ROCm    | 0    | 8.2261 |
| ROCm    | 7    | 8.1180 | (-1.31%; boundary q8_0-V improves quality)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
HEchternacht pushed a commit to HEchternacht/llama.cpp that referenced this pull request Jul 18, 2026
…fork note (ggml-org#78)

* ci(release): ship full self-contained Windows Vulkan/HIP bundles

readme: add Prism fork note (start with Bonsai-demo, main caveats)

* readme: fix Q2_0 model-file guidance (fork=Q2_0, mainline=Q2_0_g64, PQ2_0 future) + link demo status; ASCII punctuation
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request Sep 13, 2026
…fork note (ggml-org#78)

* ci(release): ship full self-contained Windows Vulkan/HIP bundles

readme: add Prism fork note (start with Bonsai-demo, main caveats)

* readme: fix Q2_0 model-file guidance (fork=Q2_0, mainline=Q2_0_g64, PQ2_0 future) + link demo status; ASCII punctuation
pwilkin pushed a commit to pwilkin/llama.cpp that referenced this pull request Oct 7, 2026
ggml-cuda : round growing pool requests up to a power of two
imaami pushed a commit to imaami/llama.cpp that referenced this pull request Oct 10, 2026
…fork note (ggml-org#78)

* ci(release): ship full self-contained Windows Vulkan/HIP bundles

readme: add Prism fork note (start with Bonsai-demo, main caveats)

* readme: fix Q2_0 model-file guidance (fork=Q2_0, mainline=Q2_0_g64, PQ2_0 future) + link demo status; ASCII punctuation

(cherry picked from commit fcd13b7)
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 23, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  Restores are unchanged.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 23, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 23, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 24, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…lls, DFlash, FA build grouping, server prompt cache)

The delivery content not owned by blocks 00-11: the CPU top-k block prefilter
(common/sampling.cpp), the x86 quants / repack / arch-fallback campaign wins,
the ggml-alloc compute-buffer drop/realloc plumbing, the per-backend
stage_gather / moe_cache_* / slab_* NULL iface fills, the DFlash F1 model
(src/models/dflash.cpp + common/speculative.cpp), and the FA per-(ncols,head)
template-instance build grouping.  With this block the Phase-1 tree equals the
reference tip af0595360 (release.json.tree) exactly.

Also fill the newly appended slab_compute_plain device-iface entry (NULL) in the CPU and RPC device
interfaces, matching the other optional slab_* fills: the field was appended by block 09 after these
fills were written, which left a -Wmissing-field-initializers warning.

Fold (r86): beta 12, slab-transient-absorption (draft ownership).  The speculative
init accepts the pre-loaded draft model from common_init_result, so the slab has
already measured the draft's per-device weights when it sizes itself; the
fallback load keeps other callers unchanged.

Fold (r96, PR ggml-org#189, briansp2020): `llama_io_write_host` queues its deferred state-save reads as
`ggml_backend_tensor_get_async` into one pinned staging buffer kept by the context, synchronizes each
backend once, then copies to the caller's buffer.  A checkpoint of a recurrent model is ~75 small
tensor ranges and under `-sm tensor` each was one synchronous read per device, so a checkpoint paid
~150 device syncs before every prompt chunk of a follow-up turn (Flash-Next + MTP: -55 ms / -59 ms
TTFT on the short follow-up turns, same-binary A/B against `LLAMA_STATE_ASYNC=0`).  States above
`LLAMA_STATE_ASYNC_MAX_MIB` (default 256 MiB) and `LLAMA_STATE_ASYNC=0` keep the synchronous path; so
does any state with a tensor no context backend owns.  The restore direction is folded in r119 (PR ggml-org#209), below.  The staging buffer is
retained by the context (16 MiB granular, bounded by the cap) and is one buffer per context, so state
saves on one context must not run concurrently.  `src/llama-context.cpp` also gains `#include
<algorithm>` for `std::find` (the patch as submitted does not compile without it).

Fold (r106): DFlash2 under `-sm tensor` (TODO ggml-org#78).  A new ggml `GGML_OP_ALL_GATHER` collective lets the
Meta backend materialise a whole vocab-split tensor on every device, so the DFlash2 selector's `ggml_top_k`
/ `ggml_get_rows` over the draft logits -- which come from the target's vocab-split `output.weight`
projection, and are therefore split on exactly the axis the selector reduces -- run locally instead of
aborting; the r54 clean rejection is removed.  The same fold gives a tensor-split drafter its compute
region out of the slab's arena when the unmapped VA spare is too small (narrow-2): a 1280 MiB draft compute
buffer against the estimator's 512 MiB tier is what exposed it, and any DFlash drafter under `-sm tensor`
now also takes the host path for the F1 device layer-input copy (a pre-existing crash on a Meta buffer).

Fold (r119, PR ggml-org#209, briansp2020): batch the device writes of a context state restore.  The restore side
of the r96 fold wrote the ~75 pieces with one synchronous `ggml_backend_tensor_set` per tensor, and under
`-sm tensor` each of those bounced through a pinned chunk and synchronized every device.  `llama_io_read_host`
now takes the context, packs the deferred pieces into the same pinned `state_stage` that the save side keeps,
queues each with `ggml_backend_tensor_set_async` on the backend that owns it, and synchronizes each backend
once.  It falls back to the per-tensor path when there is no context, a tensor's backend cannot be resolved,
the state exceeds `LLAMA_STATE_ASYNC_MAX_MIB`, or with `LLAMA_STATE_ASYNC_READ=0` (or `LLAMA_STATE_ASYNC=0`).
Measured on r118 (2x R9700 gfx1201, `-sm tensor`, q8_0 KV, 1571-token checkpoint): 35B-A3B restore 49 -> 40
ms and Flash-Next GSQ 89 -> 75 ms, with the DFlash2 draft 68 -> 57 ms; one GPU is ~2-6 ms slower because
the extra host copy has no multi-device sync to save.  The restored 48 greedy tokens equal a fresh run
(35B-A3B plain and DFlash2, Flash-Next), the four-axis MTP text/acceptance and the prefill-logit KLD are
unchanged, and `test-save-load-state` / `test-state-restore-fragmented` pass.  The stage is one buffer per
context, so saves and restores on one context must not run concurrently.

Per-block build (blocks own their code): this block also switches the r117 identity-preference layer-drop
ranking in `moe_cache_apply_identity_pref_locked` over to `heat_rank_vec()`.  Block 09 ranks it by `t.heat`
there so that block 09 builds on its own (`heat_rank_vec` is introduced here with the band-split prior); the
two rankings are byte-identical in block 09's tree, which has no decode counter.  The merged tree is
unchanged.

Fold (r130, PR ggml-org#210, overdoingism): server prompt-cache residency.  With a unified KV cache and
`--cache-idle-slots` (default on), every new task saved each idle slot to the host prompt cache and cleared
it, so two conversations taking turns on two slots copied their whole state out and back on every switch
(Qwen3.8-27B: 330 MiB of recurrent state plus 3.8 GB of KV at 110K tokens, 1.6-2.7 s per switch).  An idle
slot now keeps its context when a new task starts; the KV-full path (`try_clear_idle_slots`) saves the
least recently used idle slot to the prompt cache before clearing it (it used to purge it); a restore that
fails for want of cells held by another idle slot moves idle slots out of the way one at a time, with the
entry being restored held out of that eviction, and retries; and the slot-selection save holds the entry
the task is about to restore out of its own eviction.  `server_prompt_cache::find()` is split out of
`load()` for that.  The buffers of restored/evicted states are kept for the next save (smallest sufficient
spare, counted against `--cache-ram` together with the cached states).  `LLAMA_SERVER_LAZY_IDLE_SLOTS=0`
and `LLAMA_SERVER_CACHE_REUSE=0` restore the eager behaviour.  There are no arithmetic changes; a
different cache history places a sequence's KV in other cells, which is the already-accepted `--kv-unified`
non-determinism (`GREEDY-PURITY.md` section 38), and the patch's teacher-forced KLD is at the
long-context noise floor.  `find()` also skips an entry whose main state buffer was already consumed: a
restore that failed on the draft buffer leaves such an entry behind, and re-matching it compared against
zero bytes and reported success.  The upstream server test `unit/test_kv_keep_only_active.py` is updated
for the new default and covers the kill switch.

Fold (r130, PR ggml-org#212, overdoingism): DFlash prompt-ingest tail.  Every layer of the Qwen3.8-27B DFlash2
draft attends over a 2048-position sliding window and its KV cache is sized for the window, but
`process()` fed it every prompt row: a 110K prompt encoded 110K rows, all but the last ~2048 dropped
without ever being read, and each prompt batch waited on the target before the draft could start, which
also broke the queue of the target's ubatches.  When every draft layer has a window, the DFlash impl now
takes the prompt end from `set_prompt_end()` (the block-02 hook) and skips the prompt rows before the last
`n_swa` positions; a batch left with no rows returns before the target wait, and the first generation row
resets the threshold as in the MTP impl.  Exact because DFlash sets `LLAMA_SWA_TYPE_STANDARD`
unconditionally (`src/models/dflash.cpp`), so the mask is `p1 - p0 >= n_swa`.  New staging query
`llama_model_n_layer_swa()` in `src/llama-ext.h` (the per-layer pattern is not reachable through
`llama_model_meta_val_str()`, which skips array values).  `LLAMA_DFLASH_INGEST_TAIL=0` feeds every row.
Measured (3x gfx1201, `-sm tensor -mg 0`, 27B UD-Q4_K_XL plus DFlash2-Q4_K_M, `-fa on -ctk/ctv q8_0`):
prefill +8-12 % at 6K/26K/88K tokens (88.6K: 1271 -> 1395 t/s, no-draft 1415 t/s, so the draft's share of
the prefill goes 10.2 % -> 1.4 %), and 35B-A3B Q4_K_M plus its DFlash2 draft +14.6 % at 6.1K; greedy text
and draft counts byte-identical in every arm (one and two slots, `-ub 512` and `-ub 2048`).

Fold (r136, PR ggml-org#225, overdoingism): idle-slot parking.  ggml-org#210's lazy idle slots (ggml-org#210 is the r130 fold
above) keep an idle slot's KV resident in a unified cache, so a request that runs alone no longer starts
in an empty cache: its cells land after the resident ones and its attention range (n_kv) covers them.
Flash attention's tiling/split depends on those indices, so near-ties can flip: the reporter's 16-request
repeat test agreed on 4/16, and our same-slot schedule on 13/32.  A staging API (llama_memory_seq_park /
llama_memory_can_park, src/llama-ext.h) now moves a sequence's cells to the top of a unified cache below
the previously parked sequences, copying the K/V rows on the device and moving the cell state
(llama_kv_cells::mv, including seq_pos and the extension); seq_unpark moves one back to the lowest free
run and park_compact keeps the stack together.  New cells (find_slot) and get_n_kv() stop below the lowest
parked cell, so a running sequence attends over the same range at the same indices as with the idle slots
saved and cleared.  Parking requires one stream, unshared cells, V not transposed and no sliding window;
anything else keeps ggml-org#210 and logs once.  The server parks idle slots at task start and unparks the slots
that run (LLAMA_SERVER_PARK_IDLE_SLOTS, on unless 0, with the lazy idle slots and --kv-unified); a slot
whose cells are not one run of its own (shared through seq_cp, e.g. a cached prefix restore) is saved and
cleared, which is the lazy-off output.  Delivery fix on top of the PR: with --no-cache-idle-slots such a
slot is left resident instead (there is no saved copy to restore, and the lazy slots are meant to stay
resident).  LLAMA_KV_PARK_DEBUG=1 logs every move and refusal.  Measured (gfx1201, 27B UD-Q4_K_XL +
DFlash2, 4 slots, 131072, q8_0 KV, 16 prompts two rounds, cache_prompt false): 16/16 rounds and 32/32
equal to LLAMA_SERVER_LAZY_IDLE_SLOTS=0, against 13/16 and 13/32 with parking off; --fa off, a
sliding-window model and an unparkable cache are text-identical on/off, hybrid attention/recurrent is
16/16 equal to lazy-off, and 2 GPU -sm tensor works.  GREEDY-PURITY.md section 57.

Amended (r143): the MoE expert cache is process-global but its tables point at host expert masters the
MODEL owns, and nothing told the cache when those went away.  `llama_model_free` frees the masters; the
deferred arena sizing -- which fills EVERY registered table from its master -- then read a freed pointer:
a host memcpy SIGSEGV in `fill_slot_from_host`, from a table belonging to a model that no longer existed.
Reproduced on Flash-Next GSQ-IQ3_XXS, 2 GPU `-sm layer -ts 59,41 -ncmoe 24` (llama-bench runs one test per
`-ts` value and frees the model between them; the second test's first band pass died filling the first
model's tables), and in the same shape with `--host-experts pool`, whose master is the read-only model
mapping, so a host-buffer-free hook could not have covered it.  `llama_model_free` now calls the new
`llama_model_moe_cache_forget()` (device iface entry, appended at the very end of the struct for the
positional-initializer reason above), which drops the device's tables -- freeing each one's arena slot
range, remap staging, heat mirror, bounce ring and host pool -- re-points every id map so a reused
`ggml_tensor*` registers a fresh table instead of inheriting a dead model's geometry, forgets the
per-model preflight accounting, and un-sizes the cache so the next model sizes on its own first band pass
instead of silently running uncached (a second model previously inherited `g_sized` and never sized).
Single-model runs are unchanged: the teardown only adds the drop log lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants