The Sequence Modeling Problem
Transformers process all tokens simultaneously using self-attention — a mechanism that lets every token compute how much it should attend to every other token. This parallel processing replaced the sequential bottleneck of RNNs and LSTMs, enabling models to handle long-range dependencies and train on GPUs at massive scale.
In 2017, a paper called "Attention Is All You Need" introduced the Transformer architecture. It replaced recurrent neural networks (RNNs) with a simpler, faster, and more powerful design. Today, every major LLM — GPT, Claude, Llama, Gemini — is built on Transformers.
This tutorial explains how Transformers work, from the ground up. We use a simple sentence example with real numbers so you can follow every step.
Table of Contents
- The Sequence Modeling Problem
- Word Embeddings and Positional Encoding
- Self-Attention: The Core Innovation
- Query, Key, Value (Q, K, V)
- The Attention Formula
- Worked Example: "The cat sat on the mat"
- Multi-Head Attention
- The Transformer Block
- Encoder vs Decoder
- RNN vs LSTM vs Transformer
- FAQ
- Exercises
- Conclusion
1. The Sequence Modeling Problem
Language is sequential. The meaning of a word depends on the words around it:
• "sat" tells us what the cat is doing
• "on the mat" tells us where
• "The" (first) tells us "cat" is a specific noun
• "the" (second) tells us "mat" is a specific noun
A good model needs to understand ALL of these relationships simultaneously.
RNNs tried to solve this by processing tokens one at a time, carrying a "hidden state" forward. But this sequential approach had two critical problems:
- Slow training: Cannot parallelize — must wait for token 1 before processing token 2
- Vanishing gradients: Information from early tokens fades by the time you reach later tokens
Transformers solve both problems by processing all tokens simultaneously using self-attention.
2. Word Embeddings and Positional Encoding
Word Embeddings
Before processing, each token is converted to a numerical vector (embedding). This captures the token's meaning.
"The" → [0.8, 0.2, 0.1, 0.3]
"cat" → [0.9, 0.8, 0.2, 0.1]
"sat" → [0.3, 0.4, 0.9, 0.2]
"on" → [0.1, 0.2, 0.3, 0.8]
"the" → [0.7, 0.3, 0.1, 0.2]
"mat" → [0.2, 0.7, 0.1, 0.9]
Real models use 768–12,288 dimensions. Words with similar meanings cluster together in this high-dimensional space.
Positional Encoding
Transformers process all tokens simultaneously — they have no inherent sense of order. Positional encoding adds position information so the model knows "cat" comes before "sat."
pos=0 "The": emb + pe = [0.800, 1.200, 0.100, 1.300]
pos=1 "cat": emb + pe = [1.741, 1.795, 0.210, 1.100]
pos=2 "sat": emb + pe = [1.209, 1.380, 0.920, 1.200]
pos=3 "on": emb + pe = [0.241, 1.155, 0.330, 1.800]
pos=4 "the": emb + pe = [-0.057, 1.221, 0.190, 1.250]
pos=5 "mat": emb + pe = [-0.759, 1.578, 0.150, 1.900]
Position encodings use sine/cosine functions at different frequencies.
3. Self-Attention: The Core Innovation
Self-attention answers one question for every token: "Which other tokens in this sequence are most relevant to me?"
Imagine you are writing an essay and need to cite sources. For each sentence you write, you scan all your notes and decide which ones are relevant. Self-attention does this for every token — it scans all other tokens and assigns "relevance weights."
"cat" should attend strongly to:
• "sat" (what the cat is doing — 19.1%)
• "mat" (where the cat is — 19.6%)
• "The" (determines it is a noun — 13.3%)
The key insight: every token attends to every other token simultaneously. This is computed in parallel, making it much faster than RNNs.
4. Query, Key, Value (Q, K, V)
Self-attention uses three vectors for each token, derived from its embedding:
| Vector | Role | Analogy |
|---|---|---|
| Query (Q) | "What am I looking for?" | Search query in Google |
| Key (K) | "What do I contain?" | Webpage title and keywords |
| Value (V) | "What information do I provide?" | Webpage content |
The attention score between two tokens is computed as the dot product of the query of one token with the key of another. High dot product = high relevance.
"The": Q=[0.71, 0.37] K=[0.55, 0.37] V=[0.56, 0.70]
"cat": Q=[0.79, 0.83] K=[0.91, 0.67] V=[0.98, 0.91]
"sat": Q=[0.52, 0.72] K=[0.60, 0.94] V=[0.60, 1.13]
"on": Q=[0.78, 0.36] K=[0.46, 0.64] V=[0.62, 0.61]
"the": Q=[0.66, 0.44] K=[0.57, 0.43] V=[0.59, 0.69]
"mat": Q=[1.04, 0.66] K=[0.79, 0.80] V=[1.08, 0.62]
5. The Attention Formula
Step by step:
- Q·KT — Compute dot product of every query with every key → raw attention scores
- / √dk — Scale by the square root of the key dimension (prevents large values)
- softmax — Convert scores to probabilities (sum to 1.0)
- · V — Multiply probabilities by values → weighted sum → output
6. Worked Example: "The cat sat on the mat"
Attention Score Matrix
After computing Q·KT / √dk (where dk=2):
| The | cat | sat | on | the | mat | |
|---|---|---|---|---|---|---|
| The | 0.373 | 0.632 | 0.547 | 0.398 | 0.395 | 0.606 |
| cat | 0.524 | 0.902 | 0.887 | 0.633 | 0.565 | 0.911 |
| sat | 0.391 | 0.676 | 0.699 | 0.495 | 0.424 | 0.698 |
| on | 0.398 | 0.672 | 0.570 | 0.417 | 0.420 | 0.639 |
| the | 0.369 | 0.628 | 0.567 | 0.410 | 0.392 | 0.612 |
| mat | 0.577 | 0.982 | 0.880 | 0.637 | 0.614 | 0.954 |
After Softmax → Attention Weights
| The | cat | sat | on | the | mat | |
|---|---|---|---|---|---|---|
| The | 14.7% | 19.1% | 17.5% | 15.1% | 15.0% | 18.6% |
| cat | 13.3% | 19.4% | 19.1% | 14.8% | 13.8% | 19.6% |
| sat | 13.9% | 18.5% | 18.9% | 15.4% | 14.4% | 18.9% |
| on | 14.7% | 19.3% | 17.4% | 14.9% | 15.0% | 18.7% |
| the | 14.6% | 18.9% | 17.8% | 15.2% | 14.9% | 18.6% |
| mat | 13.5% | 20.2% | 18.3% | 14.3% | 14.0% | 19.7% |
Reading the table: Row "cat" shows that "cat" attends 19.6% to "mat" (strongest), 19.4% to itself, and 19.1% to "sat". These weights determine how much information each token contributes to the representation of "cat."
7. Multi-Head Attention
Real transformers do not use a single attention mechanism. They use multiple "heads" — each learning different types of relationships:
• Head 1 might learn syntactic relationships (subject → verb)
• Head 2 might learn positional relationships (nearby tokens)
• Head 3 might learn semantic relationships (similar meanings)
• Head 4 might learn long-range dependencies
GPT-4 is rumored to use 96–128 attention heads. Each head has its own Q, K, V matrices.
The outputs of all heads are concatenated and projected through a linear layer to produce the final attention output.
8. The Transformer Block
Each transformer layer (block) has two main sub-layers:
↓
┌──────────────────────────────┐
│ Multi-Head Self-Attention │ ← Which tokens relate to which?
│ Add & Layer Normalization │
├──────────────────────────────┤
│ Feed-Forward Network │ ← Process each token independently
│ Add & Layer Normalization │
└──────────────────────────────┘
↓
Output
Stacked N times (12, 24, 32, or 96 layers)
Add & Norm (residual connection + layer normalization) is critical — it allows gradients to flow through deep networks and stabilizes training.
9. Encoder vs Decoder
Transformers come in three configurations:
| Type | Architecture | Attention | Examples | Best For |
|---|---|---|---|---|
| Encoder-only | Reads input bidirectionally | Self-attention (full) | BERT, RoBERTa | Classification, NER, embeddings |
| Decoder-only | Generates left-to-right | Masked self-attention | GPT, Claude, Llama | Text generation, chat, code |
| Encoder-Decoder | Reads input, generates output | Self + cross-attention | T5, BART | Translation, summarization |
Key difference: Decoder-only models (GPT, Claude) use masked self-attention — each token can only attend to previous tokens, not future ones. This prevents "cheating" during text generation.
10. RNN vs LSTM vs Transformer
| Feature | RNN (1986) | LSTM (1997) | Transformer (2017) |
|---|---|---|---|
| Processing | Sequential (one at a time) | Sequential (one at a time) | Parallel (all at once) |
| Long-range | Poor (vanishing gradients) | Better (gated memory) | Excellent (direct attention) |
| Training speed | Slow (no parallelism) | Slow (no parallelism) | Fast (GPU-friendly) |
| Max practical length | ~100 tokens | ~500 tokens | 128K+ tokens |
| Scalability | Limited | Limited | Scales to billions of params |
1. Parallel processing — All tokens processed simultaneously → 100x faster training on GPUs
2. Direct attention — Token 1 can attend to token 1000 directly, no information loss
3. Scalability — Performance improves predictably with more data, compute, and parameters
4. Simplicity — Self-attention is mathematically simpler than LSTM gates
11. FAQ
Why is it called "self-attention"?
Why divide by √d_k?
What does "attention" actually learn?
Why can't RNNs handle long sequences?
What is positional encoding?
What is masked self-attention?
How many transformer layers do modern models have?
12. Exercises
Exercise 1: Attention Intuition
For the sentence "The dog chased the cat because it was fast," which token should "it" attend to most strongly? Why? Write down the attention weight you would expect.
Exercise 2: Dot Product
Given Q=[1.0, 0.5] and K=[0.8, 0.3], compute the raw attention score (dot product). Then compute the scaled score if d_k=2. What does this number represent?
Exercise 3: Softmax
Given raw scores [2.0, 1.0, 0.5], compute the softmax probabilities by hand. Which token is most likely? What happens if you divide all scores by 2 (temperature=2.0)?
Exercise 4: Why Parallel?
If a sentence has 100 tokens, how many sequential steps does an RNN need? How many does a transformer need? What does this mean for GPU training?
Exercise 5: Multi-Head
If a transformer has 8 attention heads, each with d_k=64, what is the total dimension of the concatenated output? Why use multiple heads instead of one large head?
Try These BestWordz Tools
- Regex Tester — Practice pattern matching, analogous to attention patterns
- All BestWordz Tools — Explore the complete tool library
Continue Learning
- What Is an LLM? Beginner's Guide — The foundational concepts behind transformers
- How LLMs Generate Text — Tokens, probabilities, and next-token prediction
- Prompt Engineering Tutorial — How to write effective prompts for transformer-based models
- Context Engineering Explained — Controlling AI behavior through context
- How AI Coding Agents Work — Transformers as the brain of coding agents
- LLM Quantization Explained — Reducing model size while preserving quality
- RAG Architecture Explained — Extending transformer context with retrieval
Try the Regex Tester
Put what you've learned into practice with this free BestWordz tool.
💬 Discuss this topic
Have questions or insights about The Sequence Modeling Problem? Join the BestWordz Community.
Continue Learning: Prompt Engineering
Master the art of communicating with AI
- Free-Form vs Structured Output
- What Are Tokens?
- The Sequence Modeling Problem (this article)
- AI → Machine Learning → Deep Learning
- The 10-Stage CS Learning Roadmap
📚 Related Articles
AI → Machine Learning → Deep Learning
Key Takeaway A Large Language Model (LLM) is a neural network trained on massive text data to predi…
AI & Machine LearningThe Complete Pipeline
Key Takeaway LLMs generate text one token at a time through a repeating cycle: tokenize input → com…
CybersecurityWhat Are Tokens?
Key Takeaway Every LLM interaction has a finite context window — a fixed budget of tokens for both …
AI & Machine LearningWhat Are Embeddings?
Key Takeaway Embeddings convert text into numerical vectors where meaningful relationships become m…
CybersecurityThe 11-Stage AI Engineer Roadmap
AI engineering in 2026 is a distinct discipline requiring Python, machine learning, deep learning, …
CybersecurityThe 10-Stage Data Science Roadmap
Data science in 2026 spans far beyond machine learning. A complete data scientist needs Python, sta…
🔧 Related Tools
Regex Tester
Test regular expressions live: matches with positions, capture groups, and flag validation.
Try it now →HMAC-SHA256 Generator
Generate an HMAC-SHA256 signature from a key and message, entirely in your browser.
Try it now →HMAC-SHA512 Generator
Generate an HMAC-SHA512 signature from a key and message, entirely in your browser.
Try it now →Random Base64 Generator
Generate cryptographically secure random Base64 strings.
Try it now →💬 Discuss on BestWordz Community
Join the conversation about Neural Networks, LLMs, GPT on the BestWordz Community forum.
Visit Forum →