Skip to main content
Home › Categories › Artificial Intelligence & Computing › Transformer Architecture and the Multi-Head Self-Attention Mechanism

Transformer Architecture and the Multi-Head Self-Attention Mechanism

Author: ZUVDEX Team 4 min read
transformer architecture self attention scaled dot product attention qkv multi head and grouped query attention gqa rotary position embeddings rope encoder only vs decoder only vs encoder decoder quadratic sequence complexity flashattention

Introduced in 2017 by Vaswani et al., the Transformer is a deep neural network architecture that processes sequential and spatial tokens entirely through self-attention and position-wise feed-forward layers, dispensing with sequential recurrence and fixed-width convolutions. By enabling direct constant-path-length interaction between any pair of tokens while parallelizing every training step across matrix-multiply accelerators, the Transformer became the foundational backbone of modern artificial intelligence.

Key Highlights

  • Scaled dot-product attention projects tokens into Query (Q), Key (K), and Value (V) vectors, computing pairwise compatibility scores normalized by the square root of head dimension.
  • Multi-Head Attention runs multiple independent projection subspaces in parallel so distinct heads specialize in syntactic dependencies, coreference, and positional offsets.
  • Grouped-Query Attention (GQA) and Multi-Head Latent Attention (MLA) compress Key-Value cache memory dramatically during long-context autoregressive decoding.
  • Rotary Position Embeddings (RoPE) encode relative token distances via complex-plane rotations directly inside Q and K vectors, supporting context length extension.

Scaled Dot-Product Attention and Encoder/Decoder Topologies

In recurrent networks, information from the beginning of a long document had to survive hundreds of sequential hidden-state updates to reach the end. Self-attention replaces sequential state passing with content-addressable lookup: every token emits a Query vector asking for relevant context, a Key vector advertising its attributes, and a Value vector carrying the payload aggregated according to softmax-normalized Query–Key inner products.

Dividing the dot product by the square root of the per-head dimension prevents variance growth in high dimensions from pushing the softmax function into saturated regions with vanishing gradients. Surrounding each attention and SwiGLU feed-forward sub-block with Pre-RMSNorm and residual connections ensures clean signal propagation across dozens of stacked layers.

Transformer Variant Attention Masking Canonical Examples Best-Fit Workload
Encoder-Only Bidirectional (all tokens attend to all) BERT, RoBERTa, ModernBERT, ViT Embeddings, reranking, classification, NER
Decoder-Only Causal triangular (attend to past tokens) GPT, Llama, Claude, Qwen, Mistral General reasoning, code synthesis, chat, agents
Encoder–Decoder Bidirectional encoder + causal cross-attention Original Transformer, T5, Whisper Speech-to-text transcription, sequence transduction

Rotary Position Embeddings and Attention Memory Compression

Because pure self-attention is permutation-equivariant—treating an unordered bag of tokens identically unless order is injected—modern Transformers apply Rotary Position Embeddings (RoPE), rotating Query and Key coordinate pairs by angles proportional to token index so inner products depend naturally on relative token distance.

At inference time, storing past Key and Value tensors in GPU High-Bandwidth Memory (the KV cache) avoids recomputing earlier tokens, turning memory bandwidth into the primary bottleneck. Grouped-Query Attention (GQA) shares each Key-Value head across four to eight Query heads, cutting KV cache footprint by up to 8× with negligible quality impact.

Attention costs, context length, and design choices

For a sequence of length n, dense self-attention compares each query with keys across the sequence, so the attention-score work and memory traffic can grow roughly with n squared. This makes long contexts expensive even when a model advertises a large maximum window. Flash-style kernels reduce the need to materialize the full score matrix in high-bandwidth memory; grouped-query attention shares key/value heads to reduce inference cache size. Neither changes the meaning of the task or guarantees that useful evidence at every position will be used correctly.

Architecture choice follows the objective. Bidirectional encoders are useful when an output depends on context on both sides, such as classifying or reranking a complete passage. Causal decoders are convenient for generating a continuation one token at a time. Encoder–decoder models separate input encoding from output generation and remain useful for tasks such as translation. These are design patterns, not rankings: latency, model size, training data, and evaluation should decide the fit. The path from token IDs to model inputs is covered in language-model tokenization.

At inference, a key–value cache avoids recomputing earlier tokens but consumes memory proportional to sequence length, layers, batch size, and stored key/value dimensions. Serving systems trade off concurrency, latency, and cache capacity through batching and cache management. A reported context window is therefore not a substitute for retrieval tests, position-sensitive evaluations, or checks that the model cites the right evidence.

FAQs

Why does standard self-attention scale quadratically with sequence length?

Every token computes a compatibility score against every preceding token in the context window, forming an N×N interaction matrix whose arithmetic operations grow proportionally to N².

How does FlashAttention speed up Transformers without approximating attention math?

FlashAttention tiles Query, Key, and Value blocks inside ultra-fast on-chip GPU SRAM and computes exact online softmax normalizers incrementally, never materializing the massive N×N attention matrix in slower off-chip HBM memory.

References & Sources

  • Vaswani, Ashish et al. — Attention Is All You Need, Advances in Neural Information Processing Systems (NeurIPS).
  • Su, Jianlin et al. — RoFormer: Enhanced Transformer with Rotary Position Embedding, Neurocomputing.
  • Dao, Tri et al. — FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, NeurIPS.