Skip to content

perf(mps): the CPU branch pass without dense masks (cascade attention), the state once per request - #34

Merged
rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/cascade-cpu-pass2
Oct 22, 2026
Merged

rkinas merged 3 commits into
rkinas:mainfrom
Butterski:perf/cascade-cpu-pass2

Conversation

@Butterski

@Butterski Butterski commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On the CPU (--mode mps --device cpu, #26) a unit longer than LENS[-1] runs through _tree_cache: pass 1 computes
the state (the root) into a transformers DynamicCache, pass 2 runs every token below it as one row over that cache.
Pass 2 today, per layer:

  • DynamicLayer.update concatenates the state's keys / values with the branch tokens' (and keeps them: use_cache=True),
    and repeat_kv repeats them for every query head;
  • the mask is [N, P + N] (N tokens below the state, P the state), built per call, its [N, P] part all zeros;
  • because these grow with N x (P + N), _oversize splits units with more than BRANCH_TOKENS (8,192) tokens below the
    state, and every part computes the state again.

Change

Attention over the union of two disjoint key sets is the two partial attentions merged by their log-sum-exp:

$$\mathrm{lse}=\log(e^{\mathrm{lse}_P}+e^{\mathrm{lse}_B}),\qquad o=e^{\mathrm{lse}_P-\mathrm{lse}},o_P+e^{\mathrm{lse}_B-\mathrm{lse}},o_B$$

(FlashAttention's own tile merge; the same as FlashInfer's merge_state or xFormers' merge_attentions). Only the
summation order changes.

  • State part: every token below the state sees every state key, so no mask; with no mask the H / Hkv query heads of a
    key / value head are folded into the query length, so the cache's keys / values are read as they are (no copy, no
    repeat). SDPA's CPU flash kernel (torch.ops.aten._scaled_dot_product_flash_attention_for_cpu, the kernel SDPA picks
    on the CPU) returns the log-sum-exp.
  • Branch part: a token sees only its trie block's ancestors below the state and its own block, so per block: keys =
    (ancestors' tokens, own tokens), causal aligned at the end; blocks of similar shape batched with bounded padding
    (_block_plan). On compress requests this is 1.4-2.7% of the N x N pairs.
  • GraphBackend._cascade runs pass 2 like this in parts of whole top-level subtrees (each sees only the state and
    itself) of at most BRANCH_TOKENS tokens, all over the one state; MPSBackend._oversize on the CPU splits a unit only
    when its prompts share no root or one top-level subtree alone holds more than BRANCH_TOKENS tokens (its shared
    block then becomes the root of a smaller unit). Pass 2 switches the model to basal_attention (basal_tree) for its
    own forwards only.
  • Only for attention-only models without a sliding window (cascade_ok: the Llama-based basal-2.0 models). Models
    with sliding-window or linear-attention layers, Apple MPS and the CUDA early-exit backend keep today's dense path.

Measurements

basal-2.0-mini, --dtype float32 (MPSBackend(device="cpu")), 6 threads, idle 6-core Zen 2; one request: a 3,278-token
state (text from docs/) with N compress-style questions ("does this passage hold information needed to answer ..."),
main (634b2cd, before 2.3.1; 2.3.1 does not change this CPU path) vs this branch, one run each:

questions units (main -> branch) tokens computed wall peak RSS above the loaded model same top answer max |Δp|
40 1 -> 1 8,959 -> 8,959 105.3 -> 91.5 s (1.15x) 1,594 -> 1,093 MiB 40 / 40 8.7e-6
120 3 -> 1 26,247 -> 19,631 313.0 -> 206.6 s (1.51x) 2,269 -> 1,520 MiB 120 / 120 7.5e-6

Pass-2 attention alone, the 40-question pack, per layer: 1.79 -> 0.77 s (min of 5, a separate microbenchmark).

Tests

  • New test_mps_cpu_branch_pass_cascade_root_once (tests/test_engine.py): 6 query heads per key / value head, four
    questions in two option orders, a duplicate prompt and a prompt that ends at the state; BRANCH_TOKENS small enough
    that the branch pass runs in two parts; the request stays one unit and every readout equals its prompt run alone
    (fp32, 1e-5). Replacing the merge by the state part alone moves a probability by 1e-2, so the test catches a broken
    merge; bf16 stays within 5e-4 of bf16 prompts run alone.
  • test_mps_cpu_cascade_large_question_split_and_padding_bound: a question over BRANCH_TOKENS on its own is split
    off (answers equal to prompts alone), and _block_plan's padded pairs stay within its bound (many one-token blocks
    next to a long one: 1.0x the real pairs; rounding batches up to multiples of 16, as first written, gave 17x).
  • test_cascade_only_for_attention_only_models: Llama and a window-less Mistral use the cascade; Mistral with a
    window, Gemma 4 and Qwen3.5 (linear attention) do not.
  • perf(mps): run the packed engine on the CPU (--mode mps --device cpu); same answers #26's test_mps_backend_on_cpu_equals_separate now runs through the cascade as well.
  • tests/ (without test_gguf.py), rebased on 2.3.1 (621bc57): 665 passed, 81 skipped.

Notes

  • The CPU flash op is private (aten); its schema is the same in torch 2.11 and 2.13. On a row whose keys are all
    masked it returns lse 0, not -inf, so the masks use finfo.min and _block_plan gives every row a key.
  • The same split applies to the GPU paths (_tree_hidden without a graph, _long_hidden) with
    torch.nn.attention.varlen.varlen_attn (return_aux=AuxRequest(lse=True), seqused_k); that needs a GPU to measure
    and is a separate PR.

…), the state once per request

On the CPU (--mode mps --device cpu) a unit longer than the largest length
runs in two passes over a transformers KV cache; the branch pass
concatenated the state's keys / values with the branch tokens' in every
layer, repeated the KV heads and attended with an [N, P + N] mask, and
units with more than BRANCH_TOKENS tokens below the state were split,
each part computing the state again.

The branch pass now attends to the state's keys / values as they are (no
mask; grouped-query heads folded into the query length) and, per trie
block, to the block's ancestors below the state (causal at the end), and
merges the two by log-sum-exp: the softmax over all keys, summed in
another order. Nothing grows with N x P or N x N, so a unit is split only
when its prompts share no root; the branch pass runs in parts of whole
top-level subtrees over the one state. Apple MPS and the CUDA early-exit
backend keep the dense path.

basal-2.0-mini fp32, 6 threads, a 3,278-token state: 40 questions 105.3 ->
91.5 s, 120 questions 313.0 -> 206.6 s (3 units -> 1), peak RSS -501 /
-749 MiB, 160/160 same top answers, max |dp| 8.7e-6.
@sourcery-ai

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a CPU-specific cascade attention implementation for branched long-state requests: root keys and values are attended without copying, branch-local attention is planned in bounded trie blocks, and the two results are merged by log-sum-exp. Shared-root requests now reuse the root across branch parts, reducing dense-mask overhead, memory use, and repeated state computation while preserving existing dense paths on other devices.

Sequence diagram for CPU cascade attention over a shared root

sequenceDiagram
    participant Backend as MPSBackend CPU
    participant Cache as DynamicCache
    participant Model as Transformer model
    participant Attention as basal_attention
    participant Flash as CPU flash attention

    Backend->>Model: _tree_cache(pack)
    Model-->>Cache: Compute root keys and values once
    Backend->>Backend: _cascade(toks, pos, seg, parents, cache)
    loop Bounded top-level subtree parts
        Backend->>Model: Forward branch tokens with basal_tree
        Model->>Attention: basal_attention(..., basal_prefix, basal_tree)
        Attention->>Flash: _attention_lse(query, root keys, root values)
        Flash-->>Attention: State output and lse
        Attention->>Flash: _branch_attention(..., _block_plan)
        Flash-->>Attention: Branch output and lse
        Attention->>Attention: _merge_attention(state, branch)
        Attention-->>Model: Merged branch output
    end
    Model-->>Backend: Branch hidden states and readouts
Loading

Flow diagram for CPU cascade attention planning and merge

flowchart TD
    A[Shared-root branched request] --> B[Compute root with KV cache once]
    B --> C{CPU device?}
    C -->|No| D[Use existing dense branch path]
    C -->|Yes| E[_cascade splits whole top-level subtrees]
    E --> F[_block_plan groups trie blocks with bounded padding]
    F --> G[State attention over cached root keys and values]
    F --> H[Branch attention over ancestor and own block tokens]
    G --> I[_merge_attention by log-sum-exp]
    H --> I
    I --> J[Merged hidden states and readouts]
    C -->|Yes, no shared root| K[_oversize splits unit]
    K --> B
Loading

File-Level Changes

Change Details Files
Adds a CPU-only cascade attention path that computes root attention once and merges separate root and trie-branch attentions using log-sum-exp.
  • Uses the CPU flash-attention operator to return attention outputs and per-row log-sum-exp values without repeating grouped-query keys for unmasked root attention.
  • Builds bounded, shape-grouped trie block plans with aligned causal masks for branch-local attention.
  • Merges root and branch attention results in fp32, preserving the equivalent softmax over the combined key sets.
  • Routes CPU branch passes through the temporary basal SDPA implementation while retaining dense attention on MPS and CUDA paths.
basal/engine.py
Changes CPU long-unit splitting so shared-root requests remain a single unit and are processed in bounded subtree parts over one cached root.
  • Adds _cascade to process top-level subtree runs with BRANCH_TOKENS activation bounds.
  • Avoids recomputing the root unless prompts do not share a root.
  • Integrates cascade outputs into _tree_cache readouts.
basal/engine.py
Adds regression coverage for numerical equivalence and root reuse in the CPU cascade path.
  • Exercises grouped-query attention, nested branch blocks, duplicate prompts, root-ending prompts, and multi-part branch execution.
  • Verifies cascade readouts against separate prompt execution at fp32 tolerance.
  • Updates the existing CPU backend equivalence test to cover the cascade path.
tests/test_engine.py
Documents the CPU performance and memory improvements from eliminating dense branch masks and repeated root computation.
  • Records benchmark speedups, memory reductions, answer agreement, and probability deltas for long shared-state requests.
  • Adds a release note for the new CPU long-state behavior.
docs/WHATS_NEW.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

@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="483" />
<code_context>
         return _varlen_attention(query, key, value, basal_cu, scaling, module.layer_idx, basal_varlen), None
+    if basal_tree is not None:
+        k, v = basal_prefix[module.layer_idx]
+        o_p, l_p = _attention_lse(query, k, v, scaling)
+        o_b, l_b = _branch_attention(query, key, value, scaling, basal_tree)
+        return _merge_attention(o_p, l_p, o_b, l_b).transpose(1, 2).contiguous(), None
</code_context>
<issue_to_address>
**Sliding-window outputs differ**

When a long-path request uses a model with sliding-window attention and a branch query advances beyond the layer’s window, `basal_attention` calls `_attention_lse` on the entire prefix and `_branch_attention` with only the trie-causal mask, so both include expired keys outside the window. The cascade returns hidden states and readouts that differ from separate prompt forwards.

Apply the layer’s position-dependent sliding-window mask to both prefix and branch attention.
</issue_to_address>

### Comment 2
<location path="basal/engine.py" line_range="1804-1823" />
<code_context>
+        top = []  # the top-level subtree of every block (a block comes after its parent)
</code_context>
<issue_to_address>
**Hybrid branch state is lost**

When a CPU long request uses a model with linear-attention layers, `_cascade` extracts only `layer.keys` and `layer.values`, then runs branch forwards with `use_cache=False` and no `past_key_values`; linear-attention layers therefore lack the root’s recurrent state, causing a cache error or incorrect branch outputs.

Carry the root’s per-layer recurrent state into each branch forward, or keep hybrid models on the cache-aware dense path.
</issue_to_address>

### Comment 3
<location path="basal/engine.py" line_range="1812" />
<code_context>
+            if i == len(seg) or top[seg[i]] != top[seg[i - 1]]:
+                runs.append((a, i))
+                a = i
+        parts = [list(runs[0])]
+        for a, b in runs[1:]:
+            if b - parts[-1][0] > self.BRANCH_TOKENS:
</code_context>
<issue_to_address>
**Large subtrees remain unbounded**

When one top-level subtree contains more than `BRANCH_TOKENS` tokens, `_cascade` accepts an oversized first top-level subtree as one part, and `_block_plan` builds a dense per-block mask for it; a long shared question block therefore still creates quadratic attention work and mask memory, so the CPU branch pass can run out of memory.

Split oversized top-level subtrees into bounded causal chunks while preserving their ancestor keys, or otherwise avoid constructing a quadratic mask for a long block.

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

