Profiling in PyTorch (Part 3): Attention is all you profile

AI-generated summary of reporting by Huggingface Blog. Read the original for the full story.

Why it matters

PyTorch engineers learn to read profiler traces to speed up attention, discovering that default one-liners can be slower than hand-written code and that in-place ops save kernels.

Read this as

This is the third part of a Hugging Face tutorial series on profiling, a technique for seeing exactly how PyTorch code runs on a GPU. The authors break attention, the core calculation inside models like chatbots, into simple steps and watch how each one shows up in a profiler. They show that one small code change removes a wasteful data copy, and that the 'math' version of PyTorch's built-in attention function is actually 3.7 times slower than the naive version they wrote themselves. This affects anyone writing or speeding up PyTorch code.

Hugging Face's profiling tutorial demonstrates measurable GPU cost savings in PyTorch attention code: switching one call to an in-place operation removes a memory-copy kernel per forward pass, which compounds across every transformer layer. It also warns decision-makers' teams that the default 'math' backend of scaled_dot_product_attention is 3.7x slower because it avoids Tensor Cores. Engineers using FlashAttention or the efficient backend gain the most; those relying on defaults may be leaving performance on the table.

The post profiles naive attention, in-place masked_fill_, and F.scaled_dot_product_attention backends on an A100-SXM4-80GB. The math backend launches 20 kernels per forward (3.7x slower), upcasting bf16 to FP32 and rebuilding the causal mask via aten::ones/aten::tril each call. The efficient backend launches one fmha_cutlassF_bf16_aligned_64x64_rf_sm80 CUTLASS kernel; flash uses FlashAttention-2, avoiding materializing the [seq, seq] score matrix in HBM via online softmax. Flash shows only ~13% occupancy despite being fastest. Scripts are public.

Read the original

This summary exists to save you time, not to replace the source.

Key terms

PyTorch Hugging Face FlashAttention-2 scaled_dot_product_attention CUTLASS A100-SXM4-80GB

Was this summary useful?

One click, anonymous. It tells us which summaries to re-run.

Related reading