Skip to content

perf(fast): pass-2 graphs only while GPU memory stays free (basal-2.0-4.5B on 16 GB cards) - #41

Closed
Butterski wants to merge 6 commits into
rkinas:mainfrom
Butterski:perf/pass2-graph-budget
Closed

Butterski wants to merge 6 commits into
rkinas:mainfrom
Butterski:perf/pass2-graph-budget

Conversation

@Butterski

@Butterski Butterski commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Rebased on 2.3.4: its Gemma 4 capture order (a63cfdb) replaces #40's commits, which this branch carried before. The
GPU numbers below were measured on 47ae982 with #40; the Llama capture code they measure is the same after the
rebase, and 2.3.4 leaves basal-2.0's probabilities as in 2.3.3 (its release notes).

Problem

basal-2.0-4.5B in --mode fast does not start on a 16 GB card (RTX 4060 Ti 16 GB, 4080, 5060 Ti) on 2.3.3: it runs
out of memory while capturing its CUDA graphs. After #35 / #37 it uses 19.3 GB after start-up on an RTX 4090, of which
about 6 GB sit outside PyTorch's allocator: every captured graph keeps device memory for its kernels, about 8 MB per
plain graph (compiled) and 19.5 MB per pass-2 graph (the uncompiled transformers forward, many small kernels) on
4.5B, and does not give it back. 264 pass-2 graphs are about 5 GB of it.

A pass-2 graph is an optimisation the engine can do without: _tree_hidden looks it up (self.graphs.get) and runs
pass 2 uncompiled when it is missing, as it does for every shape beyond the grid. The plain and compact graphs are
needed (a forward without one would capture it under load).

Change

GraphBackend._capture_deferred (basal/engine.py): the plain and compact graphs are all captured as before, the
largest first; then the pass-2 graphs, the smallest first (one unit, short roots, short branches: the commonest
requests), and only while PASS2_RESERVE (1.5 GiB) of GPU memory stays free after the capture (_room: the free
memory, _free_memory, less what the last capture took, _measured). Gemma 4's pass-2 graphs over the longer roots
(_warm_long_sfx) stop at the same reserve, besides their PASS2_POOL. If some are left out, start-up says so
(basal: 80 of 264 pass-2 graphs captured, 1536 MiB of GPU memory kept free; the other shapes run pass 2 without a graph). Where everything fits, every graph is captured, as today; the pass-2 graphs are now captured smallest first,
which changes neither the graphs nor their answers.

Measurements

basal-2.0-4.5B, torch 2.13.0+cu130, main = 47ae982 (2.3.3).

RTX 4090 24 GB, GraphBackend built as --mode fast builds it, the identity items of basal.identity.build (200
single questions in batches of 16, 40 five-question requests, 20 long):

graphs (plain + pass 2) GPU memory after warm-up graph pool probabilities vs main
main 169 + 264 19,308 MiB 1.19 GiB
this branch 169 + 264 19,308 MiB 1.19 GiB 420 / 420 bit-identical
this branch, PASS2_RESERVE 9.5 GiB (a 16 GB card's room) 169 + 56 15,834 MiB 1.19 GiB five-question and long: 220 / 220 bit-identical; single: same top 200 / 200, max |dp| 0.043

basal-2.0-mini on the same card: 420 / 420 bit-identical, the same memory. The single questions that change are the
batches of up to 8 units whose pass-2 graph was left out: the uncompiled pass 2 pads rows and branch length
differently (bf16 rounding, as between batch sizes).

RTX 4060 Ti 16 GB (15.6 GiB usable), this branch at 3b4c2f4 (the review fix: one pass-2 graph fewer than a21e8d7's
81; the 420 identity readouts bit-identical between the two):

main this branch
start-up (GraphBackend) out of memory while capturing graphs 169 + 80 graphs, ready
basal-serve ready in 791 s, 14,424 MiB after start
single questions (questions.jsonl, 32 clients) 22.6 dec/s, p50 51 ms, 0 errors
5 questions over 1.5k-token states 9.7 q/s, 0 errors
5 questions over 6k-token states (a21e8d7) 2.5 q/s, 0 errors

Large compress requests (synthetic case logs, one unit per line, keep_ratio 0.3; measured at a21e8d7) on the
same 16 GB card, one at a time and then four at once, with this branch alone and with #39 (the CUDA cascade, which
drops the dense pass-2 mask and repeated keys of such requests) merged in:

request this branch this branch + #39
compress, en 1.5k / 3k / 6k tokens 1.5 / 4.0 / 10.1 s 1.4 / 3.0 / 8.0 s
compress, pl 1.5k / 3k / 6k tokens 1.4 / 3.5 s / 503 (out of memory) 1.3 / 2.8 / 7.5 s
6k compress x2 + 40 questions x2 at once 2 of 6 answered, 4 x 503 6 of 6 answered

So without #39 the largest compress requests can still run out of memory on a 16 GB card (the server answers 503 and
frees the memory; the next requests are answered): their dense pass 2 needs about 3.8 GB above the start-up memory
(RTX 4090, #39), more than a 16 GB card has left even with no pass-2 graph. With #39 they fit.

Tests

  • New test_pass2_graphs_captured_while_memory_stays_free (tests/test_engine16.py, a simulated GPU where every
    captured graph takes one unit): every plain graph is captured, then the pass-2 graphs, the smallest first, until
    PASS2_RESERVE would be crossed, and the reserve is still free after the last capture; a request whose pass-2 shape
    lost its graph (4 units over 12-token roots) runs without one and every readout equals its prompt run alone; with
    room for all, all are captured. Without the budget, with the pass-2 graphs largest first, with the budget over the
    plain graphs too, or with the reserve checked before the capture only, it fails.
  • New test_gemma_long_root_graphs_keep_the_reserve: Gemma 4's long-root pass-2 graphs stop at the reserve too
    (fails without the check).
  • test_warm_captures_largest_first_after_every_warm_up (Llama) and test_warm_captures_largest_first_then_long_pass2
    (Gemma 4, tests/test_gemma4_graph.py): plain / compact graphs the largest first, then pass 2 the smallest first.
  • tests/ (without test_gguf.py): CPU 708 passed, 81 skipped; RTX 4090 738 passed, 47 skipped (before the fix).

Also

One small thing: my name in the README's contributors list is now Miłosz Kucharski (it was Milosz), and this PR's
WHATS_NEW entry uses it too (ed9131e). The older WHATS_NEW entries and the README's release notes still say Milosz;
change them as you prefer.

@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR makes fast-mode CUDA graph initialization fit constrained GPUs by capturing required plain graphs first and opportunistically retaining pass-2 graphs only while a 1.5 GiB runtime reserve remains, with uncompiled fallback for omitted shapes; it adds targeted ordering and fallback tests and documents the performance and numerical trade-offs.

Sequence diagram for memory-aware CUDA graph capture

sequenceDiagram
    participant GraphBackend
    participant CUDA
    participant Runtime

    GraphBackend->>GraphBackend: warm()
    GraphBackend->>GraphBackend: _capture_deferred()
    GraphBackend->>GraphBackend: _record(plain_graph)
    GraphBackend->>CUDA: empty_cache()
    loop pass-2 graphs, smallest first
        GraphBackend->>GraphBackend: _free_memory()
        alt at least PASS2_RESERVE free
            GraphBackend->>GraphBackend: _record(pass2_graph)
        else reserve would be crossed
            GraphBackend->>Runtime: print capture summary
            Note over Runtime: Remaining pass-2 shapes run uncompiled
        end
    end
Loading

Flow diagram for pass-2 graph fallback

flowchart TD
    A[Request needs pass-2 shape] --> B{Captured pass-2 graph exists?}
    B -->|Yes| C[Run captured graph]
    B -->|No| D[Run pass 2 uncompiled]
    C --> E[Produce readout]
    D --> E
Loading

File-Level Changes

Change Details Files
Bound deferred pass-2 CUDA graph capture by available GPU memory while preserving all required graph captures.
  • Added a 1.5 GiB free-memory reserve for runtime allocations.
  • Capture plain and compact graphs first, largest to smallest; capture pass-2 graphs afterward, smallest/commonest shapes first.
  • Stop pass-2 capture when the reserve would be crossed and fall back to uncompiled execution for omitted shapes.
  • Clear cached CUDA blocks before pass-2 capture and report the number of captured versus omitted graphs.
  • Adjusted warm-up sequencing so Gemma 4 captures grid graphs before measuring and capturing longer-root pass-2 graphs.
basal/engine.py
Added coverage for capture ordering, memory-budget enforcement, fallback execution, and Gemma-specific warm-up behavior.
  • Simulated constrained GPU memory and verified all plain graphs remain captured while pass-2 graphs are selected by smallest shape.
  • Verified omitted pass-2 shapes execute correctly without graphs and retain expected readouts.
  • Verified unlimited memory captures every pass-2 graph and that Gemma long-root captures remain warm-up/capture pairs.
  • Updated existing ordering assertions for separate plain and pass-2 capture phases.
tests/test_engine16.py
Documented the 16 GB-card startup optimization, its runtime trade-offs, and the related Gemma graph-capture improvement.
  • Added release notes covering memory usage, capture counts, throughput, numerical differences, and remaining OOM conditions without the CUDA cascade.
  • Corrected the contributor’s accented name in the README and release notes.
docs/WHATS_NEW.md
README.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

Butterski added a commit to Butterski/basal that referenced this pull request Oct 22, 2026

@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 4 issues

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

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="1172" />
<code_context>
                             if b * S <= self.TOKEN_BUDGET:
                                 self._graph_sfx(b, S, L)
             if self.gemma is not None:
+                self._capture_deferred()  # (the pool _warm_long_sfx measures from)
                 self._warm_long_sfx()
         if self._deferred is not None:
</code_context>
<issue_to_address>
**Long-root captures consume reserved memory**

When gemma 4 is running on CUDA, longer-root pass-2 graphs are eligible for capture, and deferred captures leave little headroom, `warm()` calls `_warm_long_sfx` after `_capture_deferred`, but `_warm_long_sfx` captures those additional graphs without checking free memory. Its `PASS2_POOL` check tracks allocator-reserved growth, not retained kernel memory, so startup consumes the advertised reserve or runs out of GPU memory.

Apply a free-memory budget that accounts for retained kernel allocations to the longer-root pass-2 captures as well.

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

### Comment 2
<location path="basal/engine.py" line_range="1495-1498" />
<code_context>
+            torch.cuda.empty_cache()  # (blocks the warm-up calls left cached are no graph's)
+        for n, key in enumerate(pass2):
+            free = self._free_memory()
+            if free is not None and free < self.PASS2_RESERVE:
+                print(f"basal: {n} of {len(pass2)} pass-2 graphs captured, {self.PASS2_RESERVE >> 20} MiB of GPU "
+                      "memory kept free; the other shapes run pass 2 without a graph", flush=True)
+                break
+            self._record(key, *deferred[key])
+
</code_context>
<issue_to_address>
**Large requests deny GPU service**

When an unauthenticated HTTP client submits a large but context-valid `compress` request on a 16-GB CUDA card whose pass-2 shape was omitted, `_capture_deferred` leaves the shape uncaptured, so `_tree_hidden` runs its uncompiled dense pass 2; when that exhausts GPU memory, the HTTP handler returns 503 and denies the request, with concurrent requests also at risk of failure.

Add memory-aware admission control or a bounded-memory fallback for requests whose pass-2 graph was not captured.
</issue_to_address>

### Comment 3
<location path="basal/engine.py" line_range="1495" />
<code_context>
+            torch.cuda.empty_cache()  # (blocks the warm-up calls left cached are no graph's)
+        for n, key in enumerate(pass2):
+            free = self._free_memory()
+            if free is not None and free < self.PASS2_RESERVE:
+                print(f"basal: {n} of {len(pass2)} pass-2 graphs captured, {self.PASS2_RESERVE >> 20} MiB of GPU "
+                      "memory kept free; the other shapes run pass 2 without a graph", flush=True)
</code_context>
<issue_to_address>
**Pass-2 capture breaks the reserve**

When a pass-2 graph is captured with free memory at or just above `PASS2_RESERVE`, `_capture_deferred` checks memory before `_record` retains the graph's device-side kernel allocations, so the capture leaves less than `PASS2_RESERVE` free and runtime forwards get less headroom than promised. The test's `+ 1` expectation also treats capturing at exactly the reserve as valid.

Account for each graph's retained device allocations when enforcing the reserve, and update the capture-count test so it requires the reserve to remain free after capture.

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

### Comment 4
<location path="docs/WHATS_NEW.md" line_range="15-16" />
<code_context>
+  answer on 200 of 200, max |Δp| 0.04). Contributed by Miłosz Kucharski (@Butterski).
+
+- **basal-omni's CUDA graphs captured largest first too** (`--mode fast`, Gemma 4): as for the Llama models in 2.3.3,
+  every graph is warmed up in the usual order and then captured largest first, so each capture reuses the pool memory a
+  larger one freed; the pass-2 graphs over longer roots follow one at a time, within their 1 GB budget as before.
+  basal-omni-1.0-mini on an A100 (default rows): graph pool 4.5 -> 3.2 GiB, 1.3 GB less GPU memory after start-up,
+  every probability bit-identical (420 readouts). Suggested in #37. Contributed by Milosz (@Butterski),
</code_context>
<issue_to_address>
**Pass-two capture order is misstated**

