Skip to content

Save host memory for scheduler context sizing - #31274

Open
joelagnel wants to merge 3 commits into
ggml-org:masterfrom
joelagnel:study/graph-memory-followups-standalone
Open

joelagnel wants to merge 3 commits into
ggml-org:masterfrom
joelagnel:study/graph-memory-followups-standalone

Conversation

@joelagnel

@joelagnel joelagnel commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Save host memory on scheduler context sizing.

Make the scheduler context buffer sized at split time from the graph being split (max(n_nodes, n_leafs) times the worst-case object count for n_copies). When a later graph needs more than it holds, a larger block is allocated and the old one is kept until the scheduler is freed, so pointers into it stay valid. It never shrinks. Before it was allocated on scheduler creation, from the largest graph the scheduler was created for. Also separate the dependency ctx from sched ctx as dependency count is known only after backend's graph optimization runs, and add error checking for if we could outgrow the backend id arrays.

Testing

On llama.cpp master vs PR:

  • Model and request: Qwen3.8-27B Q4_K_M, context 8,192, one slot, three fixed 512-token prompts, 256 greedy tokens each
  • Windows RTX 5090 (8 paired blocks per workload)
+--------------+------------+-----------------+--------------+
| Workload     | master (M) | master + PR (P) | P - M        |
+--------------+------------+-----------------+--------------+
| plain decode |     18,092 |          17,591 | -501 (-2.8%) |
| DFlash2-7 p0 |     21,452 |          20,972 | -480 (-2.2%) |
| DFlash2-7 .5 |     21,467 |          20,983 | -485 (-2.3%) |
| MTP-7 p0     |     20,286 |          19,296 | -990 (-4.9%) |
| MTP-7 .5     |     20,278 |          19,284 | -994 (-4.9%) |
+--------------+------------+-----------------+--------------+
p0 / .5 = --spec-draft-p-min 0 / 0.5. PR = #31274. 8 paired blocks per row.

Requirements

@joelagnel

Copy link
Copy Markdown
Contributor Author

CC @am17an

@github-actions github-actions Bot added the ggml changes relating to the ggml tensor library for machine learning label Oct 27, 2026
@am17an am17an self-assigned this Oct 28, 2026
@aendk

aendk commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Am I right in assuming that a substantial memory saving of this PR comes from switching out the vector allocations with calloc, which is the same from a virtual page perspective, but not from a resident set size (~= physical memory), and that the latter (calloc) is lazy loaded, so that we benefit from the unused long-tail ?

If so where did you test (windows/linux)? Can we expect that the other system exhibits the same behavior?

@joelagnel

joelagnel commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @aendk

Am I right in assuming that a substantial memory saving of this PR comes from switching out the vector allocations with calloc, which is the same from a virtual page perspective, but not from a resident set size (~= physical memory), and that the latter (calloc) is lazy loaded, so that we benefit from the unused long-tail ?

That is broadly the calloc mechanism I observed. One correction: the large savings in the PR body were largely due to scheduler-sizing commit; if we isolate to just calloc, the savings are smaller:

Host memory metric DFlash2-7 savings MTP-7 savings
GB300/Linux, settled RssAnon 50.2 MiB 168.6 MiB
RTX 5090/Windows, peak working set 81.9 MiB 213.0 MiB

If so where did you test (windows/linux)? Can we expect that the other system exhibits the same behavior?

I tested it separately on GB300/Linux and RTX 5090/Windows. On both systems, I see lower resident-memory measurements. I think the change is worthwhile given the measured resident-memory savings, though I would not assume the same savings on every system. I think it is allocator/OS dependent.

Comment thread src/llama-graph.cpp Resolved
@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from 8337f4f to d3d8017 Compare November 4, 2026 00:05
@joelagnel
joelagnel requested a review from ggerganov as a code owner November 4, 2026 00:05
@github-actions github-actions Bot added the testing Everything test related label Nov 4, 2026
@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from d3d8017 to 796958b Compare November 4, 2026 00:12

