Rewrite prefix key-padding masks as k/v truncation to keep SDPA on the flash path (PyTorch) - #80
Open
arnaudlvq wants to merge 1 commit into
Open
Conversation
arnaudlvq
requested review from
abhidas,
erzel,
rajatsen91,
siriuz42,
tamannarayan and
weihaokong
as code owners
July 21, 2026 21:35
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
…e flash path Any non-null attn_mask forces torch.nn.functional.scaled_dot_product_attention off the fused flash/memory-efficient backends onto the math backend, which materializes the [T_q, T_src] score matrix per head (O(N^2) memory) and OOMs around ~16k context rows on a 24 GB GPU. At a 100k-row context the scores alone are ~160 GB per ICL block in bf16 (100,000^2 x 8 heads x 2 bytes). The ICL attention mask is always a [B,1,1,S] boolean prefix key-padding mask: valid keys are the first n rows, the same n for every query. Masking those keys is algebraically identical to truncating k/v to the first n rows and passing attn_mask=None, which lets SDPA dispatch to the fused backends with memory linear in N. The rewrite triggers only on that exact pattern and falls through unchanged for any other mask (ragged, float, non-4D). Measured on a Colab A100 (bf16, n_estimators=8): 100k rows x 20 features fit+predict, peak allocated VRAM 13.9 GB, weights included.
arnaudlvq
force-pushed
the
prefix-mask-flash-attention
branch
from
July 21, 2026 21:40
f24fac7 to
4078baa
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Any non-null
attn_maskforcestorch.nn.functional.scaled_dot_product_attentionoff the fused flash/memory-efficient backends onto the math backend
(
check_for_attn_mask, sdp_utils_cpp.h#L258),which materializes the
[T_q, T_src]score matrix per head — O(N²) memory.In practice the PyTorch model OOMs around ~16k context rows on a 24 GB GPU.
At a 121k-row context, the score matrix would be ~235 GB per ICL block in bf16.
The fallback is silent: no warning unless a backend is forced via
torch.nn.attention.sdpa_kernel.Fix
The ICL attention mask is always a
[B,1,1,S]boolean prefix key-paddingmask: valid keys are the first
nrows, the samenfor every query and batchelement. Masking those keys is algebraically identical to truncating k/v to the
first
nrows and passingattn_mask=None, which lets SDPA dispatch to thefused backends (memory linear in N).
MultiheadAttention.forwardnow detects that exact pattern right before theSDPA call and rewrites it; any other mask (ragged n per batch element, float
bias, non-4D) falls through unchanged. The masked form is presumably needed at
pretraining time, where packed batches have a different boundary per element —
that case is ragged and is untouched by this rewrite.
~15 lines in
tabfm/src/pytorch/model.py.Measured
100k-row x 20-feature regression context, bf16,
n_estimators=8, Colab A100:fit+predict completes with peak allocated VRAM 13.9 GB (weights included),
R² 0.999 on the synthetic task. Without the rewrite the mask keeps SDPA on the
math backend, which needs ~160 GB of scores per block at that size
(100,000² x 8 heads x 2 bytes) and OOMs around ~16k rows on a 24 GB GPU.
Also validated at 121k rows on a private real dataset with metric-identical
predictions vs. the small-context baseline.
Tests
tabfm/src/pytorch/prefix_mask_test.py(torch-only, CPU, <1 s):observed max |diff| ~2e-7);
per-element truncated forwards;
TabFMforward with a batchedtrain_sizestays finite with theexpected shape.