When a reader consults the new Gemma 4 capture-order description, the release note and `warm()` docstring say every graph is captured largest first, but `_capture_deferred` captures pass-2 (`x`) graphs smallest first; readers get the wrong capture-order description.

Clarify that plain and compact graphs are captured largest first, while pass-2 graphs within the grid are captured smallest first.

Also at `basal/engine.py:1150-1151`.
</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 basal/engine.py Resolved
Comment thread basal/engine.py Resolved
Comment thread docs/WHATS_NEW.md Resolved
…basal-2.0-4.5B on 16 GB cards)

_capture_deferred captures the plain and compact graphs as before (all of
them, the largest first), then the pass-2 graphs, the smallest first,
only while PASS2_RESERVE (1.5 GiB) of GPU memory stays free. Each pass-2
graph keeps 10-20 MB outside the pool for its kernels; 264 of them about
5 GB on basal-2.0-4.5B, which therefore did not start on a 16 GB card. A
pass 2 without its graph runs uncompiled, as one beyond the grid does.
Where everything fits (24 GB and up) every graph is captured.
…s long-root graphs within it too

- _room: one more pass-2 graph only while the free GPU memory less what
  the last capture took (_measured) stays at or above PASS2_RESERVE, so
  the reserve is still free after the capture, not just before it.
