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
Input
(B, N, d)is projected to Q, K, V of(B, N, d), then split into heads as(B, h, N, d_k)withd_k = d/h.Scores
QKᵀ/√d_kand 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), thenW_Okeeps 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