NewsCrawler.org

PyTorch MultiheadAttention fast path consumed 18 GB of VRAM when passed a mask

MultiheadAttentionの高速経路がVRAMを18GB食っていた話
Image: zenn.dev

In PyTorch, nn.MultiheadAttention with need_weights=False is documented to use the optimized SDPA[1], but in eval-mode, gradient-free inference the CUDA fast path skips SDPA whenever a mask is passed and builds the full heads × P × P attention matrix (P is the number of 16×16-pixel patches). Xiaomi-Lens-0, a Qwen3.5-4B-based multimodal model that answers in text and converts <|mask|> tokens into pixel-level masks, hit this through its fallback path used when flash-attn[2] is unavailable: at 3 MP the mask generation stage added 18.02 GB of VRAM, and at 8 MP a single 30.75 GiB allocation caused OOM[3]. The decoder always passed a key_padding_mask[4], and the PyTorch source plus a profiler run confirmed that with a mask the fast path builds a [B, num_head, T, T] score matrix, while the same calls in train mode do use SDPA. A one-file PR routed the fallback to the model's existing SDPA path, cutting the extra VRAM at 3 MP to 2.28 GB (about 87% less), and it was merged the next day. Because the spike does not reproduce in training loops or gradient-enabled tests, the author advises benchmarking production-equivalent inference paths separately.

Read the original zenn.dev

Sources

  • Zenn JA

    MultiheadAttentionの高速経路がVRAMを18GB食っていた話

    0 likes0 bookmarks0 comments

Published: First seen: Читать по-русски

Open as a page