AI & Machine Learning

The Sequence Modeling Problem

Neural Networks LLMs GPT BERT RAG Prompt Engineering AI Agents Classification Transformers Embeddings Vector Search Quantization LLaMA
1,721 words
Transformers tutorial showing self-attention weights for 'The cat sat on the mat', transformer block architecture, RNN vs Transformer comparison, and encoder vs decoder diagram
📌 Key Takeaway

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


1. The Sequence Modeling Problem

Language is sequential. The meaning of a word depends on the words around it:

"The cat sat on the mat"

• "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:

  1. Slow training: Cannot parallelize — must wait for token 1 before processing token 2
  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.

TOKEN EMBEDDINGS (4-dimensional):

"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."

POSITIONAL ENCODING (simplified sinusoidal):

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?"

Analogy: Library Research

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:

VectorRoleAnalogy
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.

Q, K, V FOR OUR EXAMPLE:

"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

ATTENTION(Q, K, V) = softmax(Q·KT / √dk) · V

Step by step:

  1. Q·KT — Compute dot product of every query with every key → raw attention scores
  2. / √dk — Scale by the square root of the key dimension (prevents large values)
  3. softmax — Convert scores to probabilities (sum to 1.0)
  4. · 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):

Thecatsatonthemat
The0.3730.6320.5470.3980.3950.606
cat0.5240.9020.8870.6330.5650.911
sat0.3910.6760.6990.4950.4240.698
on0.3980.6720.5700.4170.4200.639
the0.3690.6280.5670.4100.3920.612
mat0.5770.9820.8800.6370.6140.954

After Softmax → Attention Weights

Thecatsatonthemat
The14.7%19.1%17.5%15.1%15.0%18.6%
cat13.3%19.4%19.1%14.8%13.8%19.6%
sat13.9%18.5%18.9%15.4%14.4%18.9%
on14.7%19.3%17.4%14.9%15.0%18.7%
the14.6%18.9%17.8%15.2%14.9%18.6%
mat13.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:

WHY MULTIPLE HEADS?

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:

Input
  
┌──────────────────────────────┐
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:

TypeArchitectureAttentionExamplesBest For
Encoder-onlyReads input bidirectionallySelf-attention (full)BERT, RoBERTaClassification, NER, embeddings
Decoder-onlyGenerates left-to-rightMasked self-attentionGPT, Claude, LlamaText generation, chat, code
Encoder-DecoderReads input, generates outputSelf + cross-attentionT5, BARTTranslation, 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

FeatureRNN (1986)LSTM (1997)Transformer (2017)
ProcessingSequential (one at a time)Sequential (one at a time)Parallel (all at once)
Long-rangePoor (vanishing gradients)Better (gated memory)Excellent (direct attention)
Training speedSlow (no parallelism)Slow (no parallelism)Fast (GPU-friendly)
Max practical length~100 tokens~500 tokens128K+ tokens
ScalabilityLimitedLimitedScales to billions of params
Why Transformers won:

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"?
Because each token attends to other tokens within the same sequence. It is "self" because the queries, keys, and values all come from the same input. Cross-attention, by contrast, uses queries from one sequence and keys/values from another (e.g., decoder attending to encoder output).
Why divide by √d_k?
Without scaling, dot products grow large with high-dimensional vectors, pushing softmax into regions with extremely small gradients. Dividing by √d_k keeps the variance stable and gradients healthy.
What does "attention" actually learn?
Different attention heads learn different relationships: syntactic (subject-verb), semantic (similar meanings), positional (adjacent tokens), and long-range (reference resolution). The model learns these patterns automatically during training.
Why can't RNNs handle long sequences?
RNNs compress the entire history into a single fixed-size vector. As sequences grow, early information is overwritten by newer tokens (vanishing gradient problem). LSTMs mitigate this with gates but still process sequentially.
What is positional encoding?
Since transformers process all tokens simultaneously, they need an explicit way to know token order. Positional encoding adds position-dependent vectors to embeddings, typically using sine/cosine functions at different frequencies.
What is masked self-attention?
In decoder-only models (GPT), each token can only attend to previous tokens — future tokens are masked. This prevents the model from "cheating" by seeing the answer during training. It forces the model to predict the next token using only past context.
How many transformer layers do modern models have?
GPT-3 has 96 layers. Llama 3 70B has 80 layers. BERT-base has 12 layers. More layers allow more complex pattern recognition but increase compute cost.

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

Continue Learning

Try the Regex Tester

Put what you've learned into practice with this free BestWordz tool.

Open Tool →

Continue Learning: Prompt Engineering

Master the art of communicating with AI

  1. Free-Form vs Structured Output
  2. What Are Tokens?
  3. The Sequence Modeling Problem (this article)
  4. AI → Machine Learning → Deep Learning
  5. The 10-Stage CS Learning Roadmap

💬 Discuss on BestWordz Community

Join the conversation about Neural Networks, LLMs, GPT on the BestWordz Community forum.

Visit Forum →