|
| 1 | +--- |
| 2 | +title: The Core of Transformers |
| 3 | +sidebar_label: Self-Attention |
| 4 | +description: "Understanding how models weigh the importance of different parts of an input sequence using Queries, Keys, and Values." |
| 5 | +tags: [deep-learning, attention, transformers, nlp, self-attention] |
| 6 | +--- |
| 7 | + |
| 8 | +**Self-Attention** (also known as Intra-Attention) is the mechanism that allows a model to look at other words in an input sequence to get a better encoding for the word it is currently processing. |
| 9 | + |
| 10 | +Unlike [RNNs](../rnn/rnn-basics), which process words one by one, Self-Attention allows every word to "talk" to every other word simultaneously, regardless of their distance. |
| 11 | + |
| 12 | +## 1. Why do we need Self-Attention? |
| 13 | + |
| 14 | +Consider the sentence: *"The animal didn't cross the street because **it** was too tired."* |
| 15 | + |
| 16 | +When a model processes the word **"it"**, it needs to know what "it" refers to. Is it the animal or the street? |
| 17 | +* In a standard RNN, if the sentence is long, the model might "forget" about the animal by the time it reaches "it". |
| 18 | +* In **Self-Attention**, the model calculates a score that links "it" strongly to "animal" and weakly to "street". |
| 19 | + |
| 20 | +## 2. The Three Vectors: Query, Key, and Value |
| 21 | + |
| 22 | +To calculate self-attention, we create three vectors from every input word (embedding) by multiplying it by three weight matrices ($W^Q, W^K, W^V$) that are learned during training. |
| 23 | + |
| 24 | +| Vector | Analogy (The Library) | Purpose | |
| 25 | +| :--- | :--- | :--- | |
| 26 | +| **Query ($Q$)** | The topic you are searching for. | Represents the current word looking at other words. | |
| 27 | +| **Key ($K$)** | The label on the spine of the book. | Represents the "relevance" tag of all other words. | |
| 28 | +| **Value ($V$)** | The information inside the book. | Represents the actual content of the word. | |
| 29 | + |
| 30 | +## 3. The Calculation Process |
| 31 | + |
| 32 | +The attention score is calculated through a series of matrix operations: |
| 33 | + |
| 34 | +1. **Dot Product:** We multiply the Query of the current word by the Keys of all other words. |
| 35 | +2. **Scaling:** We divide by the square root of the dimension of the key ($\sqrt{d_k}$) to keep gradients stable. |
| 36 | +3. **Softmax:** We apply a Softmax function to turn scores into probabilities (weights) that sum to 1. |
| 37 | +4. **Weighted Sum:** We multiply the weights by the Value vectors to get the final output for that word. |
| 38 | + |
| 39 | +$$ |
| 40 | +\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V |
| 41 | +$$ |
| 42 | + |
| 43 | +## 4. Advanced Flow Logic (Mermaid) |
| 44 | + |
| 45 | +The following diagram represents how an input embedding is transformed into an Attention output. |
| 46 | + |
| 47 | +```mermaid |
| 48 | +graph TD |
| 49 | + Input[Input Embedding $$\ X$$] --> WQ[Weight Matrix $$\ W^Q$$] |
| 50 | + Input --> WK[Weight Matrix $$\ W^K$$] |
| 51 | + Input --> WV[Weight Matrix $$\ W^V$$] |
| 52 | + |
| 53 | + WQ --> Q[Query $$\ Q$$] |
| 54 | + WK --> K[Key $$\ K$$] |
| 55 | + WV --> V[Value $$\ V$$] |
| 56 | + |
| 57 | + Q --> Dot[Dot Product $$\ Q·K$$] |
| 58 | + K --> Dot |
| 59 | + |
| 60 | + Dot --> Scale["Scale by $$\ 1/\sqrt {d_k}$$"] |
| 61 | + Scale --> Softmax[Softmax Layer] |
| 62 | + |
| 63 | + Softmax --> WeightSum[Weighted Sum with $$\ V$$] |
| 64 | + V --> WeightSum |
| 65 | + |
| 66 | + WeightSum --> Final[Attention Output] |
| 67 | +
|
| 68 | +``` |
| 69 | + |
| 70 | +## 5. Multi-Head Attention |
| 71 | + |
| 72 | +In practice, we don't just use one self-attention mechanism. We use **Multi-Head Attention**. This involves running several self-attention calculations (heads) in parallel. |
| 73 | + |
| 74 | +* One head might focus on the **subject-verb** relationship. |
| 75 | +* Another head might focus on **adjectives**. |
| 76 | +* Another head might focus on **contextual references**. |
| 77 | + |
| 78 | +By combining these, the model gets a much richer understanding of the text. |
| 79 | + |
| 80 | +## 6. Implementation with PyTorch |
| 81 | + |
| 82 | +Modern deep learning frameworks provide highly optimized modules for this. |
| 83 | + |
| 84 | +```python |
| 85 | +import torch |
| 86 | +import torch.nn as nn |
| 87 | + |
| 88 | +# Embedding dim = 512, Number of heads = 8 |
| 89 | +multihead_attn = nn.MultiheadAttention(embed_dim=512, num_heads=8) |
| 90 | + |
| 91 | +# Input shape: (sequence_length, batch_size, embed_dim) |
| 92 | +query = torch.randn(10, 1, 512) |
| 93 | +key = torch.randn(10, 1, 512) |
| 94 | +value = torch.randn(10, 1, 512) |
| 95 | + |
| 96 | +attn_output, attn_weights = multihead_attn(query, key, value) |
| 97 | + |
| 98 | +print(f"Output shape: {attn_output.shape}") # [10, 1, 512] |
| 99 | + |
| 100 | +``` |
| 101 | + |
| 102 | +## References |
| 103 | + |
| 104 | +* **Original Paper:** [Attention Is All You Need (2017)](https://arxiv.org/abs/1706.03762) |
| 105 | +* **The Illustrated Transformer:** [Jay Alammar's Blog](https://jalammar.github.io/illustrated-transformer/) |
| 106 | +* **Harvard NLP:** [The Annotated Transformer](http://nlp.seas.harvard.edu/2018/04/03/attention.html) |
| 107 | + |
| 108 | +--- |
| 109 | + |
| 110 | +**Self-Attention allows the model to understand the context of a sequence. But how do we stack these layers to build the most powerful models in AI today?** |
0 commit comments