Positional Encoding:
- have sentence [“i”, “love”, “ai”]
- then have each word assign an id [“1”, “4”, “9”] from your vocabulary
- then get embedding vector (of size d_model=4) assigned to each id. Final vector is of size (seq_len, d_model)
- positional embedding will give a same size array as embedding vector (seq_len, d_model). Means for each word we get a vector of size d_model.
- Finally embedding vector and positional embedding being added.
Intuition behind PE:
- The formula is a simple sin and cos, with a slightly more complex expression for the angle.
- $pos$ is the position of each word in the sentence, starting from 0 (e.g., “I love AI” → $pos$: 0, 1, 2).
- Each word gets its own positional encoding (PE) vector of size $d_{model}$, with shape $(1, d_{model})$.
- This vector is filled in pairs of slots, and $i$ is the index of each sin-cos pair. It goes from $0$ to $\frac{d_{model}}{2} - 1$.
- For example, if $d_{model} = 4$, the vector has 4 slots, which form 2 pairs ($i = 0, 1$). In each pair, one slot is filled using sin and the other using cos.
How to read it
- Each row = $pos$ (one word position, 0 to 50)
- Each column = one slot (“Depth”, 0 to 127), so $d_{model} = 128$
- Pair number: $i = \lfloor \text{depth}/2 \rfloor$, so $i$ goes from 0 to 63
- Color = the sin or cos value: blue ≈ $+1$, white ≈ $0$, red ≈ $-1$
What you see, left to right
| Region (depth) | $i$ | What it looks like | Why |
|---|---|---|---|
| Left (0–20) | small | Busy red/blue checkerboard | Values change fast from row to row |
| Middle (20–60) | medium | Wide, smooth, slanted bands | Values change slowly |
| Right (60–127) | large | Plain vertical stripes | Values barely change over 50 positions |
Why stripes on the right? For large $i$, the denominator is huge, so the angle is close to 0:
- Even slots: $\sin(\text{tiny}) \approx 0$ → white
- Odd slots: $\cos(\text{tiny}) \approx 1$ → dark blue

value from left changes quickly, in the middle its changing but slowly finally in the right its getting saturated to plain vertical strips.
Summery:
- PE is a vector added to the embedding vector of each word to inject the position information of each word.
- The PE eqn has two variables $pos$ and $i$
- $pos$ : index of each word
- $i$ : pair index in the PE vector.
- In the PE vector, even index is sin and cos in odd.
- sin and cos is the function of $pos$ and $i$.
- $pos$ is in the numerator, so as it increases, $\theta$ increases (for a fixed $i$). The sin and cos values then oscillate between $-1$ and $+1$.
- $i$ is in the exponent of the denominator. For a fixed $pos$, as $i$ increases, the denominator increases, so $\theta$ decreases (moving towards zero).
so, as the $i$ increases, it takes more time to get back to the phase it started with. because of which you see the only lack and white bars at the end.
MHA:
self-attention is nothing but the dot product.
Read if you dont understand the diagram
- $x_1, x_2, \dots, x_T$ are the word embeddings, each of size $1 \times d$.
- The dot product $x_1 x_2^\top$ gives a scalar score, $a_{ij}$ dimention is $1\times1$.
- Taking $x_1$ against all $T$ words gives $1 \times T$ scores. Applying softmax gives $a_{1,1}, \dots, a_{1,T}$.
- Repeating this for all $T$ words gives a $T \times T$ attention weight matrix, in which each row sums to 1.
ZOOM IN if needed
Self Attention from Transformer paper:
- same as the $A_i$ formula.
- Softmax part is a matrix (dim $T \times T$) and $V$ is a vectors of size $T \times \Large{d_v}$ .
- think of $a_{ij}$ as the Attention Score and $\Large A_i$ Embedding of word $i$, mixed with its context from other words. Think of $a{ij}$ as weight/importance score, which tells how much influence word $x_j$ should have on word $x_i$._
- Here, $\Large a_{i}$ is one row of $T \times T$ matrix, where $T$ is sequence length. $\Large a_i = [a_{i,1}, \dots, a_{i,T}]$ is the $1 \times T$ vector.
- $\Large a_{ij}$ is one number of the $\Large a_i$ row.
- Say, $T = 2$, $d = 2$
\(\Large 0.7\,\underbrace{[1,\ 2]}_{x_1} + 0.3\,\underbrace{[3,\ 4]}_{x_2} = [1.6,\ 2.6]\)
- So in the $\Large \Sigma$ part of the eqn we are doing scalar vector multiplication only.
Multi-head Attention:
- One attention gives one view of how words relate, multiple-attention head gives several views at once.
- Analogy: Think of it as several experts reads the same sentence, and then combining their notes. \(\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,W_O\)
in the image its being shown that $QKV$ are being sent through the linear layer, but its just the original $QKV$ vectors split in $\Large n_{head}$ number of head. Here is an example:
Take $B=2$, $T_q=5$, $d_{model}=512$, $H=8$, so $d_k = 512/8 = 64$.
| Step | Shape | Example |
|---|---|---|
Original q |
$(B,\ T_q,\ d_{model})$ | $(2, 5, 512)$ |
After .view(...) |
$(B,\ T_q,\ H,\ d_k)$ | $(2, 5, 8, 64)$ |
After .transpose(1, 2) |
$(B,\ H,\ T_q,\ d_k)$ | $(2, 8, 5, 64)$ |
viewcuts each word’s 512 numbers into 8 chunks of 64, one per head. The total number of values stays the same.transpose(1, 2)swaps $T_q$ and $H$, so each head gets its own $T_q \times d_k$ matrix.
Masked Attention:
The Transformer decoder is auto-regressive: it predicts the next token using the tokens that come before it.> If a token can attend to future tokens, their information leaks into its representation, and the model can simply copy the answer, during training instead of learning to predict it. So, a mask matrix with $-\infty$ above the diagonal (and 0 elsewhere) is added to $\frac{QK^\top}{\sqrt{d_k}}$ before applying softmax. As a result, the upper-triangular part of the final attention matrix (above the diagonal) becomes zero.
Time Complexity
In a self-attention there are QK matrix dot product which is a $(n \times d)(d \times n) \rightarrow n \times n$. If $n$ = seq length, then self-attention is calculated for each of the words, total $n^2$ combinations. and for each dot product there are total $d$ multiplications. $d$ here is the length of vector.
so the final time complexity becomes $O(n^2 d)$.
Sequential operations self-attention takes $O(1)$, because all the words are processed in the same time. Contrary to RNN, where 5-th word need to wait for 1st 4 words to be processed. So for RNN its $O(n)$.