Skip to content

perf(graph): compact rows on any sm80+ GPU through torch varlen attention (--batches compact) - #29

Merged
rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/compact-torch-varlen
Oct 21, 2026
Merged

rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/compact-torch-varlen

Conversation

@Butterski

@Butterski Butterski commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Compact rows (single prompts packed back to back into one row, graphs per token count, no padding to bucket lengths or
row counts; v2.0.0: +19% decisions/s at 16 clients on an H100) and the template prefix that builds on them run only
with FlashAttention 3: self.compact = ... and self.attn == "fa3", and _varlen_attention calls
flash_attn_interface. Every other NVIDIA GPU (A100, L4 / L40S, RTX 30 / 40 / 50, RTX PRO 6000, B200) runs padded
graphs only.

torch 2.13 (the version in uv.lock) ships torch.nn.attention.varlen.varlen_attn: torch's built-in FlashAttention 2
on packed sequences, with GQA (enable_gqa) and a causal window (window_size=(-1, 0)), registered as a custom op with
a fake implementation, so torch.compile traces it without a graph break.

Change

  • _varlen_attention(..., impl): with impl == "torch varlen", the same call through varlen_attn (same packed
    layout, same cu / template-prefix gather), else FlashAttention 3 as before. Each backend keeps its choice in
    compact_kernel and passes it through the forward (basal_varlen, next to basal_cu), so backends in one process
    do not share it.
  • GraphBackend.__init__: compact rows with FA3 as before; with --batches compact on another GPU, for Llama models,
    through varlen_attn when torch_varlen_available(dtype) (CUDA, sm80+, bf16 / fp16, a torch with enable_gqa).
    --batches auto is unchanged (compact only where FA3 runs). A --batches compact that no kernel can serve is
    refused with the reason before the tokenizer and the weights load.
  • The start-up line names the compact kernel and the template prefix:
    mode fast attention fa2 compact rows torch varlen template prefix ready in ....
  • Docs: --batches help, SERVING.md, INSTALL.md, WHATS_NEW.md.

Measurements

RTX 4060 Ti 16 GB (sm_89, also driving a Windows desktop), WSL2 Ubuntu 24.04, torch 2.13.0+cu130, basal-2.0-mini,
--mode fast, basal-loadtest at 16 clients. A = --batches default (today), B = --batches compact --template-prefix off, C = --batches compact. One session, the same baseline GPU memory (~1 GB) for all three:

A B C
single questions, decisions/s (2 runs) 66.8 (64.3-69.3) 69.6 (68.8-70.5) 109.4 (108.0-110.7), +64%
single questions, p50 / p95 ms 20.2 / 22.6 24.9 / 34.7 16.9 / 26.8
five questions over ~1.5k tokens, requests/s (3 seeds) 5.64 (5.57-5.67) 5.19 (5.03-5.32) 5.33 (5.21-5.43)
GPU memory after ready / peak (whole card) 13.4 / 14.0 GB 15.8 / 16.1 GB 15.8 / 16.1 GB
  • Answers (44 bundled simple items + 5 complex.jsonl requests, 58 probability vectors): B vs A and C vs A the same
    top answer on 58 of 58, max |Δp| 0.0064 (B) and 0.0248 (C).
  • basal-loadtest --determinism 50 (concurrency 32, no --deterministic): A 1/50 identical, max |Δp| 0.024, 0 flips;
    C 1/50, 0.030, 1 flip. Under load the default path is no more repeatable than compact rows; --deterministic stays
    the setting for repeatable answers.
  • The five-question requests do not use compact rows (branched units take the two-pass tree path, as in A;
    _forwards sends only one-block units to compact rows), so their slowdown is not the kernel: the compact graphs take
    about 2.4 GB more, B and C filled the 16 GB card, and Windows counters showed 3.3-3.5 GB of the WSL VM in shared
    system memory during C's five-question runs (WDDM pages instead of failing). On a card with headroom this should
    not appear [not measured].
  • Tests: tests/test_compact_varlen.py on the RTX 4060 Ti: 2 passed (compact rows equal separate SDPA prompts with
    GQA and empty trailing prompts; the template prefix equals a bottom-right causal reference), 1 skipped (FA3 vs torch,
    Hopper only). Full suite there: 645 passed; one failure that also fails on main on that GPU (below). These GPU
    runs are of c0359ef; the review fix after it (2defa6e) changes how the kernel choice reaches _varlen_attention, not
    the kernel call, and adds test_unsupported_compact_refused_before_loading (CPU: suite 616 passed, 76 skipped).

Not measured: Ampere, Blackwell, larger models (basal-2.0-4.5B's graph engine does not fit 16 GB with or without
compact rows: it never finished warm-up), Hopper (unchanged path).

Notes

  • Why opt-in: on a 16 GB card the extra compact graphs leave little room; whether auto should turn this on where
    memory allows is your call.
  • Unrelated, found on the same GPU: tests/test_lean.py::test_flex_with_lean_on_refused_before_loading fails on any
    CUDA GPU without FlashAttention 3, also on main: main() calls default_mode(), which resolves the model to check
    for Gemma 4, before the --lean / --tree check, and the test's resolve stub fails on any call.
  • Limits of my testing: one 16 GB consumer card is all the GPU I have right now, so larger models, Ampere / Blackwell,
    a card with memory headroom and the next step (fewer compact graphs, to cut the 2.4 GB) are not covered here. I'll
    keep working on what I can measure; numbers from a bigger GPU would be welcome.

…tion (--batches compact)

Compact rows (prompts packed back to back, no padding to graph lengths
and row counts) ran only with FlashAttention 3, i.e. on Hopper. torch
2.13 ships torch.nn.attention.varlen.varlen_attn (its built-in
FlashAttention 2 on packed sequences, with GQA and a causal window), a
custom op that compiles without a graph break. With --batches compact on
other GPUs, Llama models now run compact rows (and the template prefix)
through it; --batches auto keeps compact on Hopper only.

WIP: kernel tests need CUDA; GPU numbers pending.
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR extends opt-in compact-row batching from Hopper-only FlashAttention 3 to PyTorch varlen attention on compatible sm80+ CUDA GPUs. It adds capability-gated backend selection with explicit refusal messages, preserves the existing auto behavior and FA3 path, reports the selected kernel at startup, documents the memory/performance trade-offs, and adds CUDA correctness tests for packed prompts and template-prefix attention.

Sequence diagram for packed-row varlen attention

sequenceDiagram
    participant Backend as GraphBackend
    participant Forward as Compiled forward
    participant Attention as _varlen_attention
    participant Torch as torch varlen_attn
    Backend->>Forward: Run compact packed prompts
    Forward->>Attention: q, k, v, cu, scale
    Attention->>Attention: Gather template prefix keys and values
    Attention->>Torch: varlen_attn(q, k, v, cu, cu_k, window_size, enable_gqa)
    Torch-->>Attention: Packed causal attention output
    Attention-->>Forward: Return output with row dimension
Loading

Flow diagram for compact attention kernel selection

flowchart TD
    A["GraphBackend initializes with --batches setting"] --> B{"Compact rows requested?"}
    B -->|No| C["Use padded batching"]
    B -->|Yes| D{"FlashAttention 3 available?"}
    D -->|Yes| E["Use FA3 compact rows"]
    D -->|No| F{"torch_varlen_available passes?"}
    F -->|Yes| G["Use torch varlen compact rows"]
    F -->|No| H["Refuse with capability reason"]
    I["--batches auto"] --> J["Compact only through FA3"]
    J --> D
Loading

File-Level Changes

Change Details Files
Add PyTorch varlen attention as an opt-in compact-row backend for compatible non-Hopper GPUs while preserving the existing FlashAttention 3 path.
  • Detect CUDA sm80+, fp16/bf16, and varlen_attn GQA support with actionable refusal reasons.
  • Route packed and template-prefix attention through torch varlen_attn with GQA, causal windowing, and compile-safe custom-op behavior.
  • Keep --batches auto unchanged and select torch varlen only for explicitly requested compact Llama configurations.
  • Expose the selected compact kernel and template-prefix status in the startup message.
basal/engine.py
basal/server.py
Document compact batching availability, configuration behavior, performance gains, and increased memory requirements across GPU classes.
  • Update --batches help to describe torch varlen support on sm80+ GPUs and unchanged auto behavior.
  • Document installation, serving results, memory trade-offs, model limitations, and release-note changes.
docs/INSTALL.md
docs/SERVING.md
docs/WHATS_NEW.md
Add CUDA coverage for packed-row correctness and template-prefix causal semantics across attention implementations.
  • Compare torch varlen packed outputs with separate causal SDPA prompts, including trailing empty prompts.
  • Validate template-prefix bottom-right causal masking and numerical agreement with FlashAttention 3 where available.
  • Skip tests with a clear reason when the required CUDA or torch varlen capabilities are unavailable.
tests/test_compact_varlen.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

@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="633" />
<code_context>
+        why = torch_varlen_available(getattr(torch, dtype)) if self.gemma is None else "Gemma 4 needs --gemma-attn fa3"
+        torch_varlen = not fa3 and batches == "compact" and why is None
+        self.compact = batches in ("compact", "auto") and (fa3 or torch_varlen) and self.dev.type == "cuda"
+        _VARLEN["impl"] = "torch" if torch_varlen else "fa3"
+        self.compact_kernel = ("torch varlen" if torch_varlen else "fa3") if self.compact else None  # start-up line
         if batches == "compact" and not self.compact:
</code_context>
<issue_to_address>
**Compact attention uses the wrong kernel**

When a compact torch-varlen backend remains in use while another `GraphBackend` is initialized, the constructor overwrites process-wide `_VARLEN["impl"]`, and the first backend’s `_varlen_attention` then dispatches through the new choice. On a GPU without usable FA3, compact requests fail importing or launching FA3 instead of using torch varlen.

Store the kernel choice on each backend and have `_varlen_attention` dispatch using that backend’s choice rather than the process-wide selector.

Also at `basal/engine.py:434-437`, `basal/engine.py:634`.
</issue_to_address>

### Comment 2
<location path="basal/engine.py" line_range="630-636" />
<code_context>
+        why = torch_varlen_available(getattr(torch, dtype)) if self.gemma is None else "Gemma 4 needs --gemma-attn fa3"
</code_context>
<issue_to_address>
**Unsupported compact setup loads model first**

When `--batches compact` is requested on a GPU, dtype, or PyTorch installation without a usable compact kernel, `GraphBackend.__init__` loads the tokenizer and moves the full model onto CUDA before checking `torch_varlen_available` and raising the refusal, so an unsupported compact configuration spends time and GPU memory loading the model and can OOM before showing the intended reason.

Preflight compact-kernel availability before loading model weights, then raise the same reason immediately for unsupported configurations.
</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
…unsupported --batches compact is refused before loading

_VARLEN was process-wide: a second GraphBackend in the same process
switched the kernel of the first. Each backend now keeps its own
compact_kernel and passes it through the forward (basal_varlen), like
basal_cu. A --batches compact that no kernel can serve (no CUDA, sm < 80,
fp32 activations, Gemma 4 without --gemma-attn fa3) is refused right
after set_attention, before the tokenizer and the weights load.
@rkinas
rkinas merged commit 7669362 into rkinas:main Oct 21, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 21, 2026
….1 check (#29)

--attn fa2 --batches compact against --batches default on one H100 (think20 venv, torch 2.13), 16 clients: single
questions basal-2.0-mini 79.0 -> 91.7 decisions/s, basal-2.0-4.5B 27.9 -> 32.3; five questions over 3k-10k tokens
unchanged; GPU memory +5.8 / +7.2 GB; start-up +51 / +88 s. dev v2: same top answer at margin >= 0.2 on 7,629 /
7,629 (mini) and 9,064 / 9,064 (4.5B, --template-prefix off; on: 9,060, max |dp| 0.53).
rkinas added a commit that referenced this pull request Oct 21, 2026
rkinas added a commit that referenced this pull request Oct 21, 2026
…orced (--attn fa2) and on an RTX 4060 Ti; Blackwell not yet
rkinas added a commit that referenced this pull request Oct 21, 2026
rkinas added a commit that referenced this pull request Oct 21, 2026
…ot yet measured on Blackwell'

RTX PRO 6000 Blackwell Server Edition (sm_120, torch 2.13 cu129), release-2.3.1 b870eb3, --batches compact vs auto
(auto: no compact rows there, start-up line 'attention fa2'): single questions basal-2.0-mini 49.0 -> 57.9
decisions/s, basal-2.0-4.5B 17.0 -> 19.1; five questions unchanged; GPU memory +5.8 / +7.2 GB; start-up +31 / +112 s;
dev v2 same top answer at margin >= 0.2: 7,632 / 7,632 and 9,047 / 9,049 (4.5B --template-prefix off).
rkinas added a commit that referenced this pull request Oct 21, 2026
@rkinas

rkinas commented Oct 21, 2026

Copy link
Copy Markdown
Owner

Merged and released in basal 2.3.1 (https://github.com/rkinas/basal/releases/tag/v2.3.1). Gates: --batches auto unchanged (dev v2 bit-identical on an H100 for basal-2.0-mini and 4.5B); --batches compact vs default on an RTX PRO 6000 Blackwell: same top answer at margin ≥ 0.2 on 7,632 / 7,632 (mini) and 9,047 / 9,049 (4.5B, template prefix off), single questions +18% / +13%, multi unchanged, about 6–7 GB more GPU memory and a slower start-up (documented in SERVING.md next to your RTX 4060 Ti numbers). Thank you, you're credited in the release notes and the README.

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