Repository navigation
perf(fast): capture the CUDA graphs largest first (compact rows on 16 GB and 24 GB cards) - #37
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.
…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.
Reviewer's GuideThe 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 capturesequenceDiagram
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
Flow diagram for shared Llama graph outputsflowchart 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
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 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>… 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.
|
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:
Thanks for fixing the two test points from the bot review. We added one docs commit that updates |
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.
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):--batches compactSo compact rows (#29's
--batches compacton 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_sfxmeasures 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 compiledkernels are those of today) and defers the captures:
_capture_deferredthen captures them all, the most tokensfirst (
_graph_tokens: rows x length, pass 2 then by query-key pairs). Each smaller graph reuses blocks a larger onefreed. A shape that two families ask for (
--prefix-cache: plain pass 2 and the prefix family) is warmed up andcaptured once.
_captureis split into_warm_upand_record; outsidewarm()(graphs captured on demand) nothing changes._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 andpass-2 graphs (104 graphs, 0.8 GiB on basal-2.0-mini). With
--readout-layer ontheir output is[32, D]and staysas it is.
Measurements
RTX 4090 24 GB, torch 2.13.0+cu130; #35's engine vs this branch,
GraphBackendbuilt directly, memory fromtorch.cuda.mem_get_infoafter warm-up, probabilities of the identity items (basal.identity.build: 200 singlequestions, 40 five-question requests, 20 long):
--batches compact--readout-layer on--batches compactbasal-serve(fast, compile caches warm) andbasal-loadtest, 32 clients:--batches compact--batches compact--batches compactStart-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 compactwith mini 17,459 -> 9,253 MiB after start.Tests
test_warm_captures_largest_first_after_every_warm_up(tests/test_engine16.py, with and without the prefixfamily): every warm-up call comes before the first capture, captures run in descending
_graph_tokens, each graphis warmed up and captured once although the prefix family asks for shared shapes twice, and the replays answer as
separate forwards. Capturing in ascending order, not deferring, or warming duplicate keys again each fail it.
mainand perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35 with 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): allprobabilities bit-identical, the same graphs as perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35.
check()(the routing tests' helper) now compares result and readout counts before values, and perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35'stest_pass2_graphs_are_the_reachable_shapesrunswarm()and compares the pass-2 shapes it asks for (it fails withwarm()reverted to the condition before perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35).--prefix-cache on(the shapes two families share), basal-2.0-mini on an RTX 4060 Ti 16 GB: perf(fast): less GPU memory for basal-2.0's CUDA graphs (shared graph outputs, reachable pass-2 graphs only) #35 vs thisbranch 420 / 420 bit-identical.
tests/(withouttest_gguf.py): CPU 666 passed, 81 skipped; RTX 4060 Ti 16 GB 700 passed, 47 skipped.