@aendk aendk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM as far as I can see.

Since you now size the context buffer a bit tighter for each graph, can you come up with a definitive worst-case graph size, and if so, is that the opportunity for an additional test?

If not, i'd be curious if this PR passes the scheduler test suite of #27258

@ggerganov ggerganov self-assigned this Nov 5, 2026
@joelagnel

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I worked through the worst case on paper and in a new test, and it checks out.

With Maximum of 10 sources per node (GGML_MAX_SRC) and M = max(n_nodes, n_leafs),

The most it can need is (11 * n_copies + 9) * M objects, which is 20 * M in normal mode (n_copies=1) and 53 * M in parallel mode (n_copies=4).

The buffer holds about 54.8 * M objects (368 bytes per object with the header).

So even in the worst case and in parallel mode, there is room to spare in the scheduler arena. I turned this into a test case as well and updated the PR.

Also, yes, this PR passes the scheduler test suite of #27258.

@am17an

am17an commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

UUIC there are two changes in this PR:

  1. Graph metadata buffer sizing

  2. Scheduler context buffer

If so, can you can split them into two PRs?

@joelagnel

Copy link
Copy Markdown
Contributor Author

@am17an sure, will split, thanks

@joelagnel

Copy link
Copy Markdown
Contributor Author

@am17an @aendk I split the metadata changes out into different PR as suggested by Aman: #32043 , please take a look at both PRs, thanks!

@joelagnel joelagnel changed the title Save host memory for scheduler context sizing and graph metadata allocation Save host memory for scheduler context sizing Nov 10, 2026
@am17an

am17an commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

can you please make the PR description more descriptive?

@joelagnel

Copy link
Copy Markdown
Contributor Author

@am17an done

@Adon1s

Adon1s commented Nov 13, 2026

Copy link
Copy Markdown

I run a port of llama.cpp on a jailbroken base PS5, where every allocated byte is backed at once with no lazy paging. My port held 874 MiB of CPU heap and about 717 MiB of it was the two schedulers, so I wanted to test this PR.

I ran PR head a85ed2c versus merge base 7592b61 with Qwen3.8-27B-UD-Q2_K_XL and its projector, on Debian in Docker, as well as native Windows 11, with a RTX 4090 and a RTX 3080.

On Linux the two ggml schedulers were reduced from 716.7 MiB to 123.1 MiB, so 593.6 MiB less. The Windows commit charge dropped by the same amount, and the merge base and PR matched on generated text and top 3 log probabilities on every setup I tried.

I did hit one problem with the new check this PR adds in ggml_backend_sched_split_graph, the one that aborts with "the graph copy needs up to N backend id entries". It aborts a 40 node test graph with 4 copies that the merge base and master at 3ba1ce0 both allocate without error. However, this is an extreme graph, so I highly doubt any real model will run into this issue. Regardless, the test is test_sched_parallel_many_inputs on my fork: Adon1s@72b93fe

Of the 123.1 MiB that stays reserved, 33.0 MiB is the four id arrays, which this PR leaves at a fixed size. I can send a small separate PR for the id arrays once this one merges. Also, #30406 reports this same reservation as Windows commit charge, which is what my 594.4 and 596.6 MiB figures measure.

Details

Memory

I measured the memory the two ggml schedulers reserve on the merge base and with the PR on Linux, and with llama-server loaded and idle on Windows. The Windows commit charge dropped by 594.4 MiB CPU only, and 596.6 MiB on the RTX 4090, so the reservation counts against the commit limit there and the PR removes most of it.

Merge base With the PR Difference
Model scheduler, Linux, allocated 551.0 MiB 99.4 MiB -451.6 MiB
Projector scheduler, Linux, allocated 165.7 MiB 23.7 MiB -142.0 MiB
Both schedulers, Linux 716.7 MiB 123.1 MiB -593.6 MiB
Commit charge, Windows, CPU only 11,522.8 MiB 10,928.4 MiB -594.4 MiB
Commit charge, Windows, RTX 4090 12,168.1 MiB 11,571.5 MiB -596.6 MiB

