Skip to content

CI: CMake: Separate build and test steps - #376

Merged
anzz1 merged 2 commits into
masterfrom
patch-ci-win-build-test
Mar 23, 2023
Merged

anzz1 merged 2 commits into
masterfrom
patch-ci-win-build-test

Conversation

@anzz1

@anzz1 anzz1 commented Mar 22, 2023 •

Copy link
Copy Markdown
Contributor

Otherwise the tests may be ran and pass even if the build has errors and thus the step itself can pass with errors in build

edit: separate build and test steps for all platforms.

@anzz1

anzz1 commented Mar 22, 2023

Copy link
Copy Markdown
Contributor Author

For future considerations:

In GitHub actions, each row of the run: commands are executed separately, irregardless what the previous input returned. The step determines "success" from the error code returned by the very last run command. As && means "execute if last output equals no error", cmake --build . --config Release && ctest -C Release --output-on-failure makes sure that the tests are only ran if the build succeeds, and that both needs to succeed for the CI step to return "success".

@anzz1 anzz1 added bug Something isn't working build Compilation issues labels Mar 22, 2023
Comment thread .github/workflows/build.yml Resolved
Also standardise step id names
@anzz1 anzz1 changed the title CI fix Windows, make sure build passes before running tests CI: CMake: Separate build and test steps Mar 23, 2023
@anzz1

anzz1 commented Mar 23, 2023 •

Copy link
Copy Markdown
Contributor Author

Separated build and test steps as separate tasks as pointed out by @Green-Sky . Obviously should've done that in the first place, idk how I didn't think of that.

Also standardised the step id names between the platforms for 'cleanliness' sake (and possibly future expansion / easier build log scraping / etc).

@Green-Sky Green-Sky left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good.

@anzz1
anzz1 merged commit e4412b4 into master Mar 23, 2023
@anzz1
anzz1 deleted the patch-ci-win-build-test branch March 23, 2023 02:21
Seunghhon pushed a commit to Seunghhon/llama.cpp that referenced this pull request Apr 26, 2026
* CI: Separate Build and Test steps (CMake)

* CI: Make sure build passes before running tests (CMake)

* CI: Standardise step id names
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
* CI: Separate Build and Test steps (CMake)

* CI: Make sure build passes before running tests (CMake)

* CI: Standardise step id names
ljubomirj pushed a commit to ljubomirj/llama.cpp that referenced this pull request May 6, 2026
* CI: Separate Build and Test steps (CMake)

* CI: Make sure build passes before running tests (CMake)

* CI: Standardise step id names
AlexiAlp pushed a commit to minghaop/llama.cpp that referenced this pull request Jun 2, 2026
* CI: Separate Build and Test steps (CMake)

* CI: Make sure build passes before running tests (CMake)

