What are the tensor shapes at each stage of a multi-head attention forward pass for a sequence of length N and hidden dimension d?

Last updated 22 November 2026

  • Input (B, N, d) is projected to Q, K, V of (B, N, d), then split into heads as (B, h, N, d_k) with d_k = d/h.

  • Scores QKᵀ/√d_k and softmax (over keys) are (B, h, N, N). Multiplying by V gives (B, h, N, d_k).

  • Heads are merged by transpose and reshape back to (B, N, d), then W_O keeps it (B, N, d).

  • https://huggingface.co/blog/not-lain/tensor-dims
  • https://apxml.com/courses/how-to-build-a-large-language-model/chapter-10-implementing-transformer-from-scratch/building-multi-head-attention-layer
  • https://dev.to/jackm_345442a09fb53b/llm-interview-series3-transformers-explained-attention-is-all-you-need-523o
All Transformers interview questions