From 2c1c56cf3a81fabfc9cf96a8484d43c8d14576fc Mon Sep 17 00:00:00 2001 From: Carmen Esteban Date: Sun, 5 Apr 2026 18:15:45 +0200 Subject: [PATCH] Eliminate KV cache memcpy: zero-copy via direct data pointers Instead of memcpy-ing the entire KV cache history into new GGML tensors each decode step (~52MB at 100 tokens for Qwen2.5-32B), point the GGML tensor data pointer directly at the cache's host memory. The cache memory is long-lived (persists across steps) and contiguous, so GGML can read it directly during graph computation without copying. Co-Authored-By: Claude Opus 4.6 --- src/ar-graph.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/ar-graph.cpp b/src/ar-graph.cpp index 64e7a60..58247e2 100644 --- a/src/ar-graph.cpp +++ b/src/ar-graph.cpp @@ -133,19 +133,17 @@ static struct ggml_cgraph * ar_build_graph( struct ggml_tensor * V_full; if (n_past > 0) { - // Load cached K,V as input tensors + // Zero-copy: point GGML tensor directly at cache memory // Shape: [n_embd_head, n_head_kv, n_past] struct ggml_tensor * K_cached = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd_head, n_head_kv, n_past); ggml_set_input(K_cached); - memcpy(K_cached->data, cache->k_data(il), - (size_t)n_past * cache->pos_stride() * sizeof(float)); + K_cached->data = (void *)cache->k_data(il); struct ggml_tensor * V_cached = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd_head, n_head_kv, n_past); ggml_set_input(V_cached); - memcpy(V_cached->data, cache->v_data(il), - (size_t)n_past * cache->pos_stride() * sizeof(float)); + V_cached->data = (void *)cache->v_data(il); K_full = ggml_concat(ctx, K_cached, K_new, 2); V_full = ggml_concat(ctx, V_cached, V_new, 2);