Knowledge / Artificial Intelligence and Data Science / Transformers and attention

Transformers and attention

Artificial Intelligence and Data Science (B.E./B.Tech) · Deep learning · free study notes for exams, placements and interviews

In short

A transformer is a deep-learning architecture that processes a whole sequence at once and lets every token look at every other token through attention, instead of stepping through the sequence one position at a time. Attention computes a weighted average of value vectors, where the weights come from the similarity between a query and a set of keys, so the model learns which positions matter for each prediction. It replaced recurrent models for language, speech and increasingly vision, and underlies BERT, GPT, Llama and every large language model in use today. It is examined in GATE DA (Data Science and AI), AICTE/CBCS deep-learning papers and NLP electives, and it is the single most asked architecture in Indian ML and GenAI interviews at TCS Research, Infosys, Wipro, Fractal, Microsoft IDC, Google India, Sarvam AI and AI4Bharat.

Explained

Why attention replaced recurrence

Attention mechanism: queries, keys and values

Multi-head attention

Positional information

Full architecture: encoder, decoder and the sub-layers

Training and inference practicalities

Key points

Formulas and examples

Attention(Q, K, V) = softmax(QKᵗ / √d_k) · V
Q = XW_Q (n×d_k), K = XW_K (n×d_k), V = XW_V (n×d_v); X is n×d_model, n = tokens, d_model = embedding width
softmax(z)_i = ez_i / Σ_j ez_j — row-wise over the n scores of one query
Masked score: s_ij = qᵢᵗk_j/√d_k if j ≤ i, else −∞ (so weight = 0)
MultiHead(Q,K,V) = Concat(head₁ … head_h) W_O, head_i = Attention(QW_Qi, KW_Ki, VW_Vi), d_k = d_v = d_model/h
Sinusoidal PE: PE(pos, 2i) = sin(pos / 100002i/d_model); PE(pos, 2i+1) = cos(pos / 100002i/d_model)
FFN(x) = W₂ · act(W₁x + b₁) + b₂, W₁ is d_ff×d_model, W₂ is d_model×d_ff, d_ff ≈ 4 d_model
LayerNorm(x) = γ · (x − μ)/√(σ² + ε) + β, μ and σ² over the d_model features of one token; ε ≈ 1e−5
Parameters per layer ≈ 4·d_model² (attention: W_Q, W_K, W_V, W_O) + 2·d_model·d_ff (FFN) = 12·d_model² when d_ff = 4 d_model
Attention FLOPs per layer ≈ 2n²d_model (scores) + 2n²d_model (weighted sum); projections ≈ 8n·d_model²
KV cache bytes ≈ 2 × layers × n × d_model × bytes_per_element (full multi-head attention)

Example 1 — one attention head by hand. Three tokens, d_k = 2. q₃ = [1, 0]; keys k₁ = [1, 0], k₂ = [0, 1], k₃ = [1, 1]; values v₁ = [1, 0], v₂ = [0, 1], v₃ = [1, 1].

Example 2 — effect of scaling on softmax. Two scores whose dot products are 40 and 20, with d_k = 64.

Example 3 — parameter count of BERT-base-style encoder. d_model = 768, h = 12, d_ff = 3,072, L = 12 layers, vocab 30,000, max position 512.

Example 4 — compute and memory at n = 1,024. Same model, one layer, batch 1.

Example 5 — KV cache for generation. A 7-billion-parameter decoder: L = 32, d_model = 4,096, h = 32, d_k = 128, context n = 4,096, fp16 (2 bytes).

FeatureRNN / LSTMCNN (1-D)Transformer
Parallel over timeNoYesYes
Path length between distant tokensO(n)O(n/k) layersO(1)
Complexity per layerO(n·d²)O(k·n·d²)O(n²·d)
Handles variable lengthNativelyWith paddingWith masks
Long-range dependencyWeakMediumStrong
Memory at inferenceSmall hidden stateSmallLarge KV cache
ModelFamilyPretraining taskTypical use
BERT / MuRIL / IndicBERTEncoder-onlyMasked LM (+NSP in BERT)Classification, NER, embeddings
GPT / Llama / MistralDecoder-onlyCausal LMGeneration, chat, agents
T5 / BART / IndicTrans2Encoder–decoderSpan corruption / denoisingTranslation, summarisation
ViTEncoder-onlySupervised or masked patchesImage classification, OCR
import torch, torch.nn.functional as F

def attention(Q, K, V, causal=False):
    d_k = Q.size(-1)
    scores = Q @ K.transpose(-2, -1) / d_k ** 0.5      # (..., n, n)
    if causal:
        n = scores.size(-1)
        mask = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(mask, float('-inf'))
    W = F.softmax(scores, dim=-1)                       # rows sum to 1
    return W @ V, W

Where it is used

Interview questions

Common mistakes

Related topics

Recurrent networks and LSTMs · Transfer learning and fine-tuning · Training deep networks: optimisers, normalisation and regularisation · Convolutional neural networks · Graph neural networks basics · Generative models: GANs, VAEs and diffusion

Open in the Knowledge reader →Find jobs →