Skip to content

perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) - #35

Merged
rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/graph-memory-trims
Oct 22, 2026
Merged

rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/graph-memory-trims

Conversation

@Butterski

@Butterski Butterski commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

In the graph engine (--mode fast, Llama models: basal-2.0-mini, basal-2.0-4.5B) every captured CUDA graph keeps the
tensors it returned during capture alive in the graph pool for as long as the graph lives:

  • each of the 169 plain graphs keeps its own hidden states [b, L, hidden] (up to 12,288 x 2,048 bf16 = 48 MiB on
    4.5B), and each of the 276 pass-2 graphs its own output and its own dense mask [b, 1, S, L + S];
  • yet every forward's readout is copied out right after its replay (under _launch, on the same stream), so one buffer
    per graph family would do;
  • 12 of the pass-2 graphs (8 rows over roots of 2,304-3,072 tokens) can never run: pass 1 chunks at most 4 such roots
    (_chunks: 6 x 2,304 > TOKEN_BUDGET), and the key / value buffer is sized for them (TREE_ROWS[-1] x LENS[-1] =
    24,576 tokens instead of 16,384);
  • _capture makes a new side stream per graph (the pool hands out up to 32), and each stream keeps its own cuBLAS
    workspace.

On an RTX 4090 basal-2.0-4.5B uses 24.1 of the card's 24.6 GB after start-up.

Change

All in GraphBackend (basal/engine.py); Gemma 4 (basal-omni) graphs and the FlexAttention pass 2 are unchanged:

  • _shared_out(name, n, dtype): one flat buffer per family. Llama plain graphs capture out.copy_(fwd(...)) into a
    view of the "plain" buffer, Llama dense pass-2 graphs into "pass2", and their masks are views of one "pass2 mask" buffer (the mask is written whole before every replay). Plain and pass-2 outputs are separate buffers, since
    _tree_hidden reads both after pass 2. _copy_same refuses a dtype / shape mismatch, so the copy is exact.
  • _pass2_ok(b, L): a pass-2 graph is captured only if pass 1 can form such a batch (TREE_ROWS[i - 1] + 1 roots
    padded to BATCHES x L within TOKEN_BUDGET); _kv_tokens sizes the key / value buffer for the graphs that exist.
    Units with cached roots (--state-cache-gb) are chunked the same way, so they reach the same graphs.
  • _capture warms every capture up on one side stream.

Measurements

RTX 4090 24 GB (vast.ai), torch 2.13.0+cu130, main (621bc57, 2.3.1) vs this branch. Memory from nvidia-smi after
warm-up, probabilities from the identity items of basal.identity.build (200 single questions, 40 five-question
requests, 20 long; GraphBackend built directly, run_shared in batches).

model, batching main this branch probabilities
basal-2.0-mini, default 12,702 MiB 9,954 MiB 420 / 420 bit-identical
basal-2.0-mini, --batches compact 18,724 MiB 17,590 MiB 420 / 420 bit-identical
basal-2.0-4.5B, default 24,122 MiB 20,462 MiB 420 / 420 bit-identical

basal-serve --model basal-2.0-mini (fast, its defaults), basal-loadtest, 32 clients:

main this branch
ready (compile caches warm) 213 s 217 s
GPU memory after start-up / after the load tests 12,702 / 13,006 MiB 9,954 / 10,272 MiB
single questions (questions.jsonl): decisions/s, p50 128.7, 9.7 ms 128.4, 9.5 ms
5 questions over 1.5k-token states: questions/s, p50 53.4, 78 ms 54.5, 80 ms

The graph pool after warm-up (mini) 3.54 -> 1.88 GiB. The compact graphs (9 GiB of graph pool with
--batches compact) are not touched here.

Tests

  • tests/test_engine16.py: the fake graph (Replay) now keeps the tensor the function returned at capture, as a CUDA
    graph does, instead of a private clone, so every routing test runs through the shared buffers.
  • New test_shared_graph_outputs_keep_every_readout: one unit read out inside its root (pass 1's buffer) and below it
    (a pass-2 graph that covers the root's columns), plus plain prompts and the routing groups; every readout equals its
    prompt run alone, and each family keeps one output storage. Pointing pass 2 at the plain buffer fails it.
  • New test_pass2_graphs_are_the_reachable_shapes: on the default grid, the pass-2 graphs kept are exactly the
    (rows, root) batches _chunks can form, and the key / value buffer is the largest of those. A stricter and a looser
    (today's) _pass2_ok both fail it.
  • CPU, a throwaway check against main with a fake capture (small random Llama, fp32, every path: plain, pass-2 graph,
    uncompiled pass 2, readouts in the root, long roots, --prefix-cache family, state-cache hits): all probabilities
    bit-identical; 4 of 85 graphs (the unreachable ones of that grid) not captured.
  • tests/ (without test_gguf.py): CPU 664 passed, 81 skipped; RTX 4090 698 passed, 47 skipped.

Summary by Sourcery

Reduce fast-mode GPU memory consumption for basal-2.0 CUDA graphs while preserving outputs and throughput.

Enhancements:

  • Reduce GPU memory usage for Llama CUDA graphs by sharing captured outputs and pass-2 masks within graph families.
  • Capture only reachable pass-2 graph shapes and size key/value buffers to the graphs that can actually run.
  • Reuse a single warm-up CUDA stream for graph capture to avoid redundant per-stream cuBLAS workspaces.

Documentation:

  • Document the fast-mode GPU memory reductions and unchanged performance and output correctness.

Tests:

  • Add coverage for shared graph output storage, readout correctness across routing paths, and reachable pass-2 graph shapes.

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

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR lowers fast-mode Llama GPU memory usage by sharing captured outputs and pass-2 masks across graph families, skipping pass-2 shapes that pass 1 cannot produce, sizing KV storage to the retained graphs, and reusing one capture warm-up stream. Tests model CUDA graph output retention and validate routing, storage sharing, reachable shapes, bit-identical probabilities, and the reported memory/performance improvements; Gemma 4 and FlexAttention behavior remains unchanged.

Sequence diagram for shared CUDA graph replay outputs

sequenceDiagram
    participant Launch as _launch
    participant Graph as CUDA graph
    participant Forward as Llama forward
    participant Buffer as Shared output buffer
    participant Readout as Readout
    Launch->>Graph: replay()
    Graph->>Forward: fwd(...) or fwd_sfx(...)
    Forward-->>Graph: hidden states
    Graph->>Buffer: _copy_same(shared view, hidden states)
    Launch->>Readout: copy readout from buffer
Loading

Flow diagram for reachable pass-2 graph capture

flowchart TD
    Start["Candidate pass-2 shape"] --> Check["_pass2_ok(b, L)"]
    Check -->|"pass 1 can produce batch"| Capture["Capture pass-2 graph"]
    Check -->|"pass 1 cannot produce batch"| Skip["Skip graph"]
    Capture --> KV["_kv_tokens sizes KV storage"]
    Skip --> KV
Loading

File-Level Changes

Change Details Files
Reduce CUDA graph memory retention by routing Llama graph outputs and pass-2 masks through shared family buffers.
  • Allocate reusable flat buffers for plain outputs, pass-2 outputs, and pass-2 masks.
  • Copy captured forward results into shape- and dtype-validated shared views.
  • Keep plain and pass-2 output storage separate because both readouts may be needed after pass 2.
  • Preserve Gemma 4 and FlexAttention paths without shared-output changes.
basal/engine.py
Capture only pass-2 graph shapes reachable from pass-1 batching and size KV storage to the captured graph set.
  • Add reachability checks based on bucketed root counts and the token budget.
  • Apply the same filtering during graph warm-up and to cached-root chunking.
  • Compute KV capacity from the largest retained pass-2 shape, eliminating unreachable graph capacity.
basal/engine.py
Reduce per-capture workspace overhead by reusing one CUDA warm-up stream.
  • Create the side stream lazily and reuse it for all graph warm-ups.
  • Retain stream synchronization and existing warm-up counts.
basal/engine.py
Strengthen CPU graph fakes and routing coverage for shared capture outputs and reachable shapes.
  • Make Replay retain the exact tensor returned during capture, matching CUDA graph lifetime behavior.
  • Verify readouts across plain, pass-1, pass-2, routing, and mixed-family paths while asserting shared storage.
  • Verify default-grid pass-2 shapes exactly match _chunks reachability and KV sizing.
tests/test_engine16.py
Document the graph-engine memory reduction and validation results.
  • Record shared buffers, skipped unreachable graphs, single-stream warm-up, GPU memory savings, and unchanged correctness/performance measurements.
docs/WHATS_NEW.md

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 1 issue

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

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="1279" />
<code_context>
             ro = torch.zeros((b, 1), dtype=torch.long, device=self.dev)
             return self._capture(key, self.fwd, ids, self._kv_views(b, L), ro)
-        return self._capture(key, self.fwd, ids, self._kv_views(b, L))
+        out = self._shared_out("plain", max(b * L for b, L in self.grid(self.PLAIN_LENS)) * self._hidden_size,
+                               self._dtype)[: b * L * self._hidden_size].view(b, L, -1)
+        fwd = self.fwd
</code_context>
<issue_to_address>
**Concurrent streams mix readouts**

When two concurrent `run_shared` calls use distinct CUDA streams, `_launch` serializes host enqueueing, but it does not order work on distinct CUDA streams: after one call queues a read from the shared output, another can replay its graph and overwrite that storage before the first read executes. The first caller then receives probabilities computed from the other call’s output.

Run all shared-buffer operations on one enforced stream, or record and wait on CUDA events so each reuse follows completion of the prior read.

Also at `basal/engine.py:1326`.
</issue_to_address>

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

Comment thread basal/engine.py Resolved
@rkinas
rkinas merged commit dc2d325 into rkinas:main Oct 22, 2026
1 check passed
rkinas pushed a commit that referenced this pull request Oct 22, 2026
…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 (#35).
rkinas added a commit that referenced this pull request Oct 22, 2026
@rkinas

rkinas commented Oct 22, 2026

Copy link
Copy Markdown
Owner

Thanks @Butterski, this is a great change. We merged it on top of 2.3.2. The only conflicts were next to the 2.3.2 refusals and in WHATS_NEW (your entry now sits under 2.3.3). On an H100 (torch 2.11, FA3), v2.3.2 vs 2.3.2 + #35 + #37, built as basal-serve --mode fast builds it:

  • every identity readout is bit-identical (mini and 4.5B, default and compact rows, --readout-layer on, --prefix-cache with --state-cache-gb, basal-omni-1.0-mini): 10,872 of 10,872, max |dp| 0;
  • memory after warm-up: mini 10.8 -> 7.1 GB, 4.5B 20.1 -> 15.2 GB; the graph pool 3.6 -> 1.0 GiB on mini;
  • load tests are within noise (mini 208 / 219 dec/s single, 287 / 290 q/s five at a time; 4.5B 172 / 168 and 104 / 104).

We also checked the stream question from the bot review. Every forward is enqueued under _launch on the default stream, and the readout is copied right after the replay, so your answer holds. _pass2_ok matches the batches _chunks forms, cached roots included. It is in basal 2.3.3: https://github.com/rkinas/basal/releases/tag/v2.3.3. Thank you!

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