PS5

On the PS5 I carried the PR's change to ggml-backend.cpp back onto my port's llama.cpp (970b51c) and ran the same model and projector on Vulkan + CPU at 8k context. The CPU heap in use when ready was 260 MiB with the PR's change against 139 MiB with my own patch, and the PC predicted 121.2 MiB for that gap. I didn't run an unpatched build at this setting, but that works out to the PR giving back about 590 of about 717 MiB on the console.

Outputs

The merge base and PR matched on generated text and top 3 log probabilities rounded to 6 decimals on CPU, the 4090, and the 4090 + 3080 with 4 copies.

The guard

The guard checks an upper estimate instead of counting what each array will hold. With 4 copies, the estimate budgets 8 entries per split input. In the actual graph copy, that input adds 2 entries to the node array and 4 to the separate leaf array.

In the 40 node test with 4 copies, the estimate was over the capacity of each array, which caused the PR to abort. The graph actually needed far fewer node and leaf slots, so both fit.

For the 40-node graph Entries
The guard's estimate 2,992
Capacity of each id array 2,989
Node entries actually written 760
Leaf entries actually written 1,485

The merge base and master at 3ba1ce0 both allocate the same graph without error and come up clean under ASan and UBSan.

The id arrays

In my port the id arrays grow with the graph copy and take 0.5 MiB, and arrays that grow don't need the guard.

For transparency purposes, it was Claude that found the reservation in my port and wrote its patch. Claude Code (Claude Fable 5.2 and Claude Opus 5.5) wrote the guard test and scripts, built the PS5 test build, and ran the PC builds and measurements, and Codex running GPT 6.0 Astra independently rechecked the CPU results. I directed the work, installed and started the PS5 build on the console, reviewed the results, and wrote this comment myself after looking over all of the data and results.

Comment thread ggml/src/ggml-backend.cpp Outdated
ggml_free(sched->ctx);

const size_t context_graph_size = std::max(graph->n_nodes, graph->n_leafs);
const size_t context_buffer_size = context_graph_size*GGML_SCHED_MAX_SPLIT_INPUTS*2*sizeof(struct ggml_tensor);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this size enough? because later down the graph size is calculated as

int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes;

@joelagnel joelagnel Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hi @am17an, Yes it's enough, because the 2 sizes are for different things. The dependency nodes live in their own context after the patch, not in the sched->ctx arena. The other size which has the dependency nodes is sizing the node/leaf lists, not the arena. Btw I will rewrite/refactor to make calculations more clear, thanks!

I will reply separately to the other comment from @Adon1s after studying the test case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@am17an I updated the PR making the existing code more readable, splitting into functions with comments and using macros to define redundant expressions. This code is very confusing and full of formulas, so I hope the clean up is Ok. Eventually, I think I want to rewrite all this code using C++ namespaces, but I keep this PR restricted to only small cleanups and adjusting the allocation :)

@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from a85ed2c to d601b78 Compare November 13, 2026 20:55
@joelagnel

joelagnel commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

I run a port of llama.cpp on a jailbroken base PS5, where every allocated byte is backed at once with no lazy paging. My port held 874 MiB of CPU heap and about 717 MiB of it was the two schedulers, so I wanted to test this PR.

I ran PR head a85ed2c versus merge base 7592b61 with Qwen3.8-27B-UD-Q2_K_XL and its projector, on Debian in Docker, as well as native Windows 11, with a RTX 4090 and a RTX 3080.

On Linux the two ggml schedulers were reduced from 716.7 MiB to 123.1 MiB, so 593.6 MiB less. The Windows commit charge dropped by the same amount, and the merge base and PR matched on generated text and top 3 log probabilities on every setup I tried.