### Comment 4
<location path="basal/engine.py" line_range="560-564" />
<code_context>
+        if it is not None:
+            nxt = cur + [it]
+            m, k = max(len(q) for q, _ in nxt), max(len(q) + len(an) for q, an in nxt)
+            if not cur or len(nxt) * m * k <= waste * sum(len(q) * (len(q) + len(an)) for q, an in nxt):
+                cur = nxt
+                continue
+        m = -(-max(len(q) for q, _ in cur) // pad) * pad
+        k = -(-max(len(q) + len(an) for q, an in cur) // pad) * pad
+        qi = torch.full((len(cur), m), N, dtype=torch.long)
+        ki = torch.full((len(cur), k), N, dtype=torch.long)
</code_context>
<issue_to_address>
**Padding defeats batch bound**

When a part contains many short trie blocks, such as many one-token blocks, `_block_plan` groups blocks using unrounded `m` and `k`, then rounds both dimensions up to `pad`; many short blocks therefore form one batch whose actual padded query-key work greatly exceeds `waste` times the real work, slowing the CPU branch pass and inflating its temporary tensors.

Apply the waste bound to the rounded dimensions, and flush the batch when the padded pair count exceeds it.
</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 basal/engine.py Resolved
…question; padding within the bound

Review fixes for the CPU cascade branch pass:
- cascade_ok(config): models with sliding-window or linear-attention
  layers (Gemma 4, Mistral with a window, Qwen3.5) keep the dense pass over
  the transformers cache; the cascade needs every visible key to be in the
  root or the block's ancestors, and linear layers need their recurrent
  state. The basal-2.0 models are Llama: no change for them.
- MPSBackend._oversize on the CPU also splits a unit whose largest
  top-level subtree holds more than BRANCH_TOKENS tokens, so a long shared
  question block becomes the root of a smaller unit instead of one large
  branch part.
- _block_plan bounds the padded pairs it actually builds: batches are
  padded to their longest block, not rounded up to multiples of 16 (many
  one-token blocks: 17x the real pairs before, 1.0x now).
Butterski added a commit to Butterski/basal that referenced this pull request Oct 22, 2026
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).
@rkinas
rkinas merged commit 0d54e0f into rkinas:main Oct 22, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 22, 2026
@rkinas

rkinas commented Oct 22, 2026

Copy link
Copy Markdown
Owner

Thank you, Milosz. This is careful work. The log-sum-exp merge is the standard one, cascade_ok keeps sliding-window and linear-attention models on the dense pass, and 6bba998 answers all four Sourcery points with tests.

We merged it on top of 2.3.2 (only WHATS_NEW conflicted; your entry now sits under 2.3.3) and checked it:

  • Tests: 708 passed, 0 failed.
  • A random fuzz of the CPU branch pass on tiny Llama models (1 to 12 query heads per key / value head, nested option blocks, duplicates, prompts that end at or inside the state, a second root, BRANCH_TOKENS from 8 to 10,000): 4,305 readouts, max |Δp| 1.8e-7 against the prompts run alone. In bf16 the top answer matches the dense pass on 203 of 203.
  • basal-2.0-mini fp32 on a Xeon 8460Y+, 40 questions in two option orders over a ~3,350-token state: the same top answer on 1,608 of 1,608 (max |Δp| 3.9e-5, median 6e-7). At 8 threads 1.10x faster with about half the peak memory (1.84 to 0.97 GB). At 32 threads about the same speed (0.94-1.04x over three runs). 150 questions on one state: one unit instead of two, 1.24x faster, peak 2.04 to 1.64 GB.

We added one small commit on top: _attention_lse uses the private torch.ops.aten._scaled_dot_product_flash_attention_for_cpu, and basal pins only torch>=2.11, so cascade_ok now also checks that the op exists and keeps the dense pass without it. The WHATS_NEW entry now names the 6 cores of your numbers and adds our 32-thread result.

It is in basal 2.3.3: https://github.com/rkinas/basal/releases/tag/v2.3.3. Thank you!

Butterski added a commit to Butterski/basal that referenced this pull request Oct 22, 2026
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 added a commit to Butterski/basal that referenced this pull request Oct 22, 2026
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).
rkinas pushed a commit that referenced this pull request Oct 23, 2026
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 (#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).
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