Repository navigation
perf(graph): compact rows on any sm80+ GPU through torch varlen attention (--batches compact) - #29
Conversation
…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.
Reviewer's GuideThis 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 attentionsequenceDiagram
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
Flow diagram for compact attention kernel selectionflowchart 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
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 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>…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.
….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).
…-in --batches compact (#29, @Butterski; branch pr29-231)
…orced (--attn fa2) and on an RTX 4060 Ti; Blackwell not yet
…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).
|
Merged and released in basal 2.3.1 (https://github.com/rkinas/basal/releases/tag/v2.3.1). Gates: |
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_attentioncallsflash_attn_interface. Every other NVIDIA GPU (A100, L4 / L40S, RTX 30 / 40 / 50, RTX PRO 6000, B200) runs paddedgraphs only.
torch 2.13 (the version in
uv.lock) shipstorch.nn.attention.varlen.varlen_attn: torch's built-in FlashAttention 2on packed sequences, with GQA (
enable_gqa) and a causal window (window_size=(-1, 0)), registered as a custom op witha fake implementation, so
torch.compiletraces it without a graph break.Change
_varlen_attention(..., impl): withimpl == "torch varlen", the same call throughvarlen_attn(same packedlayout, same
cu/ template-prefix gather), else FlashAttention 3 as before. Each backend keeps its choice incompact_kerneland passes it through the forward (basal_varlen, next tobasal_cu), so backends in one processdo not share it.
GraphBackend.__init__: compact rows with FA3 as before; with--batches compacton another GPU, for Llama models,through
varlen_attnwhentorch_varlen_available(dtype)(CUDA, sm80+, bf16 / fp16, a torch withenable_gqa).--batches autois unchanged (compact only where FA3 runs). A--batches compactthat no kernel can serve isrefused with the reason before the tokenizer and the weights load.
mode fast attention fa2 compact rows torch varlen template prefix ready in ....--batcheshelp, 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-loadtestat 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:complex.jsonlrequests, 58 probability vectors): B vs A and C vs A the sametop 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;
--deterministicstaysthe setting for repeatable answers.
_forwardssends only one-block units to compact rows), so their slowdown is not the kernel: the compact graphs takeabout 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/test_compact_varlen.pyon the RTX 4060 Ti: 2 passed (compact rows equal separate SDPA prompts withGQA 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
mainon that GPU (below). These GPUruns are of c0359ef; the review fix after it (2defa6e) changes how the kernel choice reaches
_varlen_attention, notthe 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
autoshould turn this on wherememory allows is your call.
tests/test_lean.py::test_flex_with_lean_on_refused_before_loadingfails on anyCUDA GPU without FlashAttention 3, also on
main:main()callsdefault_mode(), which resolves the model to checkfor Gemma 4, before the
--lean/--treecheck, and the test'sresolvestub fails on any call.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.