Attention lets a neural network assign different importance to input elements, giving each output access to the context most relevant to its computation. In transformer-based language models, self-attention lets every sequence position interact with and weight other positions. GPT-like models use decoder-only transformer modules and apply attention while generating text from left to right. section 1.8 section 3.2
Build attention progressively through these implementation variants:
- Simplified self-attention computes attention weights with dot products and forms each context vector as a weighted sum of the inputs. section 3.7
- Scaled-dot-product self-attention adds trainable weight matrices that transform inputs into queries, keys, and values. section 3.7
- Causal attention applies a mask so a left-to-right language model cannot access future tokens during generation. section 3.0 section 3.7
- Multi-head attention stacks multiple causal attention instances, enabling parallel attention to different aspects of the input; batched matrix multiplication provides a compact implementation. section 3.0 section 3.7
Attention transforms input elements into enhanced context-vector representations containing information from the full accessible input. Dot products provide a compact relevance calculation, while matrix multiplication replaces nested loops for efficient computation. Dropout can mask randomly selected attention weights to reduce overfitting. section 3.7
Figure 3.2 The figure depicts different attention mechanisms we will code in this chapter, starting with a simplified version of self-attention before adding the trainable weights. The causal attention mechanism adds a mask to self-attention that allows the LLM to generate one word at a time. Finally, multi-head attention organizes the attention mechanism into multiple heads, allowing the model to capture various aspects of the input data in parallel.
Use this progression diagram to connect simplified self-attention, trainable queries-keys-values attention, causal masking, and multi-head attention. section 3.0



