I did hit one problem with the new check this PR adds in ggml_backend_sched_split_graph, the one that aborts with "the graph copy needs up to N backend id entries". It aborts a 40 node test graph with 4 copies that the merge base and master at 3ba1ce0 both allocate without error. However, this is an extreme graph, so I highly doubt any real model will run into this issue. Regardless, the test is test_sched_parallel_many_inputs on my fork: Adon1s@72b93fe

Of the 123.1 MiB that stays reserved, 33.0 MiB is the four id arrays, which this PR leaves at a fixed size. I can send a small separate PR for the id arrays once this one merges. Also, #30406 reports this same reservation as Windows commit charge, which is what my 594.4 and 596.6 MiB figures measure.

Details
Memory

I measured the memory the two ggml schedulers reserve on the merge base and with the PR on Linux, and with llama-server loaded and idle on Windows. The Windows commit charge dropped by 594.4 MiB CPU only, and 596.6 MiB on the RTX 4090, so the reservation counts against the commit limit there and the PR removes most of it.

Merge base With the PR Difference
Model scheduler, Linux, allocated 551.0 MiB 99.4 MiB -451.6 MiB
Projector scheduler, Linux, allocated 165.7 MiB 23.7 MiB -142.0 MiB
Both schedulers, Linux 716.7 MiB 123.1 MiB -593.6 MiB
Commit charge, Windows, CPU only 11,522.8 MiB 10,928.4 MiB -594.4 MiB
Commit charge, Windows, RTX 4090 12,168.1 MiB 11,571.5 MiB -596.6 MiB
PS5

On the PS5 I carried the PR's change to ggml-backend.cpp back onto my port's llama.cpp (970b51c) and ran the same model and projector on Vulkan + CPU at 8k context. The CPU heap in use when ready was 260 MiB with the PR's change against 139 MiB with my own patch, and the PC predicted 121.2 MiB for that gap. I didn't run an unpatched build at this setting, but that works out to the PR giving back about 590 of about 717 MiB on the console.

Outputs

The merge base and PR matched on generated text and top 3 log probabilities rounded to 6 decimals on CPU, the 4090, and the 4090 + 3080 with 4 copies.

The guard

The guard checks an upper estimate instead of counting what each array will hold. With 4 copies, the estimate budgets 8 entries per split input. In the actual graph copy, that input adds 2 entries to the node array and 4 to the separate leaf array.

In the 40 node test with 4 copies, the estimate was over the capacity of each array, which caused the PR to abort. The graph actually needed far fewer node and leaf slots, so both fit.

For the 40-node graph Entries
The guard's estimate 2,992
Capacity of each id array 2,989
Node entries actually written 760
Leaf entries actually written 1,485
The merge base and master at 3ba1ce0 both allocate the same graph without error and come up clean under ASan and UBSan.

The id arrays

In my port the id arrays grow with the graph copy and take 0.5 MiB, and arrays that grow don't need the guard.

For transparency purposes, it was Claude that found the reservation in my port and wrote its patch. Claude Code (Claude Fable 5.2 and Claude Opus 5.5) wrote the guard test and scripts, built the PS5 test build, and ran the PC builds and measurements, and Codex running GPT 6.0 Astra independently rechecked the CPU results. I directed the work, installed and started the PS5 build on the console, reviewed the results, and wrote this comment myself after looking over all of the data and results.

Thank you @Adon1s for reporting the issue. I have fixed it in the latest version. Can you test again on your side and confirm the latest PR passes your tests along with seeing the same memory improvements on your setup?

@Adon1s

Adon1s commented Nov 15, 2026 •

Copy link
Copy Markdown

@joelagnel All of the tests pass in your latest PR, and the memory savings are just as good as before. I appreciate you reading through my longwinded comment about an edge case. I am just starting to get my feet wet contributing to llama.cpp. Hope your PR gets merged soon!

Comment thread ggml/src/ggml-backend-impl.h Resolved
@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from d601b78 to 66bcf63 Compare November 16, 2026 19:33
@am17an am17an removed their assignment Nov 17, 2026

@joelagnel joelagnel left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@aendk should be good for another look now.

@aendk

aendk commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

I can provoke test failures with the following:

diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 36e48a0f2..da5d1fcf8 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -433,6 +433,7 @@ if (NOT LLAMA_USE_SYSTEM_GGML)

     # Needs non-public ggml{,-backend}-impl.h
     llama_build_and_test(test-alloc.cpp  LABEL "behavior backend"  LINK ggml)
+    target_compile_definitions(test-alloc PRIVATE GGML_SCHED_MAX_COPIES=${GGML_SCHED_MAX_COPIES})
 endif()

C=8 is a valid config and might break with the current setting.
Additionally, the cmake patch was required as setting -DGGML_SCHED_MAX_COPIES apparently never reaches tests/ . So my suggestion is to take these sched_max_copies into account when determining sizing, and to fix the piping to the tests.

@aendk

aendk commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

I (=my AI) found another bug:
The PR now resizes the scheduler's context_buffer with realloc whenever a bigger graph comes along. Pointers into that buffer still survive from the previous split: the user graph's node->src[j], which the split rewrites, and the scheduler's table of input copies (hv_tensor_copies), which only reset() clears. So re-splitting an earlier graph after a bigger one, or calling reserve() after alloc() without a reset, reads freed memory. ASan confirms a heap use-after-free in both cases on the PR, while master's fixed-size buffer never moves and passes.

Since this is taking place in the ggml scheduler, we should tidy up this potentially brittle code, even though llama.cpp never really triggers it. Other projects building on top of ggml could run into this.

I'll share the repro and possible test internally to keep this thread minimal @joelagnel

@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from 66bcf63 to 671887c Compare November 18, 2026 22:17

@joelagnel joelagnel left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@aendk I updated the PR. The memory savings is even more now, thanks!

@aendk

aendk commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

@joelagnel I partly reran the CI and roughly the same amount of tests fail.
I suggest rebasing to rule out bugs from your specific master branch root.

@joelagnel

joelagnel commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Let's look into moving this forward @ggerganov ? @aendk mentioned to me he's happy with it now too. there's no other open review comment.

The scheduler context buffer is sized in ggml_backend_sched_new() as
  max_splits * GGML_SCHED_MAX_SPLIT_INPUTS * 2 * sizeof(ggml_tensor)
    + ggml_graph_overhead_custom(graph_size, false)
but nothing stores a ggml_cgraph in sched->ctx. The only objects allocated
from it are ggml_tensor structs: the per-backend input copies
(ggml_dup_tensor_layout) and the input dependency views (ggml_view_tensor).
sched->graph is a plain struct member whose nodes[] and leafs[] arrays are
realloc'd separately, and ggml_graph_view() returns by value without
allocating. The graph overhead term therefore reserved space that is never
used, and it scaled with the scheduler's maximum graph_size.

Remove it. The buffer is sized only for the tensors it can hold.
Allocate scheduler scratch space for the graph being split. Keep optimizer allocation-dependency views in a separate context sized for the dependencies actually created.
At most GGML_MAX_SRC * (C + 1) + (C - 1) objects per unit of graph size,
C = 1 or GGML_SCHED_MAX_COPIES, against GGML_SCHED_MAX_SPLIT_INPUTS * 2
slots of sizeof(ggml_tensor). The two scheduler macros move to
ggml-backend-impl.h so that the test can use them.
@joelagnel
joelagnel force-pushed the study/graph-memory-followups-standalone branch from b9f4edd to 0db811a Compare November 25, 2026 21:50
@joelagnel

Copy link
Copy Markdown
Contributor Author

Just rebased on master, no other change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ggml changes relating to the ggml tensor library for machine learning testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants