Commit b9fcf77a4 for llama.cpp

commit b9fcf77a499205b15bed35b7b2f3495571bca8cf
Author: Radoslav Gerganov <rgerganov@gmail.com>
Date:   Thu Dec 3 21:08:03 2026 +0200

    rpc : fix stale alloc_size cache entry reused for larger src tensor (#33611)

    The RPC client's alloc-size cache key for
    ggml_backend_rpc_buffer_type_get_alloc_size() omits the src tensors.
    For ops in ggml_op_alloc_size_may_expand() the server-side allocation
    size can depend on a src, e.g. TOP_K on Metal with nelements(src0) or
    FLASH_ATTN_EXT on CUDA/Metal with the KV length. A size cached for a
    small src could be reused for a larger one, overrunning the
    server-side compute buffer.

    Key the cache on the full layout of the tensor and its srcs, reusing
    the supports_op key (renamed to op_layout_key), and move the cache and
    its mutex from function-level statics into
    ggml_backend_rpc_buffer_type_context.

    ref: #30794

    Testing done (on Apple M4 Max):
        TEST_RPC_DEVICE=MTL0 bash tests/test-rpc-multi-server.sh \
            build/bin/ggml-rpc-server build/bin/test-rpc-multi-server


    Assisted-by: Claude Opus 5.5

    Co-authored-by: Brian Woods <me@brian.biz>

diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp
index 92796e6c0..fe1a60268 100644
--- a/ggml/src/ggml-rpc/ggml-rpc.cpp
+++ b/ggml/src/ggml-rpc/ggml-rpc.cpp
@@ -338,11 +338,13 @@ struct ggml_backend_rpc_device_context {
 };

 struct ggml_backend_rpc_buffer_type_context {
-    std::string endpoint;
-    uint32_t    device;
-    std::string name;
-    size_t      alignment;
-    size_t      max_size;
+    std::string                          endpoint;
+    uint32_t                             device;
+    std::string                          name;
+    size_t                               alignment;
+    size_t                               max_size;
+    std::mutex                           alloc_size_mutex;
+    std::unordered_map<uint64_t, size_t> alloc_size_cache;
 };

 class rpc_dispatcher;
@@ -372,6 +374,37 @@ static uint64_t fnv_hash(const uint8_t * data, size_t len, uint64_t hash = 0xcbf
     return hash;
 }

+// full layout of the op and its sources, without ids, addresses, names and buffers
+// used as the cache key for both supports_op and get_alloc_size
+static uint64_t op_layout_key(const ggml_tensor * op) {
+    struct op_layout_key_tensor {
+        uint32_t type;
+        uint32_t op;
+        int32_t  op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
+        int64_t  ne[GGML_MAX_DIMS];
+        uint64_t nb[GGML_MAX_DIMS];
+    };
+    op_layout_key_tensor key[1 + GGML_MAX_SRC];
+    memset(key, 0, sizeof(key));
+    for (int i = 0; i < 1 + GGML_MAX_SRC; i++) {
+        const ggml_tensor * t = i == 0 ? op : op->src[i - 1];
+        if (t == nullptr) {
+            key[i].type = UINT32_MAX;
+            continue;
+        }
+        key[i].type = t->type;
+        if (i == 0) {
+            key[i].op = t->op;
+            memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params));
+        }
+        for (int j = 0; j < GGML_MAX_DIMS; j++) {
+            key[i].ne[j] = t->ne[j];
+            key[i].nb[j] = t->nb[j];
+        }
+    }
+    return fnv_hash((const uint8_t *)key, sizeof(key));
+}
+
 // builds a variable-size request; the buffer must not change once queued
 struct rpc_writer {
     std::shared_ptr<std::vector<uint8_t>> buf = std::make_shared<std::vector<uint8_t>>();
@@ -1156,43 +1189,15 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty
         // TODO: change rpc_tensor nb to 64-bit int
         const size_t min_size = ggml_nbytes(tensor);

-        // Cache key for calls to read the alloc_size.
-        // We deliberately exclude src tensor dimensions from the key because:
-        // 1. For CPU backends, alloc_size = ggml_nbytes(output) regardless of src shapes
-        // 2. For GPU backends, the reservation graph uses max dimensions, so the
-        //    cached value from reservation is always >= any subsequent request
-        // 3. Including src dims causes cache misses per-ubatch (e.g. growing KV cache)
-        //    which blocks the main thread behind in-flight GRAPH_COMPUTE commands
-        struct alloc_size_cache_key {
-            uint32_t device;
-            uint32_t type;
-            uint32_t op;
-            int32_t  op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
-            uint32_t ne[GGML_MAX_DIMS];
-            uint64_t nb[GGML_MAX_DIMS];
-        };
-
-        alloc_size_cache_key key = {};
-        key.device = buft_ctx->device;
-        key.type = tensor->type;
-        key.op = tensor->op;
-        memcpy(key.op_params, tensor->op_params, sizeof(key.op_params));
-        for (int i = 0; i < GGML_MAX_DIMS; i++) {
-            key.ne[i] = (uint32_t)tensor->ne[i];
-            key.nb[i] = (uint64_t)tensor->nb[i];
-        }
-
-        uint64_t cache_hash = fnv_hash((const uint8_t *)&key, sizeof(key));
-        cache_hash = fnv_hash((const uint8_t *)buft_ctx->endpoint.data(), buft_ctx->endpoint.size(), cache_hash);
-
-        // alloc sizes are immutable for a given tensor configuration
-        static std::mutex cache_mutex;
-        static std::unordered_map<uint64_t, size_t> cache;
-
+        // alloc sizes are immutable for a given layout of the tensor and its srcs
+        // the srcs must be part of the key: some backends reserve extra memory that scales with a src,
+        // e.g. FLASH_ATTN_EXT with the KV length or TOP_K with nelements(src0)
+        // ref: https://github.com/ggml-org/llama.cpp/issues/30794
+        const uint64_t key = op_layout_key(tensor);
         {
-            std::lock_guard<std::mutex> lock(cache_mutex);
-            auto it = cache.find(cache_hash);
-            if (it != cache.end()) {
+            std::lock_guard<std::mutex> lock(buft_ctx->alloc_size_mutex);
+            auto it = buft_ctx->alloc_size_cache.find(key);
+            if (it != buft_ctx->alloc_size_cache.end()) {
                 LOG_DBG3("[%s] cache hit: %s -> %s\n", __func__, rpc_log_format_tensor(tensor).c_str(),
                          rpc_log_format_size(it->second).c_str());
                 return std::max<size_t>(it->second, min_size);
@@ -1216,8 +1221,8 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty
         const auto response = dispatcher->call<RPC_CMD_GET_ALLOC_SIZE>(request);

         {
-            std::lock_guard<std::mutex> lock(cache_mutex);
-            cache[cache_hash] = response.alloc_size;
+            std::lock_guard<std::mutex> lock(buft_ctx->alloc_size_mutex);
+            buft_ctx->alloc_size_cache[key] = response.alloc_size;
         }

         LOG_DBG2("[%s] %s -> alloc_size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(),
@@ -1412,11 +1417,13 @@ ggml_backend_buffer_type_t ggml_backend_rpc_buffer_type(const char * endpoint, u
     size_t alignment = get_alignment(dispatcher, device);
     size_t max_size = get_max_size(dispatcher, device);
     ggml_backend_rpc_buffer_type_context * buft_ctx = new ggml_backend_rpc_buffer_type_context {
-        /* .endpoint  = */ endpoint,
-        /* .device    = */ device,
-        /* .name      = */ buft_name,
-        /* .alignment = */ alignment,
-        /* .max_size  = */ max_size
+        /* .endpoint         = */ endpoint,
+        /* .device           = */ device,
+        /* .name             = */ buft_name,
+        /* .alignment        = */ alignment,
+        /* .max_size         = */ max_size,
+        /* .alloc_size_mutex = */ {},
+        /* .alloc_size_cache = */ {},
     };
     auto reg = ggml_backend_rpc_add_server(endpoint);
     ggml_backend_buffer_type_t buft = new ggml_backend_buffer_type {
@@ -2891,36 +2898,6 @@ static ggml_backend_buffer_type_t ggml_backend_rpc_device_get_buffer_type(ggml_b
     GGML_UNUSED(dev);
 }

-// full layout of the op and its sources, without ids, addresses, names and buffers
-static uint64_t supports_op_key(const ggml_tensor * op) {
-    struct supports_op_key_tensor {
-        uint32_t type;
-        uint32_t op;
-        int32_t  op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
-        int64_t  ne[GGML_MAX_DIMS];
-        uint64_t nb[GGML_MAX_DIMS];
-    };
-    supports_op_key_tensor key[1 + GGML_MAX_SRC];
-    memset(key, 0, sizeof(key));
-    for (int i = 0; i < 1 + GGML_MAX_SRC; i++) {
-        const ggml_tensor * t = i == 0 ? op : op->src[i - 1];
-        if (t == nullptr) {
-            key[i].type = UINT32_MAX;
-            continue;
-        }
-        key[i].type = t->type;
-        if (i == 0) {
-            key[i].op = t->op;
-            memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params));
-        }
-        for (int j = 0; j < GGML_MAX_DIMS; j++) {
-            key[i].ne[j] = t->ne[j];
-            key[i].nb[j] = t->nb[j];
-        }
-    }
-    return fnv_hash((const uint8_t *)key, sizeof(key));
-}
-
 // ask the server about the whole graph in a single round trip, unless every node already has an answer
 static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev, const struct ggml_cgraph * graph) {
     ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context;
@@ -2934,7 +2911,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev,
     {
         std::lock_guard<std::mutex> lock(ctx->supports_op_mutex);
         for (int i = 0; i < graph->n_nodes; i++) {
-            keys[i] = supports_op_key(graph->nodes[i]);
+            keys[i] = op_layout_key(graph->nodes[i]);
             all_cached = all_cached && ctx->supports_op_cache.count(keys[i]) > 0;
         }
     }
@@ -2955,7 +2932,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev,
 // cached answer if the layout was seen, else ask the server about this op
 static bool ggml_backend_rpc_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
     ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context;
-    const uint64_t key = supports_op_key(op);
+    const uint64_t key = op_layout_key(op);
     {
         std::lock_guard<std::mutex> lock(ctx->supports_op_mutex);
         auto it = ctx->supports_op_cache.find(key);
diff --git a/tests/test-rpc-multi-server.cpp b/tests/test-rpc-multi-server.cpp
index f253b6e14..ece602ec1 100644
--- a/tests/test-rpc-multi-server.cpp
+++ b/tests/test-rpc-multi-server.cpp
@@ -17,7 +17,7 @@ int main(int argc, char ** argv) {
     GGML_ASSERT(backend_b != nullptr);

     ggml_init_params params = {
-        /* .mem_size   = */ 3*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false),
+        /* .mem_size   = */ 10*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false),
         /* .mem_buffer = */ nullptr,
         /* .no_alloc   = */ true,
     };
@@ -62,6 +62,35 @@ int main(int argc, char ** argv) {
     GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, packed)  >= ggml_nbytes(packed));
     GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, strided) >= ggml_nbytes(strided));

+    // Two TOP_K tensors with the same output layout but different srcs must not share a cached alloc size.
+    // ref: https://github.com/ggml-org/llama.cpp/issues/30794
+    ggml_tensor * src_small = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 8);
+    ggml_tensor * top_k_small = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
+    top_k_small->op = GGML_OP_TOP_K;
+    top_k_small->src[0] = src_small;
+
+    ggml_tensor * src_large = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4096*8);
+    ggml_tensor * top_k_large = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
+    top_k_large->op = GGML_OP_TOP_K;
+    top_k_large->src[0] = src_large;
+
+    // uncached baseline for the large src: a different op_params value gives a separate cache entry
+    ggml_tensor * top_k_large_probe = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4);
+    top_k_large_probe->op = GGML_OP_TOP_K;
+    top_k_large_probe->src[0] = src_large;
+    top_k_large_probe->op_params[0] = 1;
+    size_t size_large_uncached = ggml_backend_buft_get_alloc_size(buft, top_k_large_probe);
+
+    // ask for the small src first, so a cache keyed without srcs holds the smaller size
+    size_t size_small = ggml_backend_buft_get_alloc_size(buft, top_k_small);
+    size_t size_large = ggml_backend_buft_get_alloc_size(buft, top_k_large);
+    GGML_ASSERT(size_large >= size_large_uncached);
+    GGML_ASSERT(size_small <= size_large);
+
+    // the small src must not be affected by the larger one
+    size_t size_small_again = ggml_backend_buft_get_alloc_size(buft, top_k_small);
+    GGML_ASSERT(size_small_again >= size_small);
+
     ggml_free(ctx);
     ggml_backend_free(backend_b);
     ggml_backend_free(backend_a);
diff --git a/tests/test-rpc-multi-server.sh b/tests/test-rpc-multi-server.sh
index a8c723162..71e2eec92 100755
--- a/tests/test-rpc-multi-server.sh
+++ b/tests/test-rpc-multi-server.sh
@@ -17,7 +17,7 @@ trap cleanup EXIT

 wait_for_port() {
     local port=$1
-    for _ in {1..600}; do
+    for _ in {1..2400}; do
         if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
             exec 3>&-
             exec 3<&-
@@ -28,7 +28,8 @@ wait_for_port() {
     return 1
 }

-"$server" --device CPU --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 &
+# the TOP_K alloc size check needs a device whose alloc size depends on src0, e.g. Metal
+"$server" --device "${TEST_RPC_DEVICE:-CPU}" --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 &
 pid_a=$!
 "$server" --device CPU --host 127.0.0.1 --port "$port_b" >"$test_dir/server-b.log" 2>&1 &
 pid_b=$!
@@ -37,7 +38,7 @@ wait_for_port "$port_b"

 "$client" "$endpoint_a" "$endpoint_b"

-if grep -q "invalid data ptr" "$test_dir/server-b.log"; then
+if grep -q "has a data pointer but no buffer" "$test_dir/server-b.log"; then
     cat "$test_dir/server-b.log"
     exit 1
 fi