Skip to content

perf(fast): the uncompiled pass 2 as a cascade on CUDA (compress and many-question requests without dense masks) - #39

Closed
Butterski wants to merge 3 commits into
rkinas:mainfrom
Butterski:perf/cascade-cuda-pass2
Closed

Butterski wants to merge 3 commits into
rkinas:mainfrom
Butterski:perf/cascade-cuda-pass2

Conversation

@Butterski

@Butterski Butterski commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

The GPU half of #34: the same cascade (root part + per-block branch part, #34's _merge_attention) for the CUDA graph
engine's pass 2 where it runs without a graph.

Problem

In the graph engine (--mode fast, Llama models) pass 2 of a branched unit runs without a CUDA graph when its rows
are longer than 256 tokens, it has more than 8 rows, or its root is longer than 3,072 tokens: every compress request
(one branch per sentence, thousands of tokens below the document) and requests with many questions. That pass
attends through basal_attention with basal_prefix, per layer:

  • torch.cat of the root's keys / values with the branch tokens', then transformers' repeat_kv (6 or 8 copies of
    every key head for SDPA with a mask);
  • an additive mask [B, 1, S, L + S] built per call, its root part all zeros;
  • SDPA's memory-efficient kernel computes every query-key pair of S x (L + S), although a branch token sees only the
    root and its own trie ancestors (1.4-2.7% of the S x S part on compress requests).

Change

basal/engine.py, Llama on CUDA with torch's varlen attention (torch_varlen_available, plus seqused_k), not
--lean, not Gemma 4 (_cascade_why). The model check is split out of cascade_ok as attention_only: the CUDA
path needs it but not the private CPU flash op that cascade_ok also checks since 2.3.3.

  • A pass 2 without a graph whose longest row has at least CASCADE_TOKENS = 1024 tokens runs as a cascade
    (_forward_cascade -> basal_attention with a _VarlenTree -> _cascade_varlen):
    • root part: one varlen_attn over the root key / value buffers pass 1 wrote, seqused_k = each row's root length
      (no mask, no concatenated or repeated keys);
    • branch part: one varlen_attn over, per trie block, its ancestors' and own tokens, causal from the end
      (_varlen_tree builds the index lists on the host from the same seg / parents as the dense mask);
    • merged by log-sum-exp (perf(mps): the CPU branch pass without dense masks (cascade attention), the state once per request #34's _merge_attention): the softmax over all keys, summed in another order. A padding
      token sees the root only, as in the dense mask.
  • The long lane (_long_hidden) uses it too.
  • Below the threshold, with pass-2 graphs, in fp32 (varlen needs bf16 / fp16) and on every other backend nothing
    changes; the dense path is bit-identical to main.

Measurements

RTX 4090, torch 2.13.0+cu130, basal-serve (fast, its defaults) on this branch; per request the pass 2 alternates
between dense (threshold off), cascade (threshold 0) and the default threshold (a research launcher that reads the
threshold from a file; not part of this PR), one client, median of 5 (mini) / 3 (4.5B) after a warm-up round. Compress
over synthetic case logs (one unit per ticket line, keep_ratio 0.3), multi-question requests over a 1.5k-token log:

request mini dense ms mini default speed-up 4.5B dense ms 4.5B default speed-up
compress, en 1.5k tokens (25 units) 169.6 141.4 1.20x 439.4 384.4 1.14x
compress, en 3k (52 units) 434.3 328.8 1.32x 1127.3 865.4 1.30x
compress, en 6k (103 units) 1142.7 881.2 1.30x 2915.6 2322.9 1.26x
compress, pl 1.5k (27 units) 162.5 137.5 1.18x 409.6 359.1 1.14x
compress, pl 3k (55 units) 401.7 304.7 1.32x 1028.0 814.1 1.26x
compress, pl 6k (109 units) 1053.7 863.8 1.22x 2728.1 2219.6 1.23x
5 questions (below the threshold) 49.1 48.6 1.01x 131.8 132.0 1.00x
10 questions (below) 60.0 59.4 1.01x 156.4 156.8 1.00x
20 questions 76.0 75.7 1.00x 189.1 189.3 1.00x
40 questions 110.9 103.8 1.07x 285.0 260.0 1.10x

With the cascade forced on 5-10 questions it is 0.98-1.02x (two small kernels and the merge against one small dense
call), hence the threshold.

A100 PCIe 40 GB (Ampere), the same runs, median of 3:

request mini dense ms mini default speed-up 4.5B dense ms 4.5B default speed-up
compress, en 1.5k 167.6 140.9 1.19x 434.5 369.4 1.18x
compress, en 3k 439.6 316.5 1.39x 1126.1 813.1 1.38x
compress, en 6k 1166.7 869.2 1.34x 2894.9 2152.7 1.34x
compress, pl 1.5k 156.5 135.8 1.15x 404.3 352.8 1.15x
compress, pl 3k 407.4 306.9 1.33x 1022.3 770.1 1.33x
compress, pl 6k 1064.1 810.1 1.31x 2608.2 1996.4 1.31x
5 questions (below the threshold) 49.5 49.0 1.01x 124.5 123.7 1.01x
40 questions 111.8 101.1 1.11x 290.7 267.3 1.09x

There the forced cascade costs 0.83-0.84x at 5 questions, so the threshold matters more. An H100 was not measured
(three rented hosts never finished loading the container).

Re-checked after the rebase on 2.3.3 (with #34, #35, #37), RTX 4060 Ti 16 GB, basal-2.0-mini, median of 3: compress
1.16-1.34x (en 3k: 1447 -> 1077 ms, en 6k: 3750 -> 2874 ms), 40 questions 1.10x (325 -> 293 ms), 5-20 questions as
dense (default threshold); the dense path bit-identical to main (47ae982) on all six compress requests.

GPU memory for the largest of these requests (compress en / pl 6k, 40 questions) on a fresh server, cascade first,
then dense (the allocator keeps its peak). Measured before #35 / #37 were merged; their savings are in the start-up
memory, the cascade's in the per-request part:

after start after the cascade requests after the dense requests
basal-2.0-mini 12,702 MiB 14,080 MiB (+1.4 GB) 16,600 MiB (+3.9 GB)
basal-2.0-4.5B 22,858 MiB 24,568 MiB (+1.7 GB) 26,628 MiB (+3.8 GB)

Answers: the dense path of this branch against upstream main (621bc57, and 47ae982 after the rebase) on the six
compress requests: every probability bit-identical. The cascade changes bf16 rounding only; against basal-2.0-mini in
fp32 (where every mode runs the dense fp32 pass) as the reference, over all ten requests (679 probabilities):

bf16 max |dp| vs fp32 mean |dp| vs fp32 decisions as fp32
dense (today) 4.4e-2 7.04e-3 6 / 10 requests
cascade 5.9e-2 6.88e-3 5 / 10 requests

The compress decisions are the top 30% of units, so near-ties at the cut flip with bf16 rounding in both: dense bf16
already keeps a different set than fp32 in 4 of the 6 compress requests.

Tests

  • New test_cascade_pass2_equals_separate (tests/test_engine16.py): the cascade path on the CPU with torch's varlen
    attention written out (ref_varlen): several units per forward with different root and branch lengths (padding,
    stale buffer keys past each root), nested option orders, readouts inside the root; every readout equals its prompt
    run alone (fp32, 1e-5), and below the threshold the dense pass runs. Dropping seqused_k, a non-causal branch part,
    missing ancestors or the root part alone each fail it.
  • New tests/test_cascade_cuda.py (CUDA sm80+): torch's varlen_attn against the attention written out (its
    log-sum-exp layout, causal aligned at the end, seqused_k), and _cascade_varlen against one masked SDPA call over
    cat(root, branch) with repeated heads (two rows, nested blocks, padding).
  • test_cascade_why: off on the CPU and with --lean; on CUDA it does not need the CPU flash op (with the gate on
    cascade_ok, a torch without that op would switch the CUDA cascade off; the test fails that way).
  • tests/ (without test_gguf.py), rebased on 2.3.3: CPU 703 passed, 83 skipped; RTX 4060 Ti 739 passed, 47 skipped
    (test_cascade_cuda.py 2 passed). Before the rebase (2.3.1 + perf(mps): the CPU branch pass without dense masks (cascade attention), the state once per request #34, the same pass-2 code): RTX 4090 and A100 703
    passed, 47 skipped each.

Summary by Sourcery

Speed up long uncompiled CUDA pass-2 requests by using a trie-aware varlen attention cascade instead of dense masked attention.

New Features:

  • Add a CUDA varlen-attention cascade for uncompiled pass-2 requests on supported Llama models, avoiding dense masks and repeated root keys.

Enhancements:

  • Automatically select the cascade for sufficiently long rows while preserving the existing dense path for short, unsupported, or non-CUDA cases.
  • Support cascade execution for long hidden-state requests and separate model capability checks from the CPU flash-attention requirement.

Documentation:

  • Document the CUDA pass-2 cascade, its performance improvements, memory reductions, and numerical behavior in the release notes.

Tests:

  • Add CPU and CUDA coverage validating varlen attention, trie ancestry handling, padding, per-row key counts, log-sum-exp merging, and fallback selection.

@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR optimizes graphless CUDA pass 2 for eligible Llama attention workloads by building host-side trie index lists and running separate root and ancestor-only branch varlen attention passes, merged with log-sum-exp instead of dense masked attention. The path is conservatively gated by backend, model, mode, dtype, torch API, and a 1,024-token threshold, preserving the existing dense implementation for unsupported or smaller workloads; focused CPU/CUDA tests cover numerical equivalence and fallback semantics.

Sequence diagram for CUDA cascade pass 2 attention

sequenceDiagram
    participant G as GraphBackend
    participant T as _varlen_tree
    participant M as Model
    participant V as varlen_attn
    participant L as _merge_attention
    G->>T: Build trie index lists from seg and parents
    G->>M: _forward_cascade(ids, pos, prefix, tree)
    M->>V: Root attention with seqused_k
    V-->>M: Root output and log-sum-exp
    M->>V: Branch attention over ancestors and own tokens
    V-->>M: Branch output and log-sum-exp
    M->>L: Merge root and branch results
    L-->>G: Pass 2 hidden states
Loading

Flow diagram for graphless CUDA pass 2 cascade selection

flowchart TD
    A[Graphless pass 2] --> B{Rows reach 1024 tokens?}
    B -- No --> D[Dense masked attention]
    B -- Yes --> C{CUDA Llama varlen support?
Not lean or Gemma}
    C -- No --> D
    C -- Yes --> E[_varlen_tree builds trie indices]
    E --> F[_forward_cascade]
    F --> G[_cascade_varlen]
    G --> H[Root and ancestor-only attention]
    H --> I[Log-sum-exp merge]
Loading

File-Level Changes

Change Details Files
Adds a CUDA varlen-attention cascade for eligible uncompiled pass-2 forwards, replacing dense masked attention with separate root and trie-branch attention passes merged by log-sum-exp.
  • Introduces _VarlenTree and host-side tree index construction from segment and parent metadata.
  • Uses varlen_attn with grouped-query support, per-row seqused_k, and end-aligned causal masking for branch blocks.
  • Merges root and branch outputs while preserving padding, root-length, ancestor, and stale-buffer semantics.
  • Routes graphless pass 2 and long-lane execution through the cascade only when the row length meets the 1,024-token threshold and CUDA/Llama/dtype/runtime gates pass; otherwise retains the dense path.
basal/engine.py
Separates model eligibility from the CPU flash-attention capability and adds runtime gating for the CUDA implementation.
  • Adds attention_only for full-attention, non-sliding-window models.
  • Keeps the CPU cascade's private flash-op requirement in cascade_ok while allowing CUDA to depend only on torch varlen attention and seqused_k.
  • Excludes Gemma, lean mode, unsupported backends, incompatible dtypes, and torch versions lacking required varlen features.
basal/engine.py
Documents the CUDA optimization, performance characteristics, memory savings, and numerical behavior.
  • Records supported request types, threshold behavior, measured speedups, and reduced GPU memory use.
  • Notes that the dense path remains unchanged and bit-identical, while the cascade differs within expected bf16 rounding.
docs/WHATS_NEW.md
Adds CPU and CUDA correctness coverage for varlen attention, cascade masking, routing, and fallback behavior.
  • Compares the varlen wrapper with an explicit attention reference, including grouped-query heads, causal alignment, and seqused_k.
  • Validates cascade output against dense masked SDPA across nested blocks, differing root lengths, and padding.
  • Checks separate prompt equivalence, readouts, stale keys, threshold fallback, and CUDA eligibility gates.
tests/test_cascade_cuda.py
tests/test_engine16.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 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 2 issues

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

## Individual Comments

### Comment 1
<location path="docs/WHATS_NEW.md" line_range="3-8" />
<code_context>
+# What is new in basal 2.3.4 (not released yet)
+
+- **Compress and many-question requests faster on CUDA** (`--mode fast`, the Llama-based basal-2.0 models): a pass 2
+  without a CUDA graph whose rows hold 1,024 or more tokens (every `compress` request, dozens of questions over a state)
+  attends to the state's keys and values as pass 1 wrote them and, per trie block, to its own ancestors (torch's
+  varlen attention), merged by log-sum-exp, instead of one masked call over concatenated and repeated keys. Compress
+  over 1.5k-6k-token documents 1.14-1.39x faster (basal-2.0-mini and basal-2.0-4.5B, RTX 4090 and A100), 40 questions
+  1.07-1.11x, 2.1-2.5 GB less GPU memory for the largest of them; smaller requests run as before, bit-identical.
+  Answers within bf16 rounding: against fp32, mean |Δp| 6.9e-3 (the dense bf16 pass: 7.0e-3).
+  Contributed by Milosz (@Butterski).
</code_context>
<issue_to_address>
**Cascade availability is overstated**

When a CUDA installation lacks supported varlen attention or `seqused_k`, `GraphBackend._cascade_why` disables the cascade when the installed torch lacks supported varlen attention or `seqused_k`, and otherwise-ineligible configurations use the dense pass. The note's claim that every compress request gets the cascade-led speedup therefore does not hold for all supported CUDA installations.

Qualify the release note's availability and speedup claims with the varlen-attention, `seqused_k`, and dtype requirements.
</issue_to_address>

### Comment 2
<location path="basal/engine.py" line_range="746-758" />
<code_context>
+def _cascade_varlen(q, k, v, kp, vp, tree, scale):
</code_context>
<issue_to_address>
**Pass-two documentation omits cascade**

When pass 2 is cascade-eligible on CUDA, `GraphBackend`'s class docstring still says pass 2 uses a block mask and runs as a normal forward for other shapes (`basal/engine.py:888-894`). On cascade-eligible CUDA requests, `_cascade_varlen` instead runs separate root and branch varlen attentions without that mask, so the documented pass-two behavior no longer matches the code.

Update the `GraphBackend` class docstring to describe the cascade path and its eligibility alongside the graph and dense paths.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread docs/WHATS_NEW.md Resolved
Comment thread basal/engine.py Resolved
A pass 2 without a CUDA graph whose longest row has CASCADE_TOKENS (1024)
or more tokens (every compress request, dozens of questions) runs as a
cascade on Llama models with torch varlen attention: one varlen_attn over
the root key / value buffers pass 1 wrote (seqused_k = each row's root
length; no mask, no concatenated or repeated keys), one over each trie
block's ancestors and own tokens (causal from the end), merged by
log-sum-exp (rkinas#34's _merge_attention). Also the long lane. Below the
threshold, in fp32, with --lean and on Gemma 4 nothing changes.

RTX 4090 / A100, basal-2.0-mini and 4.5B: compress over 1.5k-6k-token
documents 1.14-1.39x faster, 40 questions 1.07-1.11x, 2.1-2.5 GB less GPU
memory for the largest requests; the dense path bit-identical to main;
against fp32 the cascade's mean |dp| 6.9e-3 (dense bf16 7.0e-3).
@Butterski
Butterski force-pushed the perf/cascade-cuda-pass2 branch from 5cb8d9c to 8faed53 Compare October 22, 2026 22:58
rkinas pushed a commit that referenced this pull request Oct 23, 2026
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. #39 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 with your authorship (aa03a84, 6bb06b5, 7920ee9), so GitHub shows this PR as closed rather than merged.

What we measured on an H100 with torch 2.13:

  • Answers: on the usual paths every probability is the same as in 2.3.4 (basal-2.0-mini default and compact, 4.5B compact: 4,120 readouts). On compress and 40-question requests the top answer is the same on all 240 decisions per model (max |dp| 0.031).
  • Speed: compress over 1.5k-6k-token documents is 1.18-1.30x faster on mini and 1.27-1.49x on the 4.5B. 40 questions: 0.90x on mini and 1.11x on the 4.5B. With 4 clients, 6.9 -> 8.3 and 3.2 -> 4.6 requests per second. The release gate reproduced these.
  • A small addition from us: the CUDA tests also skip where varlen_attn has no seqused_k, as _cascade_why does (53dc29d).
  • Worth a look later: mini's 40-question requests sit just above CASCADE_TOKENS, and the cascade is about 10% slower there; a higher threshold for the small model might avoid that.

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