Commit ea7229481 for llama.cpp
commit ea722948146befb23c9529c1ec7f59fb2f34911f
Author: Aman Gupta <amangupta052@gmail.com>
Date: Wed Nov 25 16:34:49 2026 +0800
ggml: allow reserving scratch memory in graph_optimize (#31898)
* ggml: allow reserving scratch memory in graph_optimize
Add add_scratch to ggml_backend_graph_optimize_params. A backend can
reserve compute buffer memory that is allocated before a node `first`
and kept until a node `last` has been computed, e.g. for data that
several nodes share. The scheduler adds the scratch tensor to the graph
copy right before `first` and frees it with an alloc dep at `last`.
* ggml: clarify the lifetime of add_scratch memory
* ggml: build the pending scratch set from the scratch map
diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h
index aaec8ac41..482d6b33c 100644
--- a/ggml/src/ggml-backend-impl.h
+++ b/ggml/src/ggml-backend-impl.h
@@ -125,6 +125,15 @@ extern "C" {
// keep `tensor` allocated at least until `until` (a node of the same graph) has been computed
// can be called multiple times for the same tensor: the longest lifetime applies
void (*add_alloc_dep)(void * user_data, struct ggml_tensor * tensor, struct ggml_tensor * until);
+
+ // reserve `nbytes` of memory in the compute buffer of the backend, e.g. for data that several nodes share
+ // the memory is reserved from before `first` is computed until `last` has been computed: outside of that range the
+ // allocator can give it to other tensors, so its contents do not carry over between evaluations of the graph
+ // `first` and `last` are nodes of the same graph, and `last` must not come before `first` in the optimized graph
+ // returns a 1-d GGML_TYPE_I8 tensor that is not a node of the graph, its data is set when the graph is allocated
+ // the backend can keep references to the tensor itself until the scheduler splits the next graph
+ struct ggml_tensor * (*add_scratch)(void * user_data, size_t nbytes, struct ggml_tensor * first, struct ggml_tensor * last);
+
void * user_data;
};
diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp
index 8e175649b..97f267d46 100644
--- a/ggml/src/ggml-backend.cpp
+++ b/ggml/src/ggml-backend.cpp
@@ -21,6 +21,7 @@
#include <string.h>
#include <algorithm>
#include <unordered_map>
+#include <unordered_set>
#include <vector>
#ifdef __APPLE__
@@ -1890,20 +1891,38 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
sched->prev_leaf_backend_ids = tmp;
}
- // optimize the split graphs and collect the allocation dependencies added by the backends
+ // optimize the split graphs and collect the allocation dependencies and scratch tensors added by the backends
// this needs to happen before we make graph_copy, so they are in sync
// TODO: this may create many small allocations in the scheduler, restructure to use a flat array
- std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
+ struct optimize_state {
+ ggml_context * ctx;
+ // node -> tensors kept allocated until the node has been computed
+ std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
+ // node -> scratch tensors allocated before the node is computed
+ std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> scratch;
+ } opt_state;
+ opt_state.ctx = sched->ctx;
struct ggml_backend_graph_optimize_params opt_params = {
/* .add_alloc_dep = */ [](void * user_data, ggml_tensor * tensor, ggml_tensor * until) {
- auto & deps = *(std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> *) user_data;
- std::vector<ggml_tensor *> & keep = deps[until];
+ auto & state = *(optimize_state *) user_data;
+ std::vector<ggml_tensor *> & keep = state.alloc_deps[until];
if (std::find(keep.begin(), keep.end(), tensor) == keep.end()) {
keep.push_back(tensor);
}
},
- /* .user_data = */ &alloc_deps,
+ /* .add_scratch = */ [](void * user_data, size_t nbytes, ggml_tensor * first, ggml_tensor * last) {
+ auto & state = *(optimize_state *) user_data;
+ GGML_ASSERT(nbytes > 0);
+ ggml_tensor * t = ggml_new_tensor_1d(state.ctx, GGML_TYPE_I8, (int64_t) nbytes);
+ std::vector<ggml_tensor *> & first_scratch = state.scratch[first];
+ ggml_format_name(t, "scratch-%zu (%s)", first_scratch.size(), first->name);
+ first_scratch.push_back(t);
+ // the scratch tensor has no other users, the dep at `last` is what frees it
+ state.alloc_deps[last].push_back(t);
+ return t;
+ },
+ /* .user_data = */ &opt_state,
};
for (int i = 0; i < sched->n_splits; i++) {
@@ -1913,17 +1932,27 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
ggml_backend_graph_optimize(sched->backends[split->backend_id], &split->graph, &opt_params);
}
+ const auto & alloc_deps = opt_state.alloc_deps;
+
// each dep is added to graph_copy as a GGML_OP_NONE node with the kept tensors as srcs
int n_dep_nodes = 0;
for (const auto & it : alloc_deps) {
n_dep_nodes += (it.second.size() + GGML_MAX_SRC - 1) / GGML_MAX_SRC;
}
+ // each scratch tensor is added to graph_copy as a GGML_OP_NONE node right before its first user
+ // scratch tensors not yet added to graph_copy
+ std::unordered_set<ggml_tensor *> scratch_pending;
+ for (const auto & it : opt_state.scratch) {
+ scratch_pending.insert(it.second.begin(), it.second.end());
+ }
+ const int n_scratch_nodes = (int) scratch_pending.size();
+
int total_inputs = sched->n_graph_inputs;
for (int i = 0; i < sched->n_splits; i++) {
total_inputs += sched->splits[i].n_inputs;
}
- int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes;
+ int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes + n_scratch_nodes;
// remember the actual graph_size for performing reallocation checks later
sched->prev_graph_size = sched->graph_size;
@@ -1966,6 +1995,19 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
}
for (int j = split->i_start; j < split->i_end; j++) {
+ // add the scratch tensors first so that they are allocated before this node is computed
+ if (!scratch_pending.empty()) {
+ auto it = opt_state.scratch.find(graph->nodes[j]);
+ if (it != opt_state.scratch.end()) {
+ for (ggml_tensor * t : it->second) {
+ assert(graph_copy->size > graph_copy->n_nodes);
+ sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
+ graph_copy->nodes[graph_copy->n_nodes++] = t;
+ scratch_pending.erase(t);
+ }
+ }
+ }
+
assert(graph_copy->size > graph_copy->n_nodes);
sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]);
graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
@@ -1981,6 +2023,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
for (size_t k = 0; k < keep.size(); k += GGML_MAX_SRC) {
struct ggml_tensor * dep = ggml_view_tensor(sched->ctx, keep[k]);
for (size_t s = 0; s < GGML_MAX_SRC && k + s < keep.size(); s++) {
+ // a scratch tensor freed before it was allocated: its `last` comes before its `first`
+ GGML_ASSERT(scratch_pending.count(keep[k + s]) == 0 && "add_scratch: last is before first");
dep->src[s] = keep[k + s];
}
assert(graph_copy->size > graph_copy->n_nodes);
@@ -1994,6 +2038,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
// a mismatch means a backend added a dep with an `until` tensor that is not a node of the optimized graph
GGML_ASSERT(n_dep_nodes_added == n_dep_nodes);
+ // a scratch tensor left over means a backend passed a `first` tensor that is not a node of the optimized graph
+ GGML_ASSERT(scratch_pending.empty() && "add_scratch: first is not a node of the graph");
if (sched->n_copies > 1) {
// add input copies as leafs so that they are allocated first
diff --git a/tests/test-alloc.cpp b/tests/test-alloc.cpp
index 45d9a3eda..3f5de1378 100644
--- a/tests/test-alloc.cpp
+++ b/tests/test-alloc.cpp
@@ -677,6 +677,71 @@ static void test_graph_optimize_alloc_dep() {
GGML_ASSERT(!graph_reuses_allocation(true));
}
+// scratch tensors requested by test_backend_graph_optimize_scratch
+static ggml_tensor * test_scratch[2];
+
+static void test_backend_graph_optimize_scratch(ggml_backend_t /*backend*/, ggml_cgraph * graph, ggml_backend_graph_optimize_params * params) {
+ // nodes: x1 = cont(x0), x2 = scale(x1), x3 = scale(x2), x4 = scale(x3)
+ GGML_ASSERT(graph->n_nodes == 4);
+ // live from before x1 is computed until x2 has been computed
+ test_scratch[0] = params->add_scratch(params->user_data, 32, graph->nodes[0], graph->nodes[1]);
+ // live only while x3 is computed
+ test_scratch[1] = params->add_scratch(params->user_data, 64, graph->nodes[2], graph->nodes[2]);
+}
+
+static bool tensors_overlap(const ggml_tensor * a, const ggml_tensor * b) {
+ const uint8_t * a0 = (const uint8_t *) a->data;
+ const uint8_t * b0 = (const uint8_t *) b->data;
+ return a->buffer == b->buffer && a0 < b0 + ggml_nbytes(b) && b0 < a0 + ggml_nbytes(a);
+}
+
+static void test_graph_optimize_scratch() {
+ auto [ctx, graph, ctx_ptr] = make_context();
+
+ // x1 is not computed in place, so x0 is freed once x1 has been computed:
+ // a scratch tensor allocated too late would take the memory of x0
+ ggml_tensor * x[5];
+ x[0] = make_input_with_size(ctx, 32);
+ x[1] = ggml_cont(ctx, x[0]);
+ for (int i = 2; i < 5; i++) {
+ x[i] = ggml_scale(ctx, x[i - 1], 2.0f);
+ }
+ assign_names(ctx);
+
+ ggml_set_output(x[4]);
+ ggml_build_forward_expand(graph, x[4]);
+
+ dummy_backend backend = dummy_backend_init(SIZE_MAX);
+ backend.context->backend.iface.graph_optimize = test_backend_graph_optimize_scratch;
+
+ ggml_backend_t backend_ptr = &backend.context->backend;
+ ggml_backend_buffer_type_t buft = &backend.buffer_type;
+ ggml_backend_sched_ptr sched(ggml_backend_sched_new(&backend_ptr, &buft, 1, 8, false, true));
+ GGML_ASSERT(ggml_backend_sched_reserve(sched.get(), graph));
+ GGML_ASSERT(ggml_backend_sched_alloc_graph(sched.get(), graph));
+ check_all_allocated(graph);
+
+ ggml_tensor * s0 = test_scratch[0];
+ ggml_tensor * s1 = test_scratch[1];
+ GGML_ASSERT(s0 && s1 && s0 != s1);
+ GGML_ASSERT(s0->type == GGML_TYPE_I8 && ggml_nbytes(s0) == 32);
+ GGML_ASSERT(s1->type == GGML_TYPE_I8 && ggml_nbytes(s1) == 64);
+ GGML_ASSERT(s0->data != nullptr && s0->buffer != nullptr);
+ GGML_ASSERT(s1->data != nullptr && s1->buffer != nullptr);
+
+ // tensors that are live at some point between `first` and `last` must not share memory with the scratch
+ for (int i : { 0, 1, 2 }) {
+ GGML_ASSERT(!tensors_overlap(s0, x[i]));
+ }
+ for (int i : { 2, 3 }) {
+ GGML_ASSERT(!tensors_overlap(s1, x[i]));
+ }
+
+ // s0 is freed once x2 has been computed: x2-x4 are computed in place over x1,
+ // and s1 only fits into the memory that x0 and s0 leave free
+ GGML_ASSERT(tensors_overlap(s0, s1));
+}
+
// Check that the size reported by ggml_backend_alloc_ctx_tensors_from_buft_size
// matches the actual size of the buffer allocated for the ctx tensors
static ggml_backend_buffer_ptr check_size_matches(ggml_backend_buffer_type_t buft, ggml_context * ctx) {
@@ -1121,6 +1186,7 @@ int main() {
run("test_buffer_size_zero", test_buffer_size_zero);
run("test_reallocation", test_reallocation);
run("test_graph_optimize_alloc_dep", test_graph_optimize_alloc_dep);
+ run("test_graph_optimize_scratch", test_graph_optimize_scratch);
run("test_buft_alloc_buffer_n_single_buffer", test_buft_alloc_buffer_n_single_buffer);
run("test_buft_alloc_buffer_n_multi_buffer", test_buft_alloc_buffer_n_multi_buffer);
run("test_buft_alloc_buffer_n_zero_size", test_buft_alloc_buffer_n_zero_size);