* CI: Standardise step id names
ddvnguyen pushed a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 1, 2026
… in capabilities (hydra_vortex ggml-org#375 ggml-org#376)

## ggml-org#375 — advertise combined/pipeline in engine_info

server-context.cpp: the engine_info (0x41) handler now lists 'combined' and
'pipeline' in the capabilities set. The build that ships this binary is
always the llama-engine fork, which carries the COMBINED code path; this
is the engine-side mirror of the static workers.json fields.

## ggml-org#376 — fail-open on RPC handshake

ggml-rpc.cpp: RPC_STATUS_ASSERT in negotiate_hello (line 363) replaced
with if(!status){log; return false;}. The TCP connection succeeds before
the RPC server's HELLO handler is ready, especially under compose where
two llama-engine instances start simultaneously. Aborting on a transient
HELLO failure crashes the head for no reason — returning false lets the
caller (get_socket -> get_device_count -> add_server) return 0 devs,
which keeps the head alive and degrades to solo instead.

Refs: ddvnguyen/hydra_vortex#375, ddvnguyen/hydra_vortex#376

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 1, 2026
* fork: bind-on-activation + registry epoch + ne-guard + fail-open (hydra_vortex ggml-org#368)

Makes COMBINED zero-copy binding (llama.cpp#20) swap-safe and re-callable
in preparation for dynamic quant swap (ggml-org#263, SWAP_QUANT 0x45). Also fixes
the COMBINED startup race (hydra_vortex ggml-org#357) by binding on demand at
SET_EXPERT_MODE("combined") instead of one-shot at startup.

Forward-compatible slice per docs/dynamic-quant-swap-combined.md: this
lands the protocol + binding + fail-open + tests now, so ggml-org#263 can plug
in the actual model free/reload against a stable contract.

## What

### 1. Registry epoch (ggml-rpc.cpp)
- rpc_msg_resolve_tensor_rsp gets a new uint32_t registry_epoch; the
  server returns its g_hydra_registry_epoch with every resolve.
- g_hydra_registry_epoch (atomic<uint32_t>) is bumped on every
  ggml_backend_rpc_clear_local_tensors() call. A head re-checks
  ggml_backend_rpc_get_remote_registry_epoch() before each use of a
  binding; mismatch = stale = the head must rebind or stay solo.

### 2. ggml_backend_rpc_clear_local_tensors
New public proc. Clears the local-tensor registry and bumps the epoch.
Idempotent. Foreign-buffer clearing is a defense-in-depth follow-up
(the head's epoch check is the primary safety).

### 3. ggml_backend_rpc_get_remote_registry_epoch
New public proc. Probes the peer's current epoch over RPC (reuses
RPC_CMD_RESOLVE_TENSOR with a sentinel name and reads back the epoch
field of the response — single round trip). Returns 0 on any failure;
callers must treat 0 as "couldn't verify" not "epoch is 0".

### 4. Fail-open in ggml_backend_rpc_bind_remote_tensor
Replaced RPC_STATUS_ASSERT(status) (which calls GGML_ABORT) with
"if (!status) { log; return nullptr; }" — peer drop, malformed
response, or transient RPC error must NOT crash the engine. The
bind result is still observable: nullptr means "fall back to solo".

### 5. ne-guard
ggml_backend_rpc_bind_remote_tensor takes a new const uint32_t*
expected_ne parameter (may be NULL to skip). After resolve, the
response's ne[] is compared element-wise; mismatch = refuse the bind
(return nullptr) — only type/nb (the quant layout) may differ between
bindings; ne (the count along each axis) is structural. A head bound
to a different peer's resident model fails loud, not by running on
the wrong weights (which would corrupt the KV cache silently).

### 6. llama_hydra_rebind_combined_experts (new)
Extracted from llama_hydra_load_combined_experts. Reuses the per-peer
backend (which is registered once at startup), frees the previous
binding's meta_ctx, allocates a new one, and re-runs the bind loop
with the new epoch + ne-guard. Per-peer resource map
(s_hydra_combined_bindings) owns the meta_ctx — replacing an entry
drops the previous ctx (the per-rebind leak fix; old code pushed
ctxs into a static vector and never freed).

### 7. llama_hydra_register_local_tensors_for_rpc re-callable
Now calls ggml_backend_rpc_clear_local_tensors before the registration
loop. First call: clear is a no-op (epoch 0 → 1). Subsequent calls
(after a model swap / re-register on the peer) bump the epoch again,
so any outstanding binding becomes observably stale.

### 8. SET_EXPERT_MODE(combined) handler now binds on activation
server-context.cpp:3504. Replaces the implicit reliance on a
startup-only binding. On each SET_EXPERT_MODE("combined") the head
calls llama_hydra_rebind_combined_experts and degrades to solo if
the rebind fails (peer unreachable, ne-guard, RPC error). This is
the ggml-org#357 fix: the head binds on demand when the peer is reachable,
every time. No abort path.

## Tests (test-hydra-rpc-bind.cpp)
- original round-trip (zero-copy read of server's live tensor)
- registry_epoch in resolve response
- ne-guard: rejected bind with mismatched shape (returns null)
- ne-guard: NULL expected_ne skips the check (legacy callers)
- missing name: returns null
- clear → epoch bumps; re-register → epoch unchanged (only clear bumps)
- re-bind after clear+re-register succeeds and observes the new epoch
- fail-open: bind to unreachable endpoint returns null (no abort)
- re-callable register is monotonic (no spurious epoch bump)

Run: `./bin/test-hydra-rpc-bind` → "OK: zero-copy RESOLVE_TENSOR/
bind_remote_tensor round-trips correctly (incl. ggml-org#368 epoch, ne-guard,
fail-open, re-callable register)"

## Build verification
- sm_120 (CUDA 13.2): `cmake --build build_sm120 --target llama-engine
  test-hydra-rpc-bind` — clean. Test runs and passes.
- sm_60 build deferred to P100 host (the AGENTS.md note about the
  gcc-15 / cuda-12.9 toolchain incompatibility is unchanged).

## Out of scope (lands with ggml-org#263)
The actual SWAP_QUANT model free/reload + re-register on the engine
(0x45 handler body) — slots into this contract once built. The Core
side (WorkerSchedulerService SWAPPING state) is in the parent repo
(ddvnguyen/hydra_vortex#368 §3).

## Cross-repo
- ddvnguyen/hydra_vortex#368 (parent issue)
- ddvnguyen/hydra_vortex#366 (merged — the SOLO_BUSY/COMBINED_SERVING
  state machine foundation that ggml-org#368 §3 extends)
- ddvnguyen/hydra_vortex#357 (startup race — fixed here by bind-on-
  activation)
- #22 (fork-side tracker)

AI assistance note: this commit was produced with AI assistance
(Claude) under explicit owner direction. Per AGENTS.md the private
fork ddvnguyen/llama.cpp is exempt from the upstream llama.cpp AI-
submission policy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(rpc): set registry_epoch on not-found path; bump RPC_PROTO_MINOR_VERSION to 1

P1: rpc_server::resolve_tensor left response.registry_epoch uninitialised
on the not-found early return. ggml_backend_rpc_get_remote_registry_epoch
probes with a sentinel name that is never found, so it was reading
indeterminate stack bytes instead of the real epoch. Fix: populate
registry_epoch before the not-found return, inside the lock where
g_hydra_registry_epoch is already loaded for the found path.

P2: rpc_msg_resolve_tensor_rsp gained a uint32_t registry_epoch field but
RPC_PROTO_MINOR_VERSION was not bumped. A new RTX head talking to an old
P100 server (not yet rebuilt) would size-mismatch on RESOLVE_TENSOR and
silently fail-open to permanent solo with no diagnostic. Fix: bump minor
to 1 and tighten negotiate_hello to require an exact minor match (reject
both older AND newer peers) so the mismatch is diagnosed at hello, not
buried in a silent fail-open.

Fixes review findings P1 and P2 on #23.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: fail-open on RPC handshake (HELLO) + advertise combined/pipeline in capabilities (hydra_vortex ggml-org#375 ggml-org#376)

## ggml-org#375 — advertise combined/pipeline in engine_info

server-context.cpp: the engine_info (0x41) handler now lists 'combined' and
'pipeline' in the capabilities set. The build that ships this binary is
always the llama-engine fork, which carries the COMBINED code path; this
is the engine-side mirror of the static workers.json fields.

## ggml-org#376 — fail-open on RPC handshake

ggml-rpc.cpp: RPC_STATUS_ASSERT in negotiate_hello (line 363) replaced
with if(!status){log; return false;}. The TCP connection succeeds before
the RPC server's HELLO handler is ready, especially under compose where
two llama-engine instances start simultaneously. Aborting on a transient
HELLO failure crashes the head for no reason — returning false lets the
caller (get_socket -> get_device_count -> add_server) return 0 devs,
which keeps the head alive and degrades to solo instead.

Refs: ddvnguyen/hydra_vortex#375, ddvnguyen/hydra_vortex#376

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: bind-on-activation and OT-pattern stripping for COMBINED mode

Two bugs prevented SET_EXPERT_MODE("combined") from ever activating when
the peer (RTX 3060) came up after the head (RTX 5060 Ti) had already started:

1. server-context.cpp: want_combined was gated on hydra_combined_head_attached,
   which is only set true when the startup llama_hydra_load_combined_experts
   call succeeds. If the peer was down at boot, the flag stayed false and the
   entire bind-on-activation code path (ggml-org#368) was unreachable. Fixed by gating
   on "is the engine configured as a combined head" (non-empty peer addr +
   OT pattern) instead, which correctly reflects what the engine is configured
   to do rather than an accident of startup ordering. Also latches
   hydra_combined_head_attached=true on first successful rebind so INFO RPC
   advertises combined capability.

2. llama-hydra.cpp: tensor_pattern from --combined-ot-pattern uses the
   override-tensor format "<name_regex>=<backend>" (e.g.
   "blk\.([0-9]+)\.ffn_.*_exps\.weight=CPU"), but the regex was matched
   against raw tensor names which never contain "=CPU". Fixed by stripping
   everything from the last '=' onward before compiling the regex.

With both fixes applied: 120/120 expert tensors across 40 layers are bound
to the peer on the first COMBINED request, and the engine reports
applied='combined' instead of falling back to solo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Hydra Engineering <hydra-engineering@local>
Co-authored-by: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 6, 2026
…pp + Phase C/E

ggml-org#376: The original fix (PR #26, commit 8d18d1b) addressed the RPC HELLO
handshake assert only. Remaining RPC_STATUS_ASSERT calls throughout
ggml-rpc.cpp still called GGML_ABORT when the RPC connection dropped
during model loading or inference — hitting buffer_free, graph_compute,
set_tensor, get_tensor, etc. This made COMBINED mode crash on any
transient peer disconnect.

Changes:
- ggml/src/ggml-rpc/ggml-rpc.cpp: Changed RPC_STATUS_ASSERT macro from
  GGML_ABORT to GGML_LOG_ERROR. Added null/connection guards to
  buffer_free_buffer, buffer_get_base, init_tensor, set_tensor,
  get_tensor, buffer_clear, cpy_tensor, graph_compute, alloc_buffer,
  get_alignment, get_max_size. All these paths now return failure
  gracefully instead of aborting the process.
- include/llama-hydra.h: Added llama_hydra_validate_quant_parity API
  for SWAP_QUANT tensor validation.
- src/llama-hydra.cpp: Implemented validation — opens target GGUF,
  iterates tensors matching pattern, compares shapes/types against
  loaded model.
- tools/server/server-context.h/cpp: SWAP_QUANT handler now resolves
  quant_key, calls validate, returns validation JSON. Added startup
  stage tracking (1-4) for staged health endpoint.
- tools/llama-engine/llama-engine.cpp: Set startup stages during init,
  augmented /health with staged readiness info. Added silent
  consumption of removed --yarn-ext-ctx / --yarn-orig-ctx flags.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 6, 2026
…ness

Replaces the fail-open approach (which masked the crash and introduced a
worse one) with the gate-then-degrade design. Fixes the ggml-org#376 startup race
at its source.

ggml-rpc.cpp (Step 1 — restore fail-stop transport):
- Revert RPC_STATUS_ASSERT from log-only back to GGML_ABORT. The log-only
  macro let 4 unconverted query helpers (get_max_size/get_alloc_size/
  get_device_memory/get_device_count) fall through and return an
  UNINITIALIZED response struct on peer failure — garbage sizes/counts,
  a non-deterministic downstream crash. Fail-stop is correct for the
  transport; recovery belongs one layer up.
- buffer_free_buffer: keep the null-socket guard but make the send itself
  fail-SOFT (log, don't abort) so degrade-to-solo / shutdown teardown can
  tolerate an already-gone peer.
- Zero-initialize the 4 query response structs as defense-in-depth.
- Keep the legitimate null-socket guards and graph_compute/init_tensor
  GGML_STATUS_FAILED returns added earlier.

llama-engine.cpp (Step 3+6 — readiness gate, the actual ggml-org#376 fix):
- New wait_for_peer_ready(): before registering the peer, poll the peer's
  staged /health (optional, via --peer-health-url) until rpc_active, then
  retry the RPC HELLO handshake (safe post-#26). Bounded (180s). On timeout
  the head loads SOLO — never aborts, never crash-loops.
- has_peer block now gates via wait_for_peer_ready instead of a cold
  ggml_backend_rpc_add_server that races the peer's startup.
- Add --peer-health-url flag.

Deferred to follow-up (documented in the ggml-org#376 plan on PR #31; require a
CUDA build env to verify safely — not attempted blind):
- Step 2: HTTP-before-load reorder (staged /health observable during load).
- Step 4: runtime degrade-to-solo on mid-inference peer loss.
- Step 5: combined/degraded fields on /health + INFO.
- Phase C (quant-parity) still bundled; split to its own PR.

NOT built here (no CUDA/2-GPU env in this session); changes reviewed by
inspection. Needs cmake --build build_sm86_sm120 --target llama-engine.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 6, 2026
…ostics

Toward fully resolving ggml-org#376 (COMBINE RPC). Two peer-side changes in
rpc_server::graph_compute / graph_recompute (ggml-rpc.cpp):

- Convert the two GGML_ASSERT(status == GGML_STATUS_SUCCESS) to `return false`.
  Previously a failed graph compute aborted the *peer* process; now it returns
  a clean RPC error so the client fail-stops (and, once Step 4 lands, can
  degrade-to-solo). The peer stays alive.
- Add ggml-org#376-tagged GGML_LOG_ERROR to every previously-silent `return false` in
  graph_compute — especially `device >= backends.size()` (the prime suspect for
  the COMBINE "peer closes the connection" symptom: a device-index mismatch
  between the head's serialized graph and the peer's enumerated backends).

This does not by itself make COMBINE work — the graph_compute false-return
still needs a live COMBINE run to confirm which path fires (device-index vs
unresolved tensor). These logs pinpoint it in one run. Tracked in
hydra_vortex#376 (scope items 1-2).

NOT built here (no CUDA/2-GPU env). Reviewed by inspection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Jul 6, 2026
Two fixes for the COMBINE layer-split crash during warmup:

1. ggml/src/ggml-cuda/fattn.cu (line 579): GGML_ABORT -> log+return
   When ggml_cuda_get_best_fattn_kernel returns NONE (no kernel matches
   the tensor config on the peer's GPU), the old GGML_ABORT killed the
   3060 peer process. Now logs the tensor dims + device cc and returns
   gracefully. The graph compute caller sees a clean error instead of
   a fatal abort.

2. ggml/src/ggml-rpc/ggml-rpc.cpp (supports_op): reject FLASH_ATTN_EXT
   The RPC backend unconditionally returned true for all ops, so the
   scheduler assigned flash-attention ops to the RPC split. The 3060's
   CUDA backend then crashed because no flash-attn kernel handled that
   specific tensor config on sm_86. Now returns false for FLASH_ATTN_EXT,
   forcing the scheduler to place attention ops on the head's local GPU.
   Long-term fix: forward supports_op to the remote backend.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Aug 17, 2026
Two fixes for the COMBINE layer-split crash during warmup:

1. ggml/src/ggml-cuda/fattn.cu (line 579): GGML_ABORT -> log+return
   When ggml_cuda_get_best_fattn_kernel returns NONE (no kernel matches
   the tensor config on the peer's GPU), the old GGML_ABORT killed the
   3060 peer process. Now logs the tensor dims + device cc and returns
   gracefully. The graph compute caller sees a clean error instead of
   a fatal abort.

2. ggml/src/ggml-rpc/ggml-rpc.cpp (supports_op): reject FLASH_ATTN_EXT
   The RPC backend unconditionally returned true for all ops, so the
   scheduler assigned flash-attention ops to the RPC split. The 3060's
   CUDA backend then crashed because no flash-attn kernel handled that
   specific tensor config on sm_86. Now returns false for FLASH_ATTN_EXT,
   forcing the scheduler to place attention ops on the head's local GPU.
   Long-term fix: forward supports_op to the remote backend.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit to ddvnguyen/llama.cpp that referenced this pull request Aug 17, 2026
…ostics

Toward fully resolving ggml-org#376 (COMBINE RPC). Two peer-side changes in
rpc_server::graph_compute / graph_recompute (ggml-rpc.cpp):

- Convert the two GGML_ASSERT(status == GGML_STATUS_SUCCESS) to `return false`.
  Previously a failed graph compute aborted the *peer* process; now it returns
  a clean RPC error so the client fail-stops (and, once Step 4 lands, can
  degrade-to-solo). The peer stays alive.
- Add ggml-org#376-tagged GGML_LOG_ERROR to every previously-silent `return false` in
  graph_compute — especially `device >= backends.size()` (the prime suspect for
  the COMBINE "peer closes the connection" symptom: a device-index mismatch
  between the head's serialized graph and the peer's enumerated backends).

This does not by itself make COMBINE work — the graph_compute false-return
still needs a live COMBINE run to confirm which path fires (device-index vs
unresolved tensor). These logs pinpoint it in one run. Tracked in
hydra_vortex#376 (scope items 1-2).

NOT built here (no CUDA/2-GPU env). Reviewed by inspection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kiljoy001 pushed a commit to kiljoy001/llama.cpp that referenced this pull request Oct 26, 2026
…ml-org#376)

The one-column mmvq geometry gives each row its own 128-thread CTA; at
K=4096 every thread decodes one 32-element chunk. Eight rows per CTA keep
each row's K partition and reduction order, so results are bit-identical,
and on H200 the 248320x4096 LM head goes from 249 to 121 us, the 4096-12288
row projections 28-42% faster. Hopper only, rows >= 4096 and divisible by 8.
ravi9 pushed a commit to nazanin-beheshti/llama.cpp that referenced this pull request Nov 9, 2026
ggml-openvino: support Ling-mini-2.0 group-routed MoE model
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 26, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in

Re-based onto a691b23 (r236)

The rung collided with everything the streamed KV binds to: the memory instances (ggml-org#31141 no_alloc,
rotation constants moved into a per-cache buffer, ggml-org#31570 kv_rows), the Meta (tensor-split) device
(ggml-org#31447) and the qwen4exp rewrite.  8 files conflicted / 12 hunks (9 expected: src/models/qwen4exp.cpp
auto-merged, the D3 residue did not conflict this time and its 59/-7 lines all landed).  A
distinctive-added-line check over the 25 auto-merged files found no dropped delivery code.

D13 (memory instances) -- re-derived, not carried:
* llama_memory_params keeps upstream's `no_alloc` and adds the delivery's `kv_pool`
  (llama-context.cpp's designated init passes both); the three `hparams.no_alloc` reads the block
  added follow ggml-org#31141 out of the hparams and become the ctor's `no_alloc`.
* memory_breakdown() is re-derived over `ctxs_bufs.bufs` + `ctxs_bufs.no_alloc` instead of the old
  per-cache loop: upstream moved the no_alloc/plain accounting into llama_memory_bufs and added
  attn_rot_bufs (ggml-org#31073), whose bytes are summed on top.  The pool's mirror-to-host-bucket and the
  window's resident/spill split accounting are unchanged.
* the MTP draft window's llama_kv_cache construction drops the `n_pad` argument (ggml-org#31200), and the
  pool's cell count is rounded to whole PAGES (it used to round to the cache's n_pad, which no longer
  exists as a parameter -- n_ctx is unpadded now).
* create_memory() takes upstream's `params` name back (the delivery-side `params_l` rename is gone;
  the body was upstream's everywhere but two lines).
* src/llama-ext.h keeps upstream's classifier-free-guidance declaration, src/llama-memory.h keeps
  upstream's llama_memory_bufs struct, ggml-backend-meta.cpp keeps upstream's view-slab helpers next
  to ggml_backend_meta_kv_region_grow.  src/llama-context.cpp takes upstream's readback-sync hunk --
  the delivery side of it was stale F1 code (layer_inp_host_fill, deleted at R13).

D12 (quantized-KV state, rotation) -- the provider still binds at the BUFFER TYPE and no kernel
addresses cells differently: the rotation constants are a per-cache, per-layer buffer (attn_rot_bufs),
not cell-indexed, so they are outside the region; state_write/state_read keep going through the region
buffer's own copy.  Proven by the gates below, whose spilling arms really spill (16 mapping flips,
64 MiB host-backed) and whose state arm (win2mtp) takes the region path.

The r193 draft reserve is preserved (r236 absorbed the fit plumbing): common/common.cpp takes
upstream's common_fit_apply() call, and block 15's mtp_shared branch is folded into
common_draft_reserve_derive() -- the one function both `--fit` and the MoE preflight call.  Measured,
35B-A3B Q8_0 1 GPU -ncmoe 48 -c 262144 with --spec-type draft-mtp: window auto derives "draft CONTEXT
1102 MiB (kv 142 + compute 768 + slack 192)" -> arena 20527.5 MiB / 62.9 % residency; window 0 keeps
the flat 3584 MiB -> arena 17977.5 MiB / 55.1 %.  +2550 MiB of arena, +7.8 points.

Fixed on the way:
* src/llama-memory-hybrid.cpp passed its attention cache to the extended ctor positionally, so after
  upstream inserted `is_indexer` before `v_enabled` the delivery's `kv_pool` landed in `v_enabled`:
  the cache allocated NO V tensor and llama_kv_cache::cpy_v null-dereferenced on the first graph build
  (every hybrid/GDN model segfaulted at load; the dense 4B arm died before generating).  `is_indexer`
  is now named explicitly.  The other ctor call sites were audited: hybrid-idx already named it,
  model.cpp stops at `share`, and dsa/dsa-iswa/msa/dsv4 are upstream's and correct.
* ggml/src/ggml-cuda/indexer-score.cu is NOT an R16 drift but a latent R12 defect (b1b0fa807): the
  fused GGML_OP_INDEXER_SCORE node called ggml_rope_get_truncate(dst), and upstream's ggml-org#30206 added an
  assert that the argument is a ROPE/ROPE_BACK node.  Every qwen4exp sparse QSA decode run has
  aborted on this tree since R12 (no R12-R15 gate reaches that arm -- the coherence arms and both
  qwen4exp gates run the dense arm; block 15's residency gate reaches it because its `pref` arm sets
  LLAMA_QSA_DENSE_DECODE_UNTIL=0, and aborted after 63 generated tokens at ggml.c:4648).  Both call
  sites now pass /*truncate*/ true, which is the graph's own rope node default (ggml_rope_impl
  initialises no_trunc 0 and nothing calls ggml_rope_set_truncate on the indexer-key node) and the
  pre-ggml-org#30206 5-argument helper's unconditional floor/ceil, i.e. pre-re-base numerics.

Coherence (same session, same commands, this build family): dense 4B 1de99b7e6ee6, 30B-A3B
4b4d56191368, 35B-A3B 3 GPU tensor rccl 86b7f9b5aa80, Flash-Next GSQ 7a8734a9f1a6 -- all four
unchanged from R13.

Gates:
* gate-kv-residency.sh PASS.  Window: wref == wres == wspill be904e86f248, wres 0 flips / 0 MiB
  host-backed, wspill 16 flips / 64 MiB, every slide on the map grid.  Pool: pref == pres == pfloor
  f260d1824ab3, bad 0, 8192 pages (408.0 MiB) on pres vs 4104 (204.4 MiB) on pfloor, 252 resolves
  both, claims 137.7 -> 217.1 per resolve, hits 91.02 -> 89.63 %.  Multi-device (-sm layer 0,1):
  pmref == pmres == pmfloor f260d1824ab3, one mirror/pool/counter block per device, 2 counter blocks
  summed, 117.8 -> 268.1 claims per resolve.
* gate-kv-window-split.sh PASS, 38/38: one region per device on a 3-device 4B, a 27B at -c 524288
  sliding on BOTH devices (32 flips each), -c 1048576 windowed, 1-device unchanged, -nkvo still
  declines, all five fit arms (fixed/auto/ram/ram-drop/off), and win2mtp == ref2mtp with identical
  acceptance 0.46154 whose batched state save takes the region path.
* gate-spec-draft-window.sh PASS: LLAMA_SPEC_DRAFT_WINDOW=1024 gives "1024 cells per sequence, cache
  3072 cells ((win + 512) x 2)" and all six requests across both slots are byte-identical to win 0,
  acceptance identical (0.47222 / 17-36, 1.0 / 23-23).
* check-gpu-faults.sh --since the session start: clean.

r247 (issue ggml-org#293 follow-up): all three placements default OFF, and the pool stops being a size knob.

The MTP draft window shipped with `auto` as its default from r246 and that cost MTP decode whenever the
request was deeper than the window: measured -9.7 % on a `-sm tensor` split at ~105k tokens (65 536-cell
`auto` window 72.7 t/s against 80.5 off; text byte-identical; benchmarks/mtp-draft-window-depth.md).
`--spec-draft-kv-window` now defaults to 0 in BOTH `common_params` and `llama_context_params`, and `auto`
(cap or nothing) / `N` stay exactly as r246 defined them, as a conscious opt-in.

The three placements now read the same way -- default off, `auto` = the system picks, `N` = explicit:
  * `--spec-draft-kv-window [auto|N]`  (default 0)  truncates the DRAFTER's cache; lossy, measured caveat
  * `--kv-window [auto|N]`             (default 0)  the LOSSLESS resident window, promoted from the
    LLAMA_KV_RESIDENT_CELLS env var, which stays as the option's deprecated alias (the fit path and every
    shipped script keep working).  New `llama_context_params.kv_resident_cells`
  * `--kv-attendance-pool [on|off]`    (default off) the host-mirror + device page cache, renamed from
    `--kv-region-pool` (kept as an alias).  Its SIZE is no longer a knob: it is derived from the model
    (one decode band of the indexer working set, `QSA_DECODE_BAND x ceil(top_k / page)`), because a numeric
    request only ever bought ~1 point of hit rate for 2x the VRAM and `auto` had nothing to size it
    (TODO ggml-org#313, closed).  A legacy numeric size or `auto` is accepted and IGNORED, with a WARN saying so.

Default-OFF is what makes the window's cost a documented caveat instead of a shipped regression, and it
also means no default run carries a placement decision at all.

TODO ggml-org#314 (r247): --fit now NAMES the placements and takes neither.  With every block-15 placement off by
default, a config that no longer fits had no hint at all.  The fit's "does NOT fit" ERROR block lists
`--kv-window N` and `--kv-attendance-pool` with their measured costs (11-26 % of decode past the window's
depth; ~-48 % of prompt throughput for the pool) and says they are alternatives, skipping whichever is already
active; the fit's exception path prints the same block as a WARN, once per fit.  It takes NOTHING on the
user's behalf -- a placement chosen for the user is exactly the r246 -> r247 regression.

Also fixes a pre-existing units bug in the line above it: `ctx_mib` is a BYTE count, so the per-1024-token
figure printed 67721728 instead of 64.  The byte figure is kept (so the token estimate, whose units cancelled,
is unchanged) and divided by MiB only for display.

r363 amendment (GitHub PR ggml-org#369, @briansp2020): a batch that writes the KV mirror WITHOUT resolving
through the pool (a prefill chunk, the QSA dense/shortcut arm) left any resident copy of the cells it
wrote stale, so a second request over a shared prefix read the first request's K/V -- the writer rule
only re-filled a page when the batch that wrote it also resolved.  Measured on r362 (2 devices,
`-sm layer`, `LLAMA_KV_POOL_VERIFY=1`, an 18.1k request then a 4.1k request sharing its prefix):
227 M mismatching words and a wrong count in the answer; the fix reads 0 and the text equals the
resident sparse arm byte for byte (gfx1201 and gfx1100).  A non-resolving batch now drops the pool
pages it wrote (`ggml_kv_pool_drop`: the same `GGML_OP_KV_POOL`, op param 1 = 1), so the next resolve
claims and re-fills them from the authoritative mirror.  `LLAMA_KV_POOL_DROP=0` is the A/B kill
switch; without `--kv-attendance-pool` nothing is built (and the pool declines on an APU / a shared
host-device pool, so the fix is inert there).  The block-14 notes, `DIAGNOSTIC.md` 17.1 and
`INVARIANTS.md` r363 carry the record; `scripts/gate-kv-residency.sh` gains the two-request arm that
catches the class.

r364 amendment (the delivery-level half of the two-arm campaign's STEP 15, `TODO` ggml-org#376, closed):
a row-block DEVICE->HOST read is never a 2-D copy on this backend.  On ROCm a `hipMemcpy2DAsync` D2H into
host memory asks for a peer grant of the destination's pinned allocation to the copying device's agent,
and every buffer of the pinned host type (llama.cpp's output buffer above all) is allocated by ONE device
and read by ALL devices of a `-sm tensor` split, so a copy from a non-owning device needs that grant -- on
a box whose slabs leave the driver no room it is refused ("hsa_amd_agents_allow_access ... err 4096") and
the copy returns `invalid argument`, i.e. a hard abort of the request.  That is the abort `TODO` ggml-org#124
recorded for a windowed KV on a tensor split, where the delivery's answer was "the arguments are what the
caller got wrong"; they were not.  `ggml_cuda_rows_to_host()` serves all three sites (the buffer's
synchronous 2-D read, the KV region's row helper, and the async 2-D read) with a 1-D copy for a tight
block, the device-staged chunked form when the call may synchronize, and one 1-D copy per row otherwise;
a row larger than the 64 MiB staging pair is never staged.  The async read also selects its own device
(the write twin already did) -- it issued the copy on its context's stream without that.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 26, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in

Re-based onto a691b23 (r236)

The rung collided with everything the streamed KV binds to: the memory instances (ggml-org#31141 no_alloc,
rotation constants moved into a per-cache buffer, ggml-org#31570 kv_rows), the Meta (tensor-split) device
(ggml-org#31447) and the qwen4exp rewrite.  8 files conflicted / 12 hunks (9 expected: src/models/qwen4exp.cpp
auto-merged, the D3 residue did not conflict this time and its 59/-7 lines all landed).  A
distinctive-added-line check over the 25 auto-merged files found no dropped delivery code.

D13 (memory instances) -- re-derived, not carried:
* llama_memory_params keeps upstream's `no_alloc` and adds the delivery's `kv_pool`
  (llama-context.cpp's designated init passes both); the three `hparams.no_alloc` reads the block
  added follow ggml-org#31141 out of the hparams and become the ctor's `no_alloc`.
* memory_breakdown() is re-derived over `ctxs_bufs.bufs` + `ctxs_bufs.no_alloc` instead of the old
  per-cache loop: upstream moved the no_alloc/plain accounting into llama_memory_bufs and added
  attn_rot_bufs (ggml-org#31073), whose bytes are summed on top.  The pool's mirror-to-host-bucket and the
  window's resident/spill split accounting are unchanged.
* the MTP draft window's llama_kv_cache construction drops the `n_pad` argument (ggml-org#31200), and the
  pool's cell count is rounded to whole PAGES (it used to round to the cache's n_pad, which no longer
  exists as a parameter -- n_ctx is unpadded now).
* create_memory() takes upstream's `params` name back (the delivery-side `params_l` rename is gone;
  the body was upstream's everywhere but two lines).
* src/llama-ext.h keeps upstream's classifier-free-guidance declaration, src/llama-memory.h keeps
  upstream's llama_memory_bufs struct, ggml-backend-meta.cpp keeps upstream's view-slab helpers next
  to ggml_backend_meta_kv_region_grow.  src/llama-context.cpp takes upstream's readback-sync hunk --
  the delivery side of it was stale F1 code (layer_inp_host_fill, deleted at R13).

D12 (quantized-KV state, rotation) -- the provider still binds at the BUFFER TYPE and no kernel
addresses cells differently: the rotation constants are a per-cache, per-layer buffer (attn_rot_bufs),
not cell-indexed, so they are outside the region; state_write/state_read keep going through the region
buffer's own copy.  Proven by the gates below, whose spilling arms really spill (16 mapping flips,
64 MiB host-backed) and whose state arm (win2mtp) takes the region path.

The r193 draft reserve is preserved (r236 absorbed the fit plumbing): common/common.cpp takes
upstream's common_fit_apply() call, and block 15's mtp_shared branch is folded into
common_draft_reserve_derive() -- the one function both `--fit` and the MoE preflight call.  Measured,
35B-A3B Q8_0 1 GPU -ncmoe 48 -c 262144 with --spec-type draft-mtp: window auto derives "draft CONTEXT
1102 MiB (kv 142 + compute 768 + slack 192)" -> arena 20527.5 MiB / 62.9 % residency; window 0 keeps
the flat 3584 MiB -> arena 17977.5 MiB / 55.1 %.  +2550 MiB of arena, +7.8 points.

Fixed on the way:
* src/llama-memory-hybrid.cpp passed its attention cache to the extended ctor positionally, so after
  upstream inserted `is_indexer` before `v_enabled` the delivery's `kv_pool` landed in `v_enabled`:
  the cache allocated NO V tensor and llama_kv_cache::cpy_v null-dereferenced on the first graph build
  (every hybrid/GDN model segfaulted at load; the dense 4B arm died before generating).  `is_indexer`
  is now named explicitly.  The other ctor call sites were audited: hybrid-idx already named it,
  model.cpp stops at `share`, and dsa/dsa-iswa/msa/dsv4 are upstream's and correct.
* ggml/src/ggml-cuda/indexer-score.cu is NOT an R16 drift but a latent R12 defect (b1b0fa807): the
  fused GGML_OP_INDEXER_SCORE node called ggml_rope_get_truncate(dst), and upstream's ggml-org#30206 added an
  assert that the argument is a ROPE/ROPE_BACK node.  Every qwen4exp sparse QSA decode run has
  aborted on this tree since R12 (no R12-R15 gate reaches that arm -- the coherence arms and both
  qwen4exp gates run the dense arm; block 15's residency gate reaches it because its `pref` arm sets
  LLAMA_QSA_DENSE_DECODE_UNTIL=0, and aborted after 63 generated tokens at ggml.c:4648).  Both call
  sites now pass /*truncate*/ true, which is the graph's own rope node default (ggml_rope_impl
  initialises no_trunc 0 and nothing calls ggml_rope_set_truncate on the indexer-key node) and the
  pre-ggml-org#30206 5-argument helper's unconditional floor/ceil, i.e. pre-re-base numerics.

Coherence (same session, same commands, this build family): dense 4B 1de99b7e6ee6, 30B-A3B
4b4d56191368, 35B-A3B 3 GPU tensor rccl 86b7f9b5aa80, Flash-Next GSQ 7a8734a9f1a6 -- all four
unchanged from R13.

Gates:
* gate-kv-residency.sh PASS.  Window: wref == wres == wspill be904e86f248, wres 0 flips / 0 MiB
  host-backed, wspill 16 flips / 64 MiB, every slide on the map grid.  Pool: pref == pres == pfloor
  f260d1824ab3, bad 0, 8192 pages (408.0 MiB) on pres vs 4104 (204.4 MiB) on pfloor, 252 resolves
  both, claims 137.7 -> 217.1 per resolve, hits 91.02 -> 89.63 %.  Multi-device (-sm layer 0,1):
  pmref == pmres == pmfloor f260d1824ab3, one mirror/pool/counter block per device, 2 counter blocks
  summed, 117.8 -> 268.1 claims per resolve.
* gate-kv-window-split.sh PASS, 38/38: one region per device on a 3-device 4B, a 27B at -c 524288
  sliding on BOTH devices (32 flips each), -c 1048576 windowed, 1-device unchanged, -nkvo still
  declines, all five fit arms (fixed/auto/ram/ram-drop/off), and win2mtp == ref2mtp with identical
  acceptance 0.46154 whose batched state save takes the region path.
* gate-spec-draft-window.sh PASS: LLAMA_SPEC_DRAFT_WINDOW=1024 gives "1024 cells per sequence, cache
  3072 cells ((win + 512) x 2)" and all six requests across both slots are byte-identical to win 0,
  acceptance identical (0.47222 / 17-36, 1.0 / 23-23).
* check-gpu-faults.sh --since the session start: clean.

r247 (issue ggml-org#293 follow-up): all three placements default OFF, and the pool stops being a size knob.

The MTP draft window shipped with `auto` as its default from r246 and that cost MTP decode whenever the
request was deeper than the window: measured -9.7 % on a `-sm tensor` split at ~105k tokens (65 536-cell
`auto` window 72.7 t/s against 80.5 off; text byte-identical; benchmarks/mtp-draft-window-depth.md).
`--spec-draft-kv-window` now defaults to 0 in BOTH `common_params` and `llama_context_params`, and `auto`
(cap or nothing) / `N` stay exactly as r246 defined them, as a conscious opt-in.

The three placements now read the same way -- default off, `auto` = the system picks, `N` = explicit:
  * `--spec-draft-kv-window [auto|N]`  (default 0)  truncates the DRAFTER's cache; lossy, measured caveat
  * `--kv-window [auto|N]`             (default 0)  the LOSSLESS resident window, promoted from the
    LLAMA_KV_RESIDENT_CELLS env var, which stays as the option's deprecated alias (the fit path and every
    shipped script keep working).  New `llama_context_params.kv_resident_cells`
  * `--kv-attendance-pool [on|off]`    (default off) the host-mirror + device page cache, renamed from
    `--kv-region-pool` (kept as an alias).  Its SIZE is no longer a knob: it is derived from the model
    (one decode band of the indexer working set, `QSA_DECODE_BAND x ceil(top_k / page)`), because a numeric
    request only ever bought ~1 point of hit rate for 2x the VRAM and `auto` had nothing to size it
    (TODO ggml-org#313, closed).  A legacy numeric size or `auto` is accepted and IGNORED, with a WARN saying so.

Default-OFF is what makes the window's cost a documented caveat instead of a shipped regression, and it
also means no default run carries a placement decision at all.

TODO ggml-org#314 (r247): --fit now NAMES the placements and takes neither.  With every block-15 placement off by
default, a config that no longer fits had no hint at all.  The fit's "does NOT fit" ERROR block lists
`--kv-window N` and `--kv-attendance-pool` with their measured costs (11-26 % of decode past the window's
depth; ~-48 % of prompt throughput for the pool) and says they are alternatives, skipping whichever is already
active; the fit's exception path prints the same block as a WARN, once per fit.  It takes NOTHING on the
user's behalf -- a placement chosen for the user is exactly the r246 -> r247 regression.

Also fixes a pre-existing units bug in the line above it: `ctx_mib` is a BYTE count, so the per-1024-token
figure printed 67721728 instead of 64.  The byte figure is kept (so the token estimate, whose units cancelled,
is unchanged) and divided by MiB only for display.

r363 amendment (GitHub PR ggml-org#369, @briansp2020): a batch that writes the KV mirror WITHOUT resolving
through the pool (a prefill chunk, the QSA dense/shortcut arm) left any resident copy of the cells it
wrote stale, so a second request over a shared prefix read the first request's K/V -- the writer rule
only re-filled a page when the batch that wrote it also resolved.  Measured on r362 (2 devices,
`-sm layer`, `LLAMA_KV_POOL_VERIFY=1`, an 18.1k request then a 4.1k request sharing its prefix):
227 M mismatching words and a wrong count in the answer; the fix reads 0 and the text equals the
resident sparse arm byte for byte (gfx1201 and gfx1100).  A non-resolving batch now drops the pool
pages it wrote (`ggml_kv_pool_drop`: the same `GGML_OP_KV_POOL`, op param 1 = 1), so the next resolve
claims and re-fills them from the authoritative mirror.  `LLAMA_KV_POOL_DROP=0` is the A/B kill
switch; without `--kv-attendance-pool` nothing is built (and the pool declines on an APU / a shared
host-device pool, so the fix is inert there).  The block-14 notes, `DIAGNOSTIC.md` 17.1 and
`INVARIANTS.md` r363 carry the record; `scripts/gate-kv-residency.sh` gains the two-request arm that
catches the class.

r364 amendment (the delivery-level half of the two-arm campaign's STEP 15, `TODO` ggml-org#376, closed):
a row-block DEVICE->HOST read is never a 2-D copy on this backend.  On ROCm a `hipMemcpy2DAsync` D2H into
host memory asks for a peer grant of the destination's pinned allocation to the copying device's agent,
and every buffer of the pinned host type (llama.cpp's output buffer above all) is allocated by ONE device
and read by ALL devices of a `-sm tensor` split, so a copy from a non-owning device needs that grant -- on
a box whose slabs leave the driver no room it is refused ("hsa_amd_agents_allow_access ... err 4096") and
the copy returns `invalid argument`, i.e. a hard abort of the request.  That is the abort `TODO` ggml-org#124
recorded for a windowed KV on a tensor split, where the delivery's answer was "the arguments are what the
caller got wrong"; they were not.  `ggml_cuda_rows_to_host()` serves all three sites (the buffer's
synchronous 2-D read, the KV region's row helper, and the async 2-D read) with a 1-D copy for a tight
block, the device-staged chunked form when the call may synchronize, and one 1-D copy per row otherwise;
a row larger than the 64 MiB staging pair is never staged.  The async read also selects its own device
(the write twin already did) -- it issued the copy on its context's stream without that.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 27, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in

Re-based onto a691b23 (r236)

The rung collided with everything the streamed KV binds to: the memory instances (ggml-org#31141 no_alloc,
rotation constants moved into a per-cache buffer, ggml-org#31570 kv_rows), the Meta (tensor-split) device
(ggml-org#31447) and the qwen4exp rewrite.  8 files conflicted / 12 hunks (9 expected: src/models/qwen4exp.cpp
auto-merged, the D3 residue did not conflict this time and its 59/-7 lines all landed).  A
distinctive-added-line check over the 25 auto-merged files found no dropped delivery code.

D13 (memory instances) -- re-derived, not carried:
* llama_memory_params keeps upstream's `no_alloc` and adds the delivery's `kv_pool`
  (llama-context.cpp's designated init passes both); the three `hparams.no_alloc` reads the block
  added follow ggml-org#31141 out of the hparams and become the ctor's `no_alloc`.
* memory_breakdown() is re-derived over `ctxs_bufs.bufs` + `ctxs_bufs.no_alloc` instead of the old
  per-cache loop: upstream moved the no_alloc/plain accounting into llama_memory_bufs and added
  attn_rot_bufs (ggml-org#31073), whose bytes are summed on top.  The pool's mirror-to-host-bucket and the
  window's resident/spill split accounting are unchanged.
* the MTP draft window's llama_kv_cache construction drops the `n_pad` argument (ggml-org#31200), and the
  pool's cell count is rounded to whole PAGES (it used to round to the cache's n_pad, which no longer
  exists as a parameter -- n_ctx is unpadded now).
* create_memory() takes upstream's `params` name back (the delivery-side `params_l` rename is gone;
  the body was upstream's everywhere but two lines).
* src/llama-ext.h keeps upstream's classifier-free-guidance declaration, src/llama-memory.h keeps
  upstream's llama_memory_bufs struct, ggml-backend-meta.cpp keeps upstream's view-slab helpers next
  to ggml_backend_meta_kv_region_grow.  src/llama-context.cpp takes upstream's readback-sync hunk --
  the delivery side of it was stale F1 code (layer_inp_host_fill, deleted at R13).

D12 (quantized-KV state, rotation) -- the provider still binds at the BUFFER TYPE and no kernel
addresses cells differently: the rotation constants are a per-cache, per-layer buffer (attn_rot_bufs),
not cell-indexed, so they are outside the region; state_write/state_read keep going through the region
buffer's own copy.  Proven by the gates below, whose spilling arms really spill (16 mapping flips,
64 MiB host-backed) and whose state arm (win2mtp) takes the region path.

The r193 draft reserve is preserved (r236 absorbed the fit plumbing): common/common.cpp takes
upstream's common_fit_apply() call, and block 15's mtp_shared branch is folded into
common_draft_reserve_derive() -- the one function both `--fit` and the MoE preflight call.  Measured,
35B-A3B Q8_0 1 GPU -ncmoe 48 -c 262144 with --spec-type draft-mtp: window auto derives "draft CONTEXT
1102 MiB (kv 142 + compute 768 + slack 192)" -> arena 20527.5 MiB / 62.9 % residency; window 0 keeps
the flat 3584 MiB -> arena 17977.5 MiB / 55.1 %.  +2550 MiB of arena, +7.8 points.

Fixed on the way:
* src/llama-memory-hybrid.cpp passed its attention cache to the extended ctor positionally, so after
  upstream inserted `is_indexer` before `v_enabled` the delivery's `kv_pool` landed in `v_enabled`:
  the cache allocated NO V tensor and llama_kv_cache::cpy_v null-dereferenced on the first graph build
  (every hybrid/GDN model segfaulted at load; the dense 4B arm died before generating).  `is_indexer`
  is now named explicitly.  The other ctor call sites were audited: hybrid-idx already named it,
  model.cpp stops at `share`, and dsa/dsa-iswa/msa/dsv4 are upstream's and correct.
* ggml/src/ggml-cuda/indexer-score.cu is NOT an R16 drift but a latent R12 defect (b1b0fa807): the
  fused GGML_OP_INDEXER_SCORE node called ggml_rope_get_truncate(dst), and upstream's ggml-org#30206 added an
  assert that the argument is a ROPE/ROPE_BACK node.  Every qwen4exp sparse QSA decode run has
  aborted on this tree since R12 (no R12-R15 gate reaches that arm -- the coherence arms and both
  qwen4exp gates run the dense arm; block 15's residency gate reaches it because its `pref` arm sets
  LLAMA_QSA_DENSE_DECODE_UNTIL=0, and aborted after 63 generated tokens at ggml.c:4648).  Both call
  sites now pass /*truncate*/ true, which is the graph's own rope node default (ggml_rope_impl
  initialises no_trunc 0 and nothing calls ggml_rope_set_truncate on the indexer-key node) and the
  pre-ggml-org#30206 5-argument helper's unconditional floor/ceil, i.e. pre-re-base numerics.

Coherence (same session, same commands, this build family): dense 4B 1de99b7e6ee6, 30B-A3B
4b4d56191368, 35B-A3B 3 GPU tensor rccl 86b7f9b5aa80, Flash-Next GSQ 7a8734a9f1a6 -- all four
unchanged from R13.

Gates:
* gate-kv-residency.sh PASS.  Window: wref == wres == wspill be904e86f248, wres 0 flips / 0 MiB
  host-backed, wspill 16 flips / 64 MiB, every slide on the map grid.  Pool: pref == pres == pfloor
  f260d1824ab3, bad 0, 8192 pages (408.0 MiB) on pres vs 4104 (204.4 MiB) on pfloor, 252 resolves
  both, claims 137.7 -> 217.1 per resolve, hits 91.02 -> 89.63 %.  Multi-device (-sm layer 0,1):
  pmref == pmres == pmfloor f260d1824ab3, one mirror/pool/counter block per device, 2 counter blocks
  summed, 117.8 -> 268.1 claims per resolve.
* gate-kv-window-split.sh PASS, 38/38: one region per device on a 3-device 4B, a 27B at -c 524288
  sliding on BOTH devices (32 flips each), -c 1048576 windowed, 1-device unchanged, -nkvo still
  declines, all five fit arms (fixed/auto/ram/ram-drop/off), and win2mtp == ref2mtp with identical
  acceptance 0.46154 whose batched state save takes the region path.
* gate-spec-draft-window.sh PASS: LLAMA_SPEC_DRAFT_WINDOW=1024 gives "1024 cells per sequence, cache
  3072 cells ((win + 512) x 2)" and all six requests across both slots are byte-identical to win 0,
  acceptance identical (0.47222 / 17-36, 1.0 / 23-23).
* check-gpu-faults.sh --since the session start: clean.

r247 (issue ggml-org#293 follow-up): all three placements default OFF, and the pool stops being a size knob.

The MTP draft window shipped with `auto` as its default from r246 and that cost MTP decode whenever the
request was deeper than the window: measured -9.7 % on a `-sm tensor` split at ~105k tokens (65 536-cell
`auto` window 72.7 t/s against 80.5 off; text byte-identical; benchmarks/mtp-draft-window-depth.md).
`--spec-draft-kv-window` now defaults to 0 in BOTH `common_params` and `llama_context_params`, and `auto`
(cap or nothing) / `N` stay exactly as r246 defined them, as a conscious opt-in.

The three placements now read the same way -- default off, `auto` = the system picks, `N` = explicit:
  * `--spec-draft-kv-window [auto|N]`  (default 0)  truncates the DRAFTER's cache; lossy, measured caveat
  * `--kv-window [auto|N]`             (default 0)  the LOSSLESS resident window, promoted from the
    LLAMA_KV_RESIDENT_CELLS env var, which stays as the option's deprecated alias (the fit path and every
    shipped script keep working).  New `llama_context_params.kv_resident_cells`
  * `--kv-attendance-pool [on|off]`    (default off) the host-mirror + device page cache, renamed from
    `--kv-region-pool` (kept as an alias).  Its SIZE is no longer a knob: it is derived from the model
    (one decode band of the indexer working set, `QSA_DECODE_BAND x ceil(top_k / page)`), because a numeric
    request only ever bought ~1 point of hit rate for 2x the VRAM and `auto` had nothing to size it
    (TODO ggml-org#313, closed).  A legacy numeric size or `auto` is accepted and IGNORED, with a WARN saying so.

Default-OFF is what makes the window's cost a documented caveat instead of a shipped regression, and it
also means no default run carries a placement decision at all.

TODO ggml-org#314 (r247): --fit now NAMES the placements and takes neither.  With every block-15 placement off by
default, a config that no longer fits had no hint at all.  The fit's "does NOT fit" ERROR block lists
`--kv-window N` and `--kv-attendance-pool` with their measured costs (11-26 % of decode past the window's
depth; ~-48 % of prompt throughput for the pool) and says they are alternatives, skipping whichever is already
active; the fit's exception path prints the same block as a WARN, once per fit.  It takes NOTHING on the
user's behalf -- a placement chosen for the user is exactly the r246 -> r247 regression.

Also fixes a pre-existing units bug in the line above it: `ctx_mib` is a BYTE count, so the per-1024-token
figure printed 67721728 instead of 64.  The byte figure is kept (so the token estimate, whose units cancelled,
is unchanged) and divided by MiB only for display.

r363 amendment (GitHub PR ggml-org#369, @briansp2020): a batch that writes the KV mirror WITHOUT resolving
through the pool (a prefill chunk, the QSA dense/shortcut arm) left any resident copy of the cells it
wrote stale, so a second request over a shared prefix read the first request's K/V -- the writer rule
only re-filled a page when the batch that wrote it also resolved.  Measured on r362 (2 devices,
`-sm layer`, `LLAMA_KV_POOL_VERIFY=1`, an 18.1k request then a 4.1k request sharing its prefix):
227 M mismatching words and a wrong count in the answer; the fix reads 0 and the text equals the
resident sparse arm byte for byte (gfx1201 and gfx1100).  A non-resolving batch now drops the pool
pages it wrote (`ggml_kv_pool_drop`: the same `GGML_OP_KV_POOL`, op param 1 = 1), so the next resolve
claims and re-fills them from the authoritative mirror.  `LLAMA_KV_POOL_DROP=0` is the A/B kill
switch; without `--kv-attendance-pool` nothing is built (and the pool declines on an APU / a shared
host-device pool, so the fix is inert there).  The block-14 notes, `DIAGNOSTIC.md` 17.1 and
`INVARIANTS.md` r363 carry the record; `scripts/gate-kv-residency.sh` gains the two-request arm that
catches the class.

r364 amendment (the delivery-level half of the two-arm campaign's STEP 15, `TODO` ggml-org#376, closed):
a row-block DEVICE->HOST read is never a 2-D copy on this backend.  On ROCm a `hipMemcpy2DAsync` D2H into
host memory asks for a peer grant of the destination's pinned allocation to the copying device's agent,
and every buffer of the pinned host type (llama.cpp's output buffer above all) is allocated by ONE device
and read by ALL devices of a `-sm tensor` split, so a copy from a non-owning device needs that grant -- on
a box whose slabs leave the driver no room it is refused ("hsa_amd_agents_allow_access ... err 4096") and
the copy returns `invalid argument`, i.e. a hard abort of the request.  That is the abort `TODO` ggml-org#124
recorded for a windowed KV on a tensor split, where the delivery's answer was "the arguments are what the
caller got wrong"; they were not.  `ggml_cuda_rows_to_host()` serves all three sites (the buffer's
synchronous 2-D read, the KV region's row helper, and the async 2-D read) with a 1-D copy for a tight
block, the device-staged chunked form when the call may synchronize, and one 1-D copy per row otherwise;
a row larger than the 64 MiB staging pair is never staged.  The async read also selects its own device
(the write twin already did) -- it issued the copy on its context's stream without that.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 27, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in

Re-based onto a691b23 (r236)

The rung collided with everything the streamed KV binds to: the memory instances (ggml-org#31141 no_alloc,
rotation constants moved into a per-cache buffer, ggml-org#31570 kv_rows), the Meta (tensor-split) device
(ggml-org#31447) and the qwen4exp rewrite.  8 files conflicted / 12 hunks (9 expected: src/models/qwen4exp.cpp
auto-merged, the D3 residue did not conflict this time and its 59/-7 lines all landed).  A
distinctive-added-line check over the 25 auto-merged files found no dropped delivery code.

D13 (memory instances) -- re-derived, not carried:
* llama_memory_params keeps upstream's `no_alloc` and adds the delivery's `kv_pool`
  (llama-context.cpp's designated init passes both); the three `hparams.no_alloc` reads the block
  added follow ggml-org#31141 out of the hparams and become the ctor's `no_alloc`.
* memory_breakdown() is re-derived over `ctxs_bufs.bufs` + `ctxs_bufs.no_alloc` instead of the old
  per-cache loop: upstream moved the no_alloc/plain accounting into llama_memory_bufs and added
  attn_rot_bufs (ggml-org#31073), whose bytes are summed on top.  The pool's mirror-to-host-bucket and the
  window's resident/spill split accounting are unchanged.
* the MTP draft window's llama_kv_cache construction drops the `n_pad` argument (ggml-org#31200), and the
  pool's cell count is rounded to whole PAGES (it used to round to the cache's n_pad, which no longer
  exists as a parameter -- n_ctx is unpadded now).
* create_memory() takes upstream's `params` name back (the delivery-side `params_l` rename is gone;
  the body was upstream's everywhere but two lines).
* src/llama-ext.h keeps upstream's classifier-free-guidance declaration, src/llama-memory.h keeps
  upstream's llama_memory_bufs struct, ggml-backend-meta.cpp keeps upstream's view-slab helpers next
  to ggml_backend_meta_kv_region_grow.  src/llama-context.cpp takes upstream's readback-sync hunk --
  the delivery side of it was stale F1 code (layer_inp_host_fill, deleted at R13).

D12 (quantized-KV state, rotation) -- the provider still binds at the BUFFER TYPE and no kernel
addresses cells differently: the rotation constants are a per-cache, per-layer buffer (attn_rot_bufs),
not cell-indexed, so they are outside the region; state_write/state_read keep going through the region
buffer's own copy.  Proven by the gates below, whose spilling arms really spill (16 mapping flips,
64 MiB host-backed) and whose state arm (win2mtp) takes the region path.

The r193 draft reserve is preserved (r236 absorbed the fit plumbing): common/common.cpp takes
upstream's common_fit_apply() call, and block 15's mtp_shared branch is folded into
common_draft_reserve_derive() -- the one function both `--fit` and the MoE preflight call.  Measured,
35B-A3B Q8_0 1 GPU -ncmoe 48 -c 262144 with --spec-type draft-mtp: window auto derives "draft CONTEXT
1102 MiB (kv 142 + compute 768 + slack 192)" -> arena 20527.5 MiB / 62.9 % residency; window 0 keeps
the flat 3584 MiB -> arena 17977.5 MiB / 55.1 %.  +2550 MiB of arena, +7.8 points.

Fixed on the way:
* src/llama-memory-hybrid.cpp passed its attention cache to the extended ctor positionally, so after
  upstream inserted `is_indexer` before `v_enabled` the delivery's `kv_pool` landed in `v_enabled`:
  the cache allocated NO V tensor and llama_kv_cache::cpy_v null-dereferenced on the first graph build
  (every hybrid/GDN model segfaulted at load; the dense 4B arm died before generating).  `is_indexer`
  is now named explicitly.  The other ctor call sites were audited: hybrid-idx already named it,
  model.cpp stops at `share`, and dsa/dsa-iswa/msa/dsv4 are upstream's and correct.
* ggml/src/ggml-cuda/indexer-score.cu is NOT an R16 drift but a latent R12 defect (b1b0fa807): the
  fused GGML_OP_INDEXER_SCORE node called ggml_rope_get_truncate(dst), and upstream's ggml-org#30206 added an
  assert that the argument is a ROPE/ROPE_BACK node.  Every qwen4exp sparse QSA decode run has
  aborted on this tree since R12 (no R12-R15 gate reaches that arm -- the coherence arms and both
  qwen4exp gates run the dense arm; block 15's residency gate reaches it because its `pref` arm sets
  LLAMA_QSA_DENSE_DECODE_UNTIL=0, and aborted after 63 generated tokens at ggml.c:4648).  Both call
  sites now pass /*truncate*/ true, which is the graph's own rope node default (ggml_rope_impl
  initialises no_trunc 0 and nothing calls ggml_rope_set_truncate on the indexer-key node) and the
  pre-ggml-org#30206 5-argument helper's unconditional floor/ceil, i.e. pre-re-base numerics.

Coherence (same session, same commands, this build family): dense 4B 1de99b7e6ee6, 30B-A3B
4b4d56191368, 35B-A3B 3 GPU tensor rccl 86b7f9b5aa80, Flash-Next GSQ 7a8734a9f1a6 -- all four
unchanged from R13.

Gates:
* gate-kv-residency.sh PASS.  Window: wref == wres == wspill be904e86f248, wres 0 flips / 0 MiB
  host-backed, wspill 16 flips / 64 MiB, every slide on the map grid.  Pool: pref == pres == pfloor
  f260d1824ab3, bad 0, 8192 pages (408.0 MiB) on pres vs 4104 (204.4 MiB) on pfloor, 252 resolves
  both, claims 137.7 -> 217.1 per resolve, hits 91.02 -> 89.63 %.  Multi-device (-sm layer 0,1):
  pmref == pmres == pmfloor f260d1824ab3, one mirror/pool/counter block per device, 2 counter blocks
  summed, 117.8 -> 268.1 claims per resolve.
* gate-kv-window-split.sh PASS, 38/38: one region per device on a 3-device 4B, a 27B at -c 524288
  sliding on BOTH devices (32 flips each), -c 1048576 windowed, 1-device unchanged, -nkvo still
  declines, all five fit arms (fixed/auto/ram/ram-drop/off), and win2mtp == ref2mtp with identical
  acceptance 0.46154 whose batched state save takes the region path.
* gate-spec-draft-window.sh PASS: LLAMA_SPEC_DRAFT_WINDOW=1024 gives "1024 cells per sequence, cache
  3072 cells ((win + 512) x 2)" and all six requests across both slots are byte-identical to win 0,
  acceptance identical (0.47222 / 17-36, 1.0 / 23-23).
* check-gpu-faults.sh --since the session start: clean.

r247 (issue ggml-org#293 follow-up): all three placements default OFF, and the pool stops being a size knob.

The MTP draft window shipped with `auto` as its default from r246 and that cost MTP decode whenever the
request was deeper than the window: measured -9.7 % on a `-sm tensor` split at ~105k tokens (65 536-cell
`auto` window 72.7 t/s against 80.5 off; text byte-identical; benchmarks/mtp-draft-window-depth.md).
`--spec-draft-kv-window` now defaults to 0 in BOTH `common_params` and `llama_context_params`, and `auto`
(cap or nothing) / `N` stay exactly as r246 defined them, as a conscious opt-in.

The three placements now read the same way -- default off, `auto` = the system picks, `N` = explicit:
  * `--spec-draft-kv-window [auto|N]`  (default 0)  truncates the DRAFTER's cache; lossy, measured caveat
  * `--kv-window [auto|N]`             (default 0)  the LOSSLESS resident window, promoted from the
    LLAMA_KV_RESIDENT_CELLS env var, which stays as the option's deprecated alias (the fit path and every
    shipped script keep working).  New `llama_context_params.kv_resident_cells`
  * `--kv-attendance-pool [on|off]`    (default off) the host-mirror + device page cache, renamed from
    `--kv-region-pool` (kept as an alias).  Its SIZE is no longer a knob: it is derived from the model
    (one decode band of the indexer working set, `QSA_DECODE_BAND x ceil(top_k / page)`), because a numeric
    request only ever bought ~1 point of hit rate for 2x the VRAM and `auto` had nothing to size it
    (TODO ggml-org#313, closed).  A legacy numeric size or `auto` is accepted and IGNORED, with a WARN saying so.

Default-OFF is what makes the window's cost a documented caveat instead of a shipped regression, and it
also means no default run carries a placement decision at all.

TODO ggml-org#314 (r247): --fit now NAMES the placements and takes neither.  With every block-15 placement off by
default, a config that no longer fits had no hint at all.  The fit's "does NOT fit" ERROR block lists
`--kv-window N` and `--kv-attendance-pool` with their measured costs (11-26 % of decode past the window's
depth; ~-48 % of prompt throughput for the pool) and says they are alternatives, skipping whichever is already
active; the fit's exception path prints the same block as a WARN, once per fit.  It takes NOTHING on the
user's behalf -- a placement chosen for the user is exactly the r246 -> r247 regression.

Also fixes a pre-existing units bug in the line above it: `ctx_mib` is a BYTE count, so the per-1024-token
figure printed 67721728 instead of 64.  The byte figure is kept (so the token estimate, whose units cancelled,
is unchanged) and divided by MiB only for display.

r363 amendment (GitHub PR ggml-org#369, @briansp2020): a batch that writes the KV mirror WITHOUT resolving
through the pool (a prefill chunk, the QSA dense/shortcut arm) left any resident copy of the cells it
wrote stale, so a second request over a shared prefix read the first request's K/V -- the writer rule
only re-filled a page when the batch that wrote it also resolved.  Measured on r362 (2 devices,
`-sm layer`, `LLAMA_KV_POOL_VERIFY=1`, an 18.1k request then a 4.1k request sharing its prefix):
227 M mismatching words and a wrong count in the answer; the fix reads 0 and the text equals the
resident sparse arm byte for byte (gfx1201 and gfx1100).  A non-resolving batch now drops the pool
pages it wrote (`ggml_kv_pool_drop`: the same `GGML_OP_KV_POOL`, op param 1 = 1), so the next resolve
claims and re-fills them from the authoritative mirror.  `LLAMA_KV_POOL_DROP=0` is the A/B kill
switch; without `--kv-attendance-pool` nothing is built (and the pool declines on an APU / a shared
host-device pool, so the fix is inert there).  The block-14 notes, `DIAGNOSTIC.md` 17.1 and
`INVARIANTS.md` r363 carry the record; `scripts/gate-kv-residency.sh` gains the two-request arm that
catches the class.

r364 amendment (the delivery-level half of the two-arm campaign's STEP 15, `TODO` ggml-org#376, closed):
a row-block DEVICE->HOST read is never a 2-D copy on this backend.  On ROCm a `hipMemcpy2DAsync` D2H into
host memory asks for a peer grant of the destination's pinned allocation to the copying device's agent,
and every buffer of the pinned host type (llama.cpp's output buffer above all) is allocated by ONE device
and read by ALL devices of a `-sm tensor` split, so a copy from a non-owning device needs that grant -- on
a box whose slabs leave the driver no room it is refused ("hsa_amd_agents_allow_access ... err 4096") and
the copy returns `invalid argument`, i.e. a hard abort of the request.  That is the abort `TODO` ggml-org#124
recorded for a windowed KV on a tensor split, where the delivery's answer was "the arguments are what the
caller got wrong"; they were not.  `ggml_cuda_rows_to_host()` serves all three sites (the buffer's
synchronous 2-D read, the KV region's row helper, and the async 2-D read) with a 1-D copy for a tight
block, the device-staged chunked form when the call may synchronize, and one 1-D copy per row otherwise;
a row larger than the 64 MiB staging pair is never staged.  The async read also selects its own device
(the write twin already did) -- it issued the copy on its context's stream without that.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working build Compilation issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants