Repository navigation
perf(fast): less host work in the CUDA cascade (one fused merge kernel per layer, FlashAttention's op called directly) - #44
Merged
Conversation
Reviewer's GuideThis 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 2sequenceDiagram
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
Flow diagram for conditional fused merge selectionflowchart 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]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Butterski
added a commit
to Butterski/basal
that referenced
this pull request
Oct 23, 2026
There was a problem hiding this comment.
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>
Butterski
added a commit
to Butterski/basal
that referenced
this pull request
Oct 23, 2026
Butterski
force-pushed
the
perf/cascade-launches
branch
from
October 23, 2026 11:00
a3d7b8f to
69a9846
Compare
_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).
Butterski
force-pushed
the
perf/cascade-launches
branch
from
October 23, 2026 11:36
69a9846 to
c0a6a8a
Compare
This was referenced Oct 26, 2026
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_attentionran as ~15 small kernels (log-sum-exp, the two weights, casts, products, guards, sum, cast back).varlen_attn, called twice per layer, wrapstorch.ops.aten._flash_attention_forwardin a Python custom op andallocates 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_attentioncompiled (dynamic shapes,fullgraph), one kernel per layer, for aGraphBackendthat compiles and has Triton (fuse_merge;fast-nocompileand torch without Triton keep the mergeop 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_cascadecompiles it at start-up for both layouts a cascade passes (rows withoutand with padding), so no request compiles it.
_VarlenTree.fusedcarries the choice to_cascade_varlen._varlencallstorch.ops.aten._flash_attention_forwardwith the argumentsvarlen_attnpasses (its cuDNN pathis off in torch 2.13:
_should_use_cudnnreturns False): the same kernel, output and log-sum-exp bit-identical.The dense pass, the CPU cascade (#34) and
CASCADE_TOKENSare 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.0bit-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:End to end,
basal-servewith basal-2.0-mini, one client, each request with the dense pass, the cascade and thedefault threshold in turn (
cascade_bench.py, 7 repetitions, median ms):main: dense / cascadeEvery probability bit-identical to
main(dense, cascade and default threshold; 679 cascade readouts across the 10cases). 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_TOKENSas it is.Tests
test_fused_merge_gives_the_merge_bit_for_bit(tests/test_cascade_cuda.py): the cascade with the fusedmerge equals the op-by-op merge bit for bit, for rows without and with padding. The existing tests compare
_varlenwith the attention written out and the cascade with the dense masked attention; all 3 pass on the A100.
varlen_attn(causal and with per-sequence key counts): output and log-sum-exp equal.tests/(withouttest_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:
Documentation:
Tests: