Skip to content

perf(fast): capture the CUDA graphs largest first (compact rows on 16 GB and 24 GB cards) - #37

Merged
rkinas merged 7 commits into
rkinas:mainfrom
Butterski:perf/graph-capture-order
Oct 22, 2026
Merged

rkinas merged 7 commits into
rkinas:mainfrom
Butterski:perf/graph-capture-order

Conversation

@Butterski

@Butterski Butterski commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #35 (shared graph outputs): until #35 merges, this branch also carries its commits. The change here is
the last two commits (f9733ef, 8b9df34); the measurements compare #35's engine with this branch.

Problem

GraphBackend.warm() captures every graph right after its warm-up calls, in the grid's order: smallest first
(compact graphs of 16, 32, ... 12,288 tokens, then plain graphs by length, then pass 2). All graphs share one memory
pool. What a capture frees at its end, a later capture can reuse only in blocks no larger than the freed ones, so every
larger graph allocates new blocks and the pool grows far beyond the largest graph's working set. On an RTX 4090 after
start-up (#35's engine, torch.cuda.memory_snapshot):

graph pool reserved of it allocated
basal-2.0-mini, --batches compact 9.04 GiB 0.81 GiB
basal-2.0-mini, default 1.88 GiB 0.01 GiB
basal-2.0-4.5B, default 2.31 GiB 0.01 GiB

So compact rows (#29's --batches compact on GPUs without FlashAttention 3) cost about 8 GB more than default rows:
basal-2.0-4.5B with compact rows runs out of memory in warm-up on a 24 GB RTX 4090, basal-2.0-mini with compact rows
on a 16 GB RTX 4060 Ti (the "about 6 GB more" of #33 on an RTX 3090).

Change

basal/engine.py, Llama graphs only (Gemma 4's _warm_long_sfx measures the pool as each graph is captured):

  • warm() keeps the grid's order for every graph's warm-up calls (torch.compile compiles there, so the compiled
    kernels are those of today) and defers the captures: _capture_deferred then captures them all, the most tokens
    first (_graph_tokens: rows x length, pass 2 then by query-key pairs). Each smaller graph reuses blocks a larger one
    freed. A shape that two families ask for (--prefix-cache: plain pass 2 and the prefix family) is warmed up and
    captured once.
  • _capture is split into _warm_up and _record; outside warm() (graphs captured on demand) nothing changes.
  • The compact graphs write their hidden states into one shared buffer (_compact_out), as perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35 does for the plain and
    pass-2 graphs (104 graphs, 0.8 GiB on basal-2.0-mini). With --readout-layer on their output is [32, D] and stays
    as it is.

Measurements

RTX 4090 24 GB, torch 2.13.0+cu130; #35's engine vs this branch, GraphBackend built directly, memory from
torch.cuda.mem_get_info after warm-up, probabilities of the identity items (basal.identity.build: 200 single
questions, 40 five-question requests, 20 long):

model, batching #35 this branch probabilities
basal-2.0-mini, default 9,949 MiB (pool 1.88 GiB) 9,016 MiB (pool 0.97 GiB) 420 / 420 bit-identical
basal-2.0-mini, --batches compact 17,585 MiB (pool 9.04 GiB) 9,356 MiB (pool 0.97 GiB) 420 / 420 bit-identical
mini, compact + template prefixes (the server's default with compact) 17,592 MiB 9,387 MiB 420 / 420 bit-identical
mini, compact + --readout-layer on 17,563 MiB 9,265 MiB 420 / 420 bit-identical
basal-2.0-4.5B, default 20,456 MiB (pool 2.31 GiB) 19,309 MiB (pool 1.19 GiB) 420 / 420 bit-identical
basal-2.0-4.5B, --batches compact out of memory in warm-up 19,814 MiB 420 / 420 bit-identical to the same capture order patched onto #35

basal-serve (fast, compile caches warm) and basal-loadtest, 32 clients:

GPU, model server GPU memory after start single questions 5 questions over 1.5k-token states
RTX 4090, mini, --batches compact #35 17,594 MiB 373.5 dec/s, p50 7.0 ms 95.1 q/s
this branch 9,388 MiB 370.0 dec/s, p50 7.9 ms 95.7 q/s
repeat A B A B, 3 runs each #35 379.3, this 378.7 dec/s (p50 6.8-7.7 ms both)
RTX 4090, 4.5B, default this branch 17,852 MiB 70.0 dec/s, p50 18.3 ms 32.8 q/s
RTX 4090, 4.5B, --batches compact #35 out of memory
this branch 18,372 MiB 131.8 dec/s, p50 16.8 ms 32.5 q/s
RTX 4060 Ti 16 GB, mini, --batches compact #35 out of memory
this branch 9,078 MiB 117.6 dec/s, p50 15.6 ms 28.0 q/s
RTX 4060 Ti 16 GB, mini, default this branch 8,708 MiB 57.4 dec/s, p50 19.9 ms 28.0 q/s

Start-up time is unchanged (mini compact, A B A B: 193 / 192 s vs 194 / 190 s).

RTX 3090 (Ampere): basal-2.0-mini, mini with compact rows and basal-2.0-4.5B 420 / 420 bit-identical between #35 and
this branch; basal-2.0-4.5B with compact rows out of memory on #35, starts on this branch; basal-serve --batches compact with mini 17,459 -> 9,253 MiB after start.

Tests

… outputs, reachable pass-2 graphs only

Llama graphs in GraphBackend kept every capture's output alive in the graph
pool (169 plain graphs: their hidden states [b, L, D]; 276 pass-2 graphs:
outputs and dense masks), although each readout is copied out right after
its replay on the same stream.

- _shared_out: one output buffer per graph family (plain, pass 2) and one
  pass-2 mask buffer; _copy_same keeps the copy exact.
- _pass2_ok: pass-2 graphs only for batches pass 1 can form (12 of 276
  never ran); the key / value buffer 24,576 -> 16,384 tokens.
- _capture warms up on one side stream (each stream kept a cuBLAS
  workspace).

RTX 4090, 2.3.1 vs this: mini 12.7 -> 10.0 GB (compact rows 18.7 -> 17.6),
4.5B 24.1 -> 20.5 GB; probabilities bit-identical (420/420 each), the
same decisions per second and start-up.
…e output buffer

warm() (Llama) runs every graph's warm-up calls in the grid's order (so
torch.compile compiles exactly as before) and then captures them all, the
most tokens first: captured from the smallest up, every larger graph
allocated new blocks in the shared pool instead of reusing the ones the
smaller graphs freed. The compact graphs write their hidden states into
one shared buffer, like the plain and pass-2 graphs (rkinas#35).
… capture order

With --prefix-cache the two pass-2 families share shapes: a key already
waiting for _capture_deferred is not warmed up again. The order test runs
with and without the prefix family.
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR lowers Llama fast-mode GPU memory by warming graphs in the existing grid order but deferring CUDA-graph recording, capturing largest-first for allocator reuse, and sharing graph outputs and pass-2 masks; it also filters unreachable pass-2 shapes, preserves output correctness, and adds focused ordering, storage, and reachability tests.

Sequence diagram for deferred largest-first CUDA graph capture

sequenceDiagram
    participant GraphBackend
    participant WarmupStream
    participant GraphPool
    participant CUDACompile

    GraphBackend->>GraphBackend: warm()
    loop Grid order
        GraphBackend->>WarmupStream: _warm_up(fn, static, n)
        WarmupStream->>CUDACompile: fn(*static)
        CUDACompile-->>WarmupStream: compiled and warmed
        GraphBackend->>GraphBackend: defer graph key
    end
    GraphBackend->>GraphBackend: _capture_deferred()
    loop Descending _graph_tokens
        GraphBackend->>GraphPool: _record(key, fn, static)
        GraphPool-->>GraphBackend: reuse freed blocks where possible
    end
Loading

Flow diagram for shared Llama graph outputs

flowchart LR
    Warm[_warm_up in grid order] --> Deferred[Deferred graph keys]
    Deferred --> Capture[_capture_deferred]
    Capture --> Largest[Capture largest graphs first]
    Largest --> Pool[Shared CUDA graph pool]
    Pool --> Plain[_shared_out plain]
    Pool --> Compact[_shared_out compact]
    Pool --> Pass2[_shared_out pass2 and mask]
    Plain --> Replay[Graph replay and readout]
    Compact --> Replay
    Pass2 --> Replay
Loading

File-Level Changes

Change Details Files
Defers Llama CUDA graph captures until all graphs are warmed up, then records them in descending graph size so the shared CUDA memory pool can reuse blocks from larger captures.
  • Preserves grid-order warm-ups and torch.compile behavior while deduplicating shared prefix/pass-2 shapes.
  • Adds graph-size ordering and reachability filtering for pass-2 graphs, including corresponding KV-buffer sizing.
  • Keeps on-demand captures unchanged outside warm().
basal/engine.py
Reduces persistent graph allocations by routing Llama graph outputs and pass-2 masks through shared buffers.
  • Shares plain, compact, and pass-2 output storage across captured graphs.
  • Shares the pass-2 mask buffer and serializes replay/readout usage under the existing launch lock.
  • Preserves readout-layer outputs and validates shared-buffer shape and dtype compatibility.
basal/engine.py
Documents the reduced GPU-memory footprint and newly viable compact configurations.
  • Adds release notes covering capture ordering, shared buffers, reachability filtering, memory savings, throughput, and supported 16 GB/24 GB scenarios.
docs/WHATS_NEW.md
Adds CPU/fake-capture coverage for capture ordering, shared storage, reachable pass-2 shapes, and output correctness.
  • Verifies all warm-ups precede captures, captures are unique and largest-first, and prefix-family duplicates are deduplicated.
  • Checks shared outputs remain correct across concurrent graph families and replays.
  • Validates pass-2 reachability and KV sizing against chunk formation.
tests/test_engine16.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot 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.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="1878" />
<code_context>
             f"torch's varlen attention ({why})")


+def _copy_same(dst, src):
</code_context>
<issue_to_address>
**Concurrent streams corrupt probabilities**

When two callers invoke the backend on different current CUDA streams, `_launch` serializes host enqueueing but does not order CUDA work across streams, so a later call overwrites the family buffer or `_shared_out` before the earlier call finishes reading it; callers receive corrupted probabilities.

Order CUDA work across streams before reusing these shared buffers, or give each stream independent buffers.

Also at `basal/engine.py:899-912`, `basal/engine.py:1326`, `basal/engine.py:1359`, `basal/engine.py:1388`, `basal/engine.py:1875-1877`.
</issue_to_address>

### Comment 2
<location path="tests/test_engine16.py" line_range="182-185" />
<code_context>
+            g[0].replay = (lambda r, k: lambda: (used.append(k), Replay.replay(r)))(g[0], key)
+    s = [1] + [rnd.randrange(3, 50) for _ in range(12)]
+    q = prompt(rnd, s, 8)  # rows of 10 tokens below the root: a pass-2 graph of 16 that covers the root's 13
+    check(be, [([s, q + [10, 11], q + [11, 10]], [[7, 8], [10, 11], [10, 11]]),  # readouts in the root and below
+               ([prompt(rnd, s, 5)], [[7, 8, 9]])])
+    assert used == [("x", 1, 16, 16)] and ("tree", 1, 13) in be.replays
+    check(be, groups(rnd))
+    for fam in "px":
+        assert len({g[-1].untyped_storage().data_ptr() for k, g in be.graphs.items() if k[0] == fam}) == 1
</code_context>
<issue_to_address>
**Missing readouts pass the shared-output checks**

When `run_shared()` returns fewer groups or readouts than requested, with the returned prefix correct, `test_shared_graph_outputs_keep_every_readout` and `test_warm_captures_largest_first_after_every_warm_up` call `check()`, whose nested `zip` comparisons silently skip missing groups or readouts. If `run_shared()` returns fewer results but the remaining values are correct, these checks pass without verifying every readout.

Assert that the result group and readout counts match the inputs before comparing values.

Also at `tests/test_engine16.py:229`.
</issue_to_address>

### Comment 3
<location path="tests/test_engine16.py" line_range="241" />
<code_context>
+        for n in range(1, be.TREE_ROWS[-1] + 1):
+            for idx in be._chunks([L] * n, be.PLAIN_LENS, [8] * n, be.TREE_ROWS[-1]):
+                reach.add((be._bucket(len(idx), be.TREE_ROWS), L))
+    assert {(b, L) for b in be.TREE_ROWS for L in be.LENS if be._pass2_ok(b, L)} == reach
+    assert be._kv_tokens() == max(be.TOKEN_BUDGET, be.PLAIN_LENS[-1], max(b * L for b, L in reach))
+    assert be._kv_tokens() < be.TREE_ROWS[-1] * be.LENS[-1]
</code_context>
<issue_to_address>
**Reachability test skips graph capture**

When `warm()` stops applying `_pass2_ok` when capturing pass-2 graphs, `test_pass2_graphs_are_the_reachable_shapes` compares `reach` with a set filtered by `_pass2_ok`, but never calls `warm()` or inspects captured graph keys. If `warm()` captures unreachable pass-2 shapes, this assertion and the `_kv_tokens()` assertion still pass.

Warm a backend in the test and compare its captured pass-2 graph keys with the reachable set.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/engine.py Resolved
Comment thread tests/test_engine16.py Resolved
Comment thread tests/test_engine16.py Resolved
… runs warm()

- check() asserts one result group per request, one readout per prompt
  and one probability per option before comparing values.
- test_pass2_graphs_are_the_reachable_shapes runs warm() on the default
  grid with recording graph builders and compares the pass-2 shapes it
  asks for with the batches pass 1 can form.
@rkinas
rkinas merged commit 1f45217 into rkinas:main Oct 22, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 22, 2026
@rkinas

rkinas commented Oct 22, 2026

Copy link
Copy Markdown
Owner

Thanks again @Butterski. Capturing largest first fixes the compact-rows memory, and it is easy to follow. Merged after #35. Only your four commits came in, and the only conflict was WHATS_NEW. On an H100:

  • mini with compact rows (the server default on Hopper): 16.6 -> 7.3 GB after warm-up, graph pool 9.3 -> 1.0 GiB;
  • 4.5B with compact rows: 27.3 -> 15.4 GB, so it now fits 24 GB cards as you measured on the 4090;
  • compact rows now cost only 0.1-0.2 GB more than default rows;
  • every probability is bit-identical to v2.3.2 (1,640 of 1,640 readouts per model and batching mode, plus --readout-layer on), and throughput is within noise (mini compact 203 / 209 dec/s, 280 / 286 q/s; 4.5B compact 181 / 206 dec/s, 107 / 108 q/s); server start-up is unchanged;
  • basal-omni (Gemma 4) gives the same answers. The one shared warm-up stream also saves 0.66 GB there.

Thanks for fixing the two test points from the bot review. We added one docs commit that updates docs/SERVING.md (it still said the 4.5B with compact rows runs out of memory on 24 GB). If you want a follow-up: the Gemma 4 compact graphs still capture smallest first (10.6 GiB of pool, 0.7 GiB allocated on omni-mini), so the same order might help there. It is in basal 2.3.3: https://github.com/rkinas/basal/releases/tag/v2.3.3. Thank you!

rkinas added a commit that referenced this pull request Oct 22, 2026
warm() now defers the captures of basal-omni's graphs as it does for Llama
since 2.3.3 (#37): every graph is warmed up in the grid's order (the same
compiled kernels), then captured, the most tokens first. The pass-2 graphs
over roots beyond LENS come after the others and are captured as they are
warmed up, so _warm_long_sfx still measures the pool per graph.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants