Repository navigation
perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) - #35
Conversation
… 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.
Reviewer's GuideThe 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 outputssequenceDiagram
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
Flow diagram for reachable pass-2 graph captureflowchart 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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>…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).
|
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
We also checked the stream question from the bot review. Every forward is enqueued under |
Problem
In the graph engine (
--mode fast, Llama models: basal-2.0-mini, basal-2.0-4.5B) every captured CUDA graph keeps thetensors it returned during capture alive in the graph pool for as long as the graph lives:
[b, L, hidden](up to 12,288 x 2,048 bf16 = 48 MiB on4.5B), and each of the 276 pass-2 graphs its own output and its own dense mask
[b, 1, S, L + S];_launch, on the same stream), so one bufferper graph family would do;
(
_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);
_capturemakes a new side stream per graph (the pool hands out up to 32), and each stream keeps its own cuBLASworkspace.
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 captureout.copy_(fwd(...))into aview 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_hiddenreads both after pass 2._copy_samerefuses 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] + 1rootspadded to
BATCHESx L withinTOKEN_BUDGET);_kv_tokenssizes 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._capturewarms 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 fromnvidia-smiafterwarm-up, probabilities from the identity items of
basal.identity.build(200 single questions, 40 five-questionrequests, 20 long;
GraphBackendbuilt directly,run_sharedin batches).main--batches compactbasal-serve --model basal-2.0-mini(fast, its defaults),basal-loadtest, 32 clients:mainquestions.jsonl): decisions/s, p50The 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 CUDAgraph does, instead of a private clone, so every routing test runs through the shared buffers.
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.
test_pass2_graphs_are_the_reachable_shapes: on the default grid, the pass-2 graphs kept are exactly the(rows, root) batches
_chunkscan form, and the key / value buffer is the largest of those. A stricter and a looser(today's)
_pass2_okboth fail it.mainwith a fake capture (small random Llama, fp32, every path: plain, pass-2 graph,uncompiled pass 2, readouts in the root, long roots,
--prefix-cachefamily, state-cache hits): all probabilitiesbit-identical; 4 of 85 graphs (the unreachable ones of that grid) not captured.
tests/(withouttest_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:
Documentation:
Tests: