WHY: Raw tokens are discrete symbols. We need continuous vectors that capture both meaning (embedding) and position (since attention has no inherent order).
Formula Derivation:
InputRepresentation(x,pos)=Embed(x)+PE(pos)
The positional encoding uses sine/cosine functions:
PE(pos,2i)=sin(100002i/dmodelpos)PE(pos,2i+1)=cos(100002i/dmodelpos)
WHY these specific functions?
Sinusoids allow the model to learn relative positions: PE(pos+k) can be expressed as a linear function of PE(pos)
Different frequencies (via 100002i/dmodel) encode position at different scales
Extrapolates to sequence lengths unseen during training
The attention mechanism computes:
Attention(Q,K,V)=softmax(dkQKT)V
Derivation from scratch:
Start with input X∈Rn×dmodel (n tokens, dmodel=512 dims)
Project to queries/keys/values: Q=XWQ, K=XWK, V=XWV where WQ,WK,WV∈Rdmodel×dk
Compute similarity scores: QKT∈Rn×n (every token attends to every token)
Scale by dkWHY? Dot products grow with dimension; large values push softmax into saturation regions with tiny gradients
Apply softmax row-wise: attention weights sum to 1 per query
Weighted sum of values: output per token is a weighted combination of all tokens' value vectors
Multi-head attention runs h=8 attention operations in parallel:
MultiHead(Q,K,V)=Concat(head1,…,headh)WOheadi=Attention(QWiQ,KWiK,VWiV)
Each head has dk=dv=dmodel/h=512/8=64 dimensions.
WHY multiple heads? Different learn different types of relationships (syntactic, semantic, positional). One head might focus on subject-verb agreement, another on long-range dependencies.
Sub-layer 2: Position-wise Feed-Forward Network
FFN(x)=ReLU(xW1+b1)W2+b2
Where W1∈Rdmodel×dff, W2∈Rdff×dmodel, dff=2048.
WHY? Attention is linear (weighted sums). FFN adds non-linearity and increases model capacity. Applied to each position independently (same network across positions, different positions don't interact here).
Residual Connection + Layer Norm around each sub-layer:
LayerNorm(x+Sublayer(x))
WHY residuals? Enable gradient flow in deep networks (6 layers = 12 sub-layers in encoder). Without residuals, gradients vanish.
WHY LayerNorm? Stabilizes training by normalizing across features per example:
LayerNorm(x)=σ2+ϵx−μ⋅γ+β
where μ,σ2 computed over dmodel dimensions per token.
Same as encoder self-attention BUT with causal masking:
maskij={0−∞if i≥jif i<j
Applied before softmax: softmax(QKT/dk+mask)
WHY? During training, decoder sees the full target sequence. Masking prevents position i from attending to future positions j>i, ensuring autoregressive generation (predict next token using only past tokens).
WHY? This is where decoder accesses source sequence! Decoder queries encoder's representation of input. For translation "Le chat" → "The cat", decoder generating "cat" attends to "chat" in encoder output.
Parallelization: All positions processed simultaneously (vs. sequential RNNs)
Constant path length: Any token pair directly connected via attention (vs. O(n) steps in RNN)
Learnable relationships: Attention weights adapt to data (vs. fixed CNN kernels)
Scalability: Stack more layers/heads/dimensions as compute grows
Recall Explain to a 12-Year-Old
Imagine you're reading a long story. Your brain doesn't read one word, forget it, then read the next. Instead, your eyes can jump around—you might read a word, then remember something from the beginning, then connect it to the end. That's what Transformers do!
Old AI models (RNNs) were like reading with a tiny window that slides along: see one word, move to the next, but forget the first. Transformers instead see the WHOLE sentence at once. Every word looks at every other word and decides "How much should I pay attention to that word to understand this one?"
There are two parts: an Encoder (reads the input sentence, like "Le chat noir" in French) and a Decoder (writes the output, like "The black cat"). The Encoder figures out what everything means. The Decoder creates the answer, but with a special trick: when writing word3, it can only look at words 1 and 2 (no peeking at future words!), just like you can't see tomorrow when writing your diary today.
The magic ingredient is attention—a formula that computes "How related are word A and word B?" for every pair. Do this millions of times while training, and the AI learns language patterns!
What are the three sub-layers in each Transformer decoder layer?
(1) Masked multi-head self-attention, (2) Encoder-decoder cross-attention, (3) Position-wise feed-forward network. Each has residual connection + LayerNorm.
Why does the attention formula use scaling by √d_k?
Dot products grow in magnitude with dimension d_k. Large values push softmax into saturation regions where gradients are extremely small, hindering learning. Dividing by √d_k keeps variance stable.
What is the purpose of causal masking in the decoder?
Prevents position i from attending to future positions j > i during training. This enforces autoregressive generation: predicting token i can only use tokens 1 through i-1, not future tokens.
How many parameters does the Transformer base model have approximately?
~65 million parameters, using weight tying between input embedding, output embedding, and pre-softmax projection.
What is the learning rate warmup schedule used in the original paper?
lr = d_model^(-0.5) × min(step^(-0.5), step × warmup_steps^(-1.5)) with warmup_steps=4000. Linear increase for 4000 steps, then inverse square root decay.
Why multiply embedings by √d_model before adding positional encoding?
Embedings have variance ~1, positional encodings are bounded [-1,1]. Scaling by √d_model (~22.6 for d=512) ensures embedings dominate initially while PE adds positional information without overwhelming semantic content.
What is the dimension of each attention head in the base model?
d_k = d_v = d_model / h = 512 / 8 = 64 dimensions per head.
Why use sinusoidal positional encoding instead of learned embedings?
Sinusoids allow the model to extrapolate to sequence lengths longer than seen during training. PE(pos+k) can be expressed as a linear function of PE(pos), helping the model learn relative positions.
What is the FFN inner dimension d_ff in the base model?
2048 (4× the model dimension of 512). Projects up, applies ReLU, projects back down.
How does encoder-decoder attention differ from self-attention?
In cross-attention, Q comes from decoder, but K and V come from encoder output. This allows decoder to attend to source sequence while generating target sequence.
With label smoothing ε_ls=0.1 and vocabulary size K, what target probability does the true class get?
1 − ε_ls + ε_ls/K. For K=4 this is 0.9 + 0.025 = 0.925; every other class gets ε_ls/K = 0.025.
Chalo, is note ka core idea samajhte hain. 2017 se pehle, jab bhi humein language ya kisi bhi sequence ke saath kaam karna hota tha, hum RNNs ya LSTMs use karte the. Problem yeh thi ki yeh models ek-ek word ko left-to-right process karte the, matlab ek word tab tak process nahi hota jab tak pichla word finish na ho. Yeh slow tha aur parallel processing possible hi nahi thi. Doosri badi dikkat thi long-range dependencies ki — agar sentence bada hota, toh shuruaat ki information end tak pahunchte-pahunchte fade ho jaati thi (vanishing gradient ki wajah se). Transformer ne bola: "Kyun na hum saare words ko ek saath process karein, aur har word ko baaki sabhi words ko directly dekhne ki azaadi dein?" Isko hi self-attention kehte hain, aur yahi poori revolution ki jaan hai.
Ab yahan ek interesting twist hai. Kyunki hum saare words ek saath dekh rahe hain, model ko yeh pata hi nahi chalta ki kaunsa word pehle aaya aur kaunsa baad mein — order ki information gaayab ho jaati hai. Isko solve karne ke liye positional encoding add karte hain, jo sine aur cosine functions use karti hai taaki har position ka ek unique "signature" ban jaaye. Yeh smartly design kiya gaya hai — different frequencies alag-alag scale par position batati hain, aur model relative positions bhi seekh sakta hai. Ek chhoti si detail: embeddings ko dmodel se multiply karte hain taaki meaning (semantic content) shuruaati training mein dominate kare aur position ki info usse overwhelm na kar de.
Yeh sab kyun matter karta hai? Kyunki aaj jitne bhi bade models hain — ChatGPT, BERT, translation systems — sab isi "Attention is All You Need" architecture par khade hain. Yeh design GPUs par massively parallel chal sakta hai, isliye hum huge datasets par train kar paate hain jo pehle impossible tha. Encoder-decoder structure, multi-head attention, residual connections aur layer normalization — yeh saare pieces milkar ek aisa foundation banate hain jo modern AI ki backbone hai. Toh agar tum AI-ML seriously seekhna chahte ho, yeh architecture samajhna non-negotiable hai — yahi se sab kuch shuru hota hai.