- _warm_long_sfx (Gemma 4) stops at the same reserve, not only at
  PASS2_POOL, which counts the pool and not a graph's kernel memory.
- warm() docstring: plain / compact largest first, pass 2 smallest first.
@Butterski
Butterski force-pushed the perf/pass2-graph-budget branch from 8140cd8 to 45309e5 Compare October 22, 2026 23:03
rkinas pushed a commit that referenced this pull request Oct 23, 2026
…basal-2.0-4.5B on 16 GB cards)

#41 by Miłosz Kucharski (@Butterski), rebased on basal 2.3.4 without #40
(main already has the same change, a63cfdb): pass-2 graphs last, the
smallest first, while PASS2_RESERVE stays free; Gemma 4's long-root graphs
within it too; WHATS_NEW and the README contributor name.
rkinas added a commit that referenced this pull request Oct 23, 2026
…r (pass-2 graphs last, the smallest first)
rkinas added a commit that referenced this pull request Oct 23, 2026
@rkinas

rkinas commented Oct 23, 2026

Copy link
Copy Markdown
Owner

Thank you, Miłosz. #41 is in basal 2.3.5, released today: https://github.com/rkinas/basal/releases/tag/v2.3.5.
It went in rebased on 2.3.4 without #40 (main already had that change), as one commit with your authorship (2d7d009), so GitHub shows this PR as closed rather than merged.

What we measured on an H100:

  • When everything fits: nothing changes: the same graphs, the same memory, and bit-identical answers (basal-2.0-mini and 4.5B, default and compact rows, basal-omni-1.0-mini and 1.0-max).
  • On a 16 GB budget simulated on the H100: the 4.5B kept 200 of 264 pass-2 graphs (compact rows), 2.0 GB stayed free, and the identity readouts were the same as with every graph.
  • The 16 GB failure itself: the H100 needs less memory per graph than your RTX 4090 / 4060 Ti, so we could not reproduce it here; your 4060 Ti numbers are the evidence, and they are in the release notes.
  • One test of ours changed: the Gemma 4 capture-order test from 2.3.4 now expects your order, pass-2 graphs last and smallest first (e1014d6).

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