Skip to content

llama: read a state's tensors asynchronously and synchronize once - #16

Merged
lukekim merged 7 commits into
spiceai-b11803from
lukim/b11803-state-read-async
Oct 29, 2026
Merged

lukekim merged 7 commits into
spiceai-b11803from
lukim/b11803-state-read-async

Conversation

@lukekim

@lukekim lukekim commented Oct 28, 2026 •

Copy link
Copy Markdown

What this changes

Saving a sequence's state read every tensor with its own synchronous ggml_backend_tensor_get. The host writer now queues each read from a buffer that a non-host backend uses on that backend and synchronizes each backend once. The meta backend's async read now reads exactly what its synchronous read does, with each device's part queued on that device: tensors split in several segments, and reads at an offset (one sequence's cells of a recurrent state). A device whose slices in a buffer are all empty holds them in a dummy buffer with no data; the async read skips those slices, as the synchronous read does. Metal's async read takes a page-aligned destination only, so it now reads any other destination once its queue is done. A quantized tensor (a quantized KV cache) is still read synchronously, as before: a backend may keep one in a layout of its own that only its synchronous getter reads back, and CANN's async getter rejects quantized tensors.

Over RPC, a read of one row is queued on the backend either way, but a read of several rows of a split tensor (a 2D read) is queued only with GGML_RPC_GET_ASYNC=1, #8's opt-in. Without it, each such read still waits for its own round trip, as every read did before this change. A synchronous command goes through the same queue as the queued reads and waits for them, so the two can be mixed.

Why

On a tensor split over RPC a hybrid model's recurrent state is dozens of tensors read from every rank, so a prompt-cache checkpoint after each prompt cost one round trip per tensor. On GLM-5.3 split three ways a checkpoint save went from about 72 ms to 28 ms with this change, on an earlier base.

How it was measured

Three DGX Spark (GB10) nodes over 200 GbE RDMA serving GLM-5.3 (Q2_K_XL) split three ways (-sm tensor, the full-mesh all-reduce from #8), driven by the Spice runtime's llama.cpp engine with the head's own GPU reached over the NIC's RDMA loopback. Single-request decode over 8 fixed prompts, temperature 0: each prompt runs for 200 tokens and for 1 token, and the decode rate is (tokens − 1) / (T200 − T1). In the symmetric form an untimed one-token request on an unrelated prompt runs before each timed request, so both start from the same prompt-cache state; the standard form runs them back to back. Six sessions per run (one model load each), interleaved, three benches per session; every arm's replies are compared prompt by prompt.

arm build symmetric mean (range), tok/s standard mean (range), tok/s
P spiceai-b11803 at a337bb5 46.21 (45.34–47.28) 45.12 (44.58–45.65)
Z P + graph serializer/deserializer + async state read 48.86 (47.99–50.26) 46.99 (46.91–47.07)
M Z + LLAMA_KV_PAD=1024 50.14 (49.01–51.04) 48.32 (48.24–48.40)

Every arm ran with GGML_RPC_GET_ASYNC on, as every lever run on this lab does; without it the RPC part of this change covers only one-row reads (not measured). Replies: both Z sessions are identical to P on 8/8 prompts; M differs from P on 7/8 (see #15). 8 prompts per bench is too few samples for a P99, so none is stated.

Z carries this change together with the graph serializer/deserializer (#14): +5.7% symmetric / +4.1% standard over P, with no reply changed. Alone, on an earlier base, it measured about +1.2% on GLM single-request and multi-turn throughput; it was not measured alone on this base (not run).

Testing

  • The whole-run reply comparison above: every token identical with and without it (Z vs P).
  • test-meta-async-read (new): tensors split in two segments across two slices of the CPU device, along axis 0 and axis 1, with and without an empty slice; the synchronous and async reads of the whole tensor and of each row must return the bytes written. On 47073f7 it aborts on the empty slice (ggml-backend.cpp:461: GGML_ASSERT(tensor->data != NULL && "tensor not allocated") failed, exit 134, after the synchronous read of the same split matched); on 4371531 all 8 reads match (exit 0). test-meta-graph-slots passes on 4371531.
  • test-llama-context with CUDA on one GB10 (a non-host backend: the KV cache is in CUDA0 buffers, all 37 layers offloaded), base a337bb5 vs 4371531. These are the state cases: save/load/replay, sequence copy over host and device io, recurrent rollback and replay.
    • Qwen3-4B Q8_0: 12 passed, 3 skipped (recurrent-only cases), 0 failed on both builds, with identical per-case results.
    • The generated dummy model of each of 136 architectures: models: 136 passed, 0 failed on both builds, with identical per-case tables. Rollback and replay ran on the 12 recurrent architectures. Which device held their caches is not shown in these logs.
  • Metal (M3 Max, macOS 27.2), test-llama-context on Qwen3-0.6B Q8_0 and Qwen3.5-0.8B (hybrid), KV cache in MTL0 buffers. Metal's async read wraps the destination with newBufferWithBytesNoCopy, which Metal documents for page-aligned memory. Before d6c212f, 3868 of the 4094 async reads (counted under lldb on Qwen3.5) had a destination that is not page-aligned, against 0 of 224 on the base. The cases still passed, with Metal API validation on too. Since d6c212f such a destination is read once the queue is done: 0 of 226 async reads are unaligned. Both models pass with Metal API validation on (12 passed, 3 skipped; 15 passed) with per-case results identical to the base.
  • A quantized KV cache (fcae8cd), Metal, test-llama-context on Qwen3-0.6B, ggml_metal_get_tensor_async calls counted under lldb. With -ctk q8_0 -ctv q8_0 -fa on: base 70, previous head 77, fcae8cd 70, so its K and V are read synchronously as on the base. With f16: 90, 97, 97. Per-case results are identical to the base in both. On the base itself, with q8_0, cp_d and rf fail and cp_d_s segfaults, identically on every build, so that comparison leaves out cp_d_s.
  • Not run: CANN, or any other non-host backend besides CUDA, Metal and RPC (no such hardware here). CANN's quantized tensors take the synchronous path, as before.
  • Not run: upstream's CI suite on this branch.

Saving a sequence's state read every tensor with its own synchronous ggml_backend_tensor_get. On a tensor split over
RPC a hybrid model's recurrent state is dozens of tensors read from every rank, so a checkpoint after each prompt cost
a round trip per tensor. The host writer now queues each read from a buffer a non-host backend uses on that backend and
synchronizes each backend once. The meta backend's async read now reads exactly what its synchronous read does, with
each device's part queued on that device: tensors split in several segments, and reads at an offset (one sequence's
cells of a recurrent state).
Copilot AI balanced review requested due to automatic review settings October 28, 2026 21:35
@lukekim lukekim self-assigned this Oct 28, 2026
@github-actions github-actions Bot added the ggml label Oct 28, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Segmented recurrent-state saves can abort on empty slices, and multi-row RPC state reads still block by default instead of batching unless the async opt-in is enabled.

2 open issues
What changed in this PR

This PR aims to reduce state-save latency in llama.cpp by batching backend tensor reads, particularly for tensor-parallel models over RPC.

Changes:

  • Queue host state-writer reads on compatible non-host backends and synchronize each used backend once.
  • Extend meta-backend async reads to handle segmented tensors and nonzero row offsets.
  • Correct per-device offsets for single-segment split reads.
File Description
src/​llama-context.cpp Pass context backends to host state writers and batch tensor reads.
ggml/​src/​ggml-backend-meta.cpp Support segmented async reads and correct split-read offsets.

Review effort: Balanced

Comment thread ggml/src/ggml-backend-meta.cpp Resolved
Comment thread src/llama-context.cpp Resolved
A device whose slices of every tensor in a buffer are empty holds them in a zero-sized dummy buffer, and those
tensors have no data. The segmented async read passed such a slice to ggml_backend_tensor_get_2d_async, which
asserts the data pointer before it checks the size, so saving a state from that split aborted. The synchronous read
already passes through empty transfers; the async read now skips them.

test-meta-async-read splits tensors in two segments across two slices of the CPU device, along axis 0 and axis 1,
with and without an empty slice, and checks that the synchronous and async reads of the whole tensor and of each
row return the bytes written.
Copilot AI balanced review requested due to automatic review settings October 28, 2026 23:18
@lukekim

lukekim commented Oct 28, 2026

Copy link
Copy Markdown
Author

Addressed #16 (review):

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The async getter changes still need hardware round-trip validation for caller-owned host and state buffers on non-host backends, especially CANN, beyond the supplied CPU/meta and RPC coverage.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@lukekim

lukekim commented Oct 28, 2026

Copy link
Copy Markdown
Author

Addressed #16 (review):

  • CUDA round trip: ran test-llama-context's state cases with CUDA on one GB10: save/load/replay, sequence copy over host and device io, recurrent rollback and replay. The KV cache was in CUDA0 buffers (llama_kv_cache: CUDA0 KV buffer size = 5760.00 MiB, 37/37 layers offloaded), so state reads went through the async path into caller-owned host memory. Base a337bb5 and 4371531 give identical per-case results:
    • Qwen3-4B Q8_0: 12 passed, 3 skipped (recurrent-only), 0 failed.
    • The 136 generated architecture models: 136 passed, 0 failed. These logs don't show which device held those models' caches.
  • RPC: covered by the three-node GLM run in the description (Z vs P, every reply identical).
  • CANN: not run; there's no Ascend hardware here. The description lists it under Not run.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

State saves on Metal can fail validation or assert because serialized tensor destinations are passed to an API requiring page-aligned addresses and page-sized lengths that those destinations do not guarantee.

1 open issue

Review effort: Balanced

Comment thread src/llama-context.cpp Resolved
GCC's -Wcast-qual rejected passing the address of a const split as the meta device's userdata (CI builds with
-Werror). The splits are now non-const.
…getter

The async read wraps the destination with newBufferWithBytesNoCopy, which Metal documents for page-aligned memory
only. Reading a state through the host writer's queued reads sends Metal destinations inside the serialized state:
in test-llama-context on Qwen3.5-0.8B, 3868 of 4094 async reads had a destination off a 16 KiB page boundary, against
0 of 224 before. A destination that is not page-aligned is now read once the queue is done, as for a backend without
an async getter; an aligned one keeps the async read. With this, none of the 226 async reads is unaligned, and the
state cases pass with Metal API validation on, as before on that macOS, with the same per-case results as the base.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 00:36
@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Addressed #16 (review):

  • Metal page alignment: fixed in d6c212f. A destination that is not page-aligned is read once Metal's queue is done. Before the fix, 3868 of 4094 async reads on Qwen3.5-0.8B were unaligned; after it, 0 of 226. The failure itself didn't reproduce on macOS 27.2 with Metal API validation on. llama: read a state's tensors asynchronously and synchronize once #16 (comment)
  • CI ctest (UNDEFINED) and ubuntu (arm64): my new test passed the address of a const split as void *, which GCC's -Wcast-qual rejects under -Werror. Fixed in 581087f. GCC 13.3 with -Wcast-qual -Werror rejected the old file (exit 1, same message as CI) and accepts the new one (exit 0). test-meta-async-read still passes (8 reads match). ubuntu (x64) was cancelled when arm64 failed.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Backend-owner validation is needed for CANN’s async reads into caller-owned host memory and state-save correctness, which the reported CUDA, Metal, and RPC runs do not cover.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

The async getter asserted the tensor was not quantized: a quantized tensor may be held in
CANN's own layout, which only the synchronous getter transforms back. A saved state now
reads every tensor of a backend's buffer through its async getter, a quantized KV cache
included, so the getter reads such a tensor once the stream is done instead of aborting.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 06:23
@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Round on 4f39d1e, answering Copilot review #16 (review) (backend-owner validation for CANN):

  • Unchanged by this PR, already done upstream: upstream reads embeddings asynchronously into caller-owned std::vectors on every backend, CANN included (src/llama-context.cpp:1862, which predates this PR). So async reads of non-quantized tensors into plain host memory are not new with this PR.
  • What did change for CANN: ggml_backend_cann_get_tensor_async asserted !ggml_is_quantized(tensor->type), because CANN may keep a quantized tensor in its own layout, which only the sync getter transforms back. With this PR a saved state reads a quantized KV cache (-ctk q8_0) through the async getter, so on CANN that save would have aborted where the base read it synchronously. 4f39d1e makes the getter synchronize its stream and use the sync getter for a quantized tensor instead of aborting, as d6c212f does for Metal's unaligned destinations.
    • Unverified, code inspection only: not run, because no CANN hardware or toolkit is available here. The abort is read from the source, not observed, and so is the fix. A CANN owner's run of test-llama-context with -ctk q8_0 would settle both.
  • Other backends with an async getter: CUDA and SYCL assert only that the buffer is their own device buffer. backend_of picks the backend whose supports_buft accepts the buffer, and state tensors are not in split buffers. Vulkan, Hexagon, ET and RPC have no type restriction in theirs. Metal's alignment restriction is handled in d6c212f, and CUDA and Metal runs are in the description.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Partial Q4_0/Q8_0 reads can corrupt memory because the CANN fallback transforms the entire tensor despite allocating only the requested size, causing out-of-bounds reads and writes.

1 open issue

Review effort: Balanced

Comment thread ggml/src/ggml-cann/ggml-cann.cpp Resolved
A backend may hold a quantized tensor in a layout of its own that only its synchronous getter
reads back: CANN's async getter rejects quantized tensors, and its synchronous getter
converts the whole tensor even for a partial read. The host writer now reads a quantized
tensor (a quantized KV cache) with ggml_backend_tensor_get, as the base does, and queues
every other tensor of a backend's buffer as before.
Copilot AI balanced review requested due to automatic review settings October 29, 2026 06:59
@lukekim

lukekim commented Oct 29, 2026

Copy link
Copy Markdown
Author

Round on fcae8cd:

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approved

No active review issues were identified for the state-read batching changes and supporting backend fixes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@lukekim
lukekim merged commit ed4028b into spiceai-b11803 Oct 29, 2026
23 of 44 checks passed
lukekim added a commit that referenced this pull request Oct 29, 2026
Carries the two fork PRs that landed on spiceai-b11803 after the upstream merges were cut: LLAMA_KV_PAD (#15) and the
asynchronous state read (#16). Upstream b11999 pads n_kv to a fixed 256 where #15 read the cache's n_pad, so the pad is
now the larger of 256 and LLAMA_KV_PAD's.
lukekim added a commit that referenced this pull request Oct 29, 2026
lukekim added a commit to spiceai/spiceai that referenced this pull request Nov 1, 2026
…el's tensors

For a model split across nodes, configure_comm also sets GGML_RPC_GET_ASYNC and GGML_RPC_SET_ASYNC, as it sets the
mesh settings: the head queues its reads and writes of the ranks' tensors instead of waiting on each round trip.
llama.cpp leaves both off for other RPC clients; only the split reaches the ranks over RPC. A setting already in the
environment wins. The meta backend's async read is correct from spiceai/llama.cpp#16, which this pin carries.
WhaleChao pushed a commit to WhaleChao/spiceai that referenced this pull request Nov 2, 2026
Pin spiceai/llama.cpp b11999-spiceai.1: upstream b11984 and then b11999 merged into spiceai-b11803, which is
merged in again at spiceai/llama.cpp#16. This brings Mistral Large 4 (mistral-large4) and its DSpark drafter, and DeepSeek-V4.1 now
runs on upstream's deepseek41 model with the fork's fixes on top. The fork-patch ledger is re-audited against the
new revision: spiceai#14's RPC graph serialization, spiceai#16's asynchronous state reads and glm5-next's DFlash layer inputs get
rows, spiceai#15's LLAMA_KV_PAD joins the opt-in levers, and the DeepSeek-V4 zero
output-group check gets a row and a guard, a crafted GGUF header that must fail its load on that check.
tsenart pushed a commit to perfloop-oss/spiceai that referenced this pull request Nov 6, 2026
…el's tensors (spiceai#15831)

For a model split across nodes, configure_comm also sets GGML_RPC_GET_ASYNC and GGML_RPC_SET_ASYNC, as it sets the
mesh settings: the head queues its reads and writes of the ranks' tensors instead of waiting on each round trip.
llama.cpp leaves both off for other RPC clients; only the split reaches the ranks over RPC. A setting already in the
environment wins. The meta backend's async read is correct from spiceai/llama.cpp#16, which this pin carries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants