Repository navigation
perf(mps): the CPU branch pass without dense masks (cascade attention), the state once per request - #34
Conversation
…), 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.
Reviewer's GuideIntroduces 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 rootsequenceDiagram
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
Flow diagram for CPU cascade attention planning and mergeflowchart 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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>…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).
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).
… op; WHATS_NEW #34 with the core count
|
Thank you, Milosz. This is careful work. The log-sum-exp merge is the standard one, We merged it on top of 2.3.2 (only WHATS_NEW conflicted; your entry now sits under 2.3.3) and checked it:
We added one small commit on top: It is in basal 2.3.3: https://github.com/rkinas/basal/releases/tag/v2.3.3. Thank you! |
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).
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).
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).
Problem
On the CPU (
--mode mps --device cpu, #26) a unit longer thanLENS[-1]runs through_tree_cache: pass 1 computesthe 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.updateconcatenates the state's keys / values with the branch tokens' (and keeps them:use_cache=True),and
repeat_kvrepeats them for every query head;[N, P + N](N tokens below the state, P the state), built per call, its[N, P]part all zeros;_oversizesplits units with more thanBRANCH_TOKENS(8,192) tokens below thestate, 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:
(FlashAttention's own tile merge; the same as FlashInfer's
merge_stateor xFormers'merge_attentions). Only thesummation order changes.
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 pickson the CPU) returns the log-sum-exp.
(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._cascaderuns pass 2 like this in parts of whole top-level subtrees (each sees only the state anditself) of at most
BRANCH_TOKENStokens, all over the one state;MPSBackend._oversizeon the CPU splits a unit onlywhen its prompts share no root or one top-level subtree alone holds more than
BRANCH_TOKENStokens (its sharedblock then becomes the root of a smaller unit). Pass 2 switches the model to
basal_attention(basal_tree) for itsown forwards only.
cascade_ok: the Llama-based basal-2.0 models). Modelswith 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-tokenstate (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:Pass-2 attention alone, the 40-question pack, per layer: 1.79 -> 0.77 s (min of 5, a separate microbenchmark).
Tests
test_mps_cpu_branch_pass_cascade_root_once(tests/test_engine.py): 6 query heads per key / value head, fourquestions in two option orders, a duplicate prompt and a prompt that ends at the state;
BRANCH_TOKENSsmall enoughthat 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 overBRANCH_TOKENSon its own is splitoff (answers equal to prompts alone), and
_block_plan's padded pairs stay within its bound (many one-token blocksnext 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 awindow, Gemma 4 and Qwen3.5 (linear attention) do not.
test_mps_backend_on_cpu_equals_separatenow runs through the cascade as well.tests/(withouttest_gguf.py), rebased on 2.3.1 (621bc57): 665 passed, 81 skipped.Notes
aten); its schema is the same in torch 2.11 and 2.13. On a row whose keys are allmasked it returns lse 0, not -inf, so the masks use
finfo.minand_block_plangives every row a key._tree_hiddenwithout a graph,_long_hidden) withtorch.nn.attention.varlen.varlen_attn(return_aux=AuxRequest(lse=True),seqused_k); that needs a GPU to measureand is a separate PR.