Skip to content

perf(fast): less host work in the CUDA cascade (one fused merge kernel per layer, FlashAttention's op called directly) - #44

Merged
rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/cascade-launches
Nov 2, 2026
Merged

rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/cascade-launches

Conversation

@Butterski

@Butterski Butterski commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to your note on #39: basal-2.0-mini's 40-question requests ran 0.90x as fast with the cascade as with the
dense pass on your H100.

Problem

The pass 2 that has no CUDA graph runs the transformers forward uncompiled, kernel by kernel, and it is host-bound:
on an A100, mini's dense pass 2 for 40 questions over a 1.5k-token state takes 40.8 ms, of which 31.9 ms is the time
until the forward returns (the CPU issuing work). The cascade added host work per layer on top:

  • _merge_attention ran as ~15 small kernels (log-sum-exp, the two weights, casts, products, guards, sum, cast back).
  • varlen_attn, called twice per layer, wraps torch.ops.aten._flash_attention_forward in a Python custom op and
    allocates a random-number state on every call.

With these, the cascade's pass 2 for those 40 questions took 62.4 ms on the A100, almost all of it host time (62.2
ms), so the faster attention did not show; on a faster GPU the host share is larger still.

Change

  • _merge_fused: _merge_attention compiled (dynamic shapes, fullgraph), one kernel per layer, for a
    GraphBackend that compiles and has Triton (fuse_merge; fast-nocompile and torch without Triton keep the merge
    op by op). The same operations in the same order in fp32 (Inductor's exp is libdevice's, as ATen's), so the
    output is bit-identical. _warm_cascade compiles it at start-up for both layouts a cascade passes (rows without
    and with padding), so no request compiles it. _VarlenTree.fused carries the choice to _cascade_varlen.
  • _varlen calls torch.ops.aten._flash_attention_forward with the arguments varlen_attn passes (its cuDNN path
    is off in torch 2.13: _should_use_cudnn returns False): the same kernel, output and log-sum-exp bit-identical.

The dense pass, the CPU cascade (#34) and CASCADE_TOKENS are unchanged.

Measurements

A100 PCIe 40 GB, torch 2.13.0+cu130, main = 95f76e2 (2.3.5). The branch is rebased on 2.4.1: 2.4.0 left basal-2.0
bit-identical to 2.3.5 (4,960 of 4,960 readouts, its release notes), 2.4.1's one warm-up per graph (#43) keeps every
probability, and neither touches the cascade.

Pass 2 alone (real weights, random root keys and values; cascade_launch.py), median ms per forward and CUDA kernels:

model, rows dense cascade before cascade after
mini, 40 questions over 1.5k (1 row of 1,120 tokens) 40.8 ms, 1,330 kernels 62.4 ms, 1,876 48.6 ms, 1,332
mini, compress 300 sentences over 6k 357 ms (host 67) 216 ms (host 97) 211 ms (host 50)
mini, 2 padded rows over 1.5k 47.3 ms 68.7 ms 55.2 ms
4.5B, 40 questions over 1.5k 114 ms 117 ms 98.8 ms
4.5B, compress 300 sentences over 6k 914 ms 572 ms 560 ms

End to end, basal-serve with basal-2.0-mini, one client, each request with the dense pass, the cascade and the
default threshold in turn (cascade_bench.py, 7 repetitions, median ms):

request main: dense / cascade this branch: dense / cascade
5 questions over 1.5k 49.7 / 60.9 (0.82x) 50.5 / 53.6 (0.94x)
10 questions 58.9 / 60.6 (0.97x) 60.0 / 58.4 (1.03x)
20 questions 72.7 / 71.9 (1.01x) 73.8 / 71.0 (1.04x)
40 questions 110.6 / 103.8 (1.07x) 112.1 / 101.1 (1.11x)
compress en 1.5k / 3k / 6k 1.19x / 1.37x / 1.34x 1.24x / 1.44x / 1.38x
compress pl 1.5k / 3k / 6k 1.15x / 1.33x / 1.32x 1.19x / 1.37x / 1.33x

Every probability bit-identical to main (dense, cascade and default threshold; 679 cascade readouts across the 10
cases). Below CASCADE_TOKENS (5-20 questions) the default runs the dense pass, as before.

Not measured: an H100. The change removes host work, which is what an H100 exposes most, so I expect mini's
40-question requests to move from 0.90x toward the A100's 1.11x, but I could not rent one within my budget. Could you
rerun your 40-question comparison? If mini is still slower there, a higher threshold for small models on Hopper would
be the fallback; on the A100 the cascade now wins from 10 questions on, so I left CASCADE_TOKENS as it is.

Tests

  • New test_fused_merge_gives_the_merge_bit_for_bit (tests/test_cascade_cuda.py): the cascade with the fused
    merge equals the op-by-op merge bit for bit, for rows without and with padding. The existing tests compare _varlen
    with the attention written out and the cascade with the dense masked attention; all 3 pass on the A100.
  • The direct op against varlen_attn (causal and with per-sequence key counts): output and log-sum-exp equal.
  • tests/ (without test_gguf.py): CPU 754 passed, 82 skipped (on 2.4.1).

Summary by Sourcery

Reduce CUDA cascade host overhead and improve pass-2 performance without changing outputs.

Enhancements:

  • Reduce host overhead in the CUDA cascade by fusing per-layer attention merging and invoking FlashAttention directly.
  • Preserve existing cascade behavior and bit-for-bit output while retaining the unfused path when compilation or Triton is unavailable.

Documentation:

  • Document the CUDA cascade performance improvements and 2.4.2 release changes.

Tests:

  • Add CUDA coverage verifying fused and unfused cascade merges are bit-for-bit identical for padded and unpadded layouts.

@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR removes host-side overhead from CUDA cascade pass 2 by directly invoking ATen FlashAttention and conditionally compiling the attention merge into one warmed-up kernel per layer, while preserving the existing fallback path and validating bit-for-bit output equivalence.

Sequence diagram for the optimized CUDA cascade pass 2

sequenceDiagram
    participant Backend as GraphBackend
    participant Cascade as _cascade_varlen
    participant Flash as ATen FlashAttention
    participant Merge as _merge_fused
    participant GPU as CUDA kernels

    Backend->>Backend: _warm_cascade()
    Backend->>Merge: torch.compile(_merge_attention)
    Backend->>Cascade: _forward_cascade(..., tree.fused=True)
    Cascade->>Flash: _flash_attention_forward(root and branch)
    Flash->>GPU: Launch attention kernels
    Cascade->>Merge: _merge_fused(o_r, l_r, o_b, l_b)
    Merge->>GPU: Launch one fused merge kernel per layer
    GPU-->>Backend: Bit-identical cascade output
Loading

Flow diagram for conditional fused merge selection

flowchart TD
    A[Cascade pass 2] --> B{GraphBackend compile enabled and Triton available?}
    B -->|Yes| C[Set fuse_merge=True]
    C --> D[_warm_cascade compiles both cascade layouts]
    D --> E[_varlen_tree carries fused=True]
    E --> F[_cascade_varlen calls _merge_fused]
    F --> G[One fused merge kernel per layer]
    B -->|No| H[Keep fuse_merge=False]
    H --> I[_cascade_varlen calls _merge_attention]
    I --> J[Existing operation-by-operation merge]
Loading

File-Level Changes

Change Details Files
Reduce CPU launch overhead in the CUDA cascade's uncompiled pass 2.
  • Replace the Python-level varlen attention wrapper with a direct call to ATen's FlashAttention forward operator, preserving causal, grouped-query, sequence-length, and log-sum-exp behavior.
  • Add a cached, dynamically compiled full-graph merge that fuses the attention-result merge into one kernel when compilation and Triton are available.
  • Propagate the fused-merge selection through cascade tree metadata and warm both padded and unpadded layouts during backend startup to avoid request-time compilation.
  • Retain the operation-by-operation merge for non-compiling or non-Triton backends.
basal/engine.py
Document the CUDA cascade performance improvement and compatibility behavior.
  • Record the reduced kernel count and A100 benchmark improvements for mini and 4.5B models.
  • Document that fast-nocompile retains the unfused merge and that outputs remain bit-identical.
docs/WHATS_NEW.md
Add CUDA coverage for exact equivalence of fused and unfused cascade merges.
  • Compare fused and operation-by-operation cascade outputs bit-for-bit for unpadded and padded tree layouts.
  • Exercise both full and scattered branch-output paths used by the cascade.
tests/test_cascade_cuda.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

Butterski added a commit to Butterski/basal that referenced this pull request Oct 23, 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 2 issues

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

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="1296" />
<code_context>
                                                              if self.shared else []))
             if self.gemma is not None and self.flex and self.shared:
                 self._warm_pass2(n)
+        if self.shared and self.fuse_merge and self._cascade_why is None:
+            self._warm_cascade()
+
</code_context>
<issue_to_address>
**First cascade request incurs compilation latency**

When the backend is created with `warm=False` and compilation enabled, then a request takes the fused cascade path, `warm()` skips `_warm_cascade()`, so `_merge_fused()` compiles lazily on the first cascade request and adds compilation latency to that request.

Compile the fused merge before serving the first fused cascade request, including when `warm=False`.

Also at `basal/engine.py:766`, `basal/engine.py:1300`.
</issue_to_address>

### Comment 2
<location path="tests/test_cascade_cuda.py" line_range="94" />
<code_context>
+        k, v = (torch.randn(2, HKV, S, D, device="cuda", dtype=torch.bfloat16, generator=g) for _ in "kv")
+        kp, vp = (torch.randn(2, HKV, Lk, D, device="cuda", dtype=torch.bfloat16, generator=g) for _ in "kv")
+        op_by_op = _cascade_varlen(q, k, v, kp, vp, tree, D ** -0.5)
+        fused = _cascade_varlen(q, k, v, kp, vp, tree._replace(fused=True), D ** -0.5)
+        assert tree.full == (seg is full) and torch.equal(fused, op_by_op)
</code_context>
<issue_to_address>
**CUDA test requires Triton**

When CUDA and FlashAttention are available but Triton is not installed, `test_fused_merge_gives_the_merge_bit_for_bit` forces `fused=True` at this call, so `_merge_fused()` invokes `torch.compile` even when Triton is unavailable; the test errors instead of skipping although production disables fusion in that environment.

Skip this test when Triton is unavailable, or restrict it to environments where the fused path is enabled.
</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_cascade_cuda.py Resolved
Butterski added a commit to Butterski/basal that referenced this pull request Oct 23, 2026
@Butterski
Butterski force-pushed the perf/cascade-launches branch from a3d7b8f to 69a9846 Compare October 23, 2026 11:00
_cascade_varlen merged the root and branch attentions with ~15 small
kernels per layer (log-sum-exp, weights, casts, products, guards, sum,
cast back), launched one by one in the uncompiled pass 2. A GraphBackend
that compiles (with Triton) now runs _merge_attention compiled
(_merge_fused, dynamic shapes), compiled at start-up (_warm_cascade);
fast-nocompile and torch without Triton keep the merge op by op.
…gh varlen_attn

varlen_attn wraps torch.ops.aten._flash_attention_forward in a Python
custom op and allocates a random-number state on every call; the
cascade called it twice per layer of an uncompiled pass 2. The same op
with the arguments varlen_attn passes (its cuDNN path is off in torch).
@rkinas

rkinas commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Thank you, Miłosz! This is merged into the basal 2.5 release branch with your commits as you wrote them, and your WHATS_NEW entry is in the 2.5 section. Our H100 rerun: 3,720 of 3,720 readouts bit-identical, and 40- / 20-question requests over one state 5% / 10% faster. The PR will close when 2.5 is published on main.

@rkinas
rkinas merged commit f156371 into rkinas:main Nov 2, 2026
1 check passed
rkinas added a commit that referenced this pull request Nov 2, 2026
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