Duration: 3 hours | Difficulty: Beginner | Prerequisites: Basic Python
Learning Objectives
By the end of this module, you will be able to:
- Trace the evolution of NLP from rule-based systems to transformers
- Explain the self-attention mechanism using intuitive analogies
- Describe how tokenization converts text into numbers LLMs can process
- Define key LLM terminology: tokens, context window, temperature, top-p, and more
- Compare the architecture approaches behind GPT, Claude, and Gemini
1. The Journey to Large Language Models
From Rules to Intelligence
Picture teaching someone language by immersion instead of handing them a giant rulebook. Classical NLP was mostly the rulebook; modern LLMs are closer to immersion—they pick up patterns from huge amounts of text.
The evolution in four acts:
| Era | Approach | Example | Limitation |
|---|---|---|---|
| 1950s–1990s | Rule-based | ELIZA, grammar parsers | Brittle, bad with ambiguity |
| 2000s–2012 | Statistical | Bag-of-words, TF-IDF | Threw away order and nuance |
| 2013–2017 | Neural (RNNs/LSTMs) | Seq2seq, word2vec | Long documents were painful |
| 2017–present | Transformers | GPT, BERT, Claude, Gemini | Today’s default |
Concept: A transformer looks at many positions at once (with attention) instead of chewing text strictly left-to-right like an old RNN.
Why RNNs Struggled
RNNs read like a human reading a novel one word at a time while trying to remember everything from page 1. By chapter 3, early details fade—that’s the vanishing gradient story in plain clothes. LSTMs added a scratchpad, but very long context still hurt.
The Transformer Idea (2017)
The “Attention Is All You Need” paper flipped the script: instead of a strict line, the model can relate each word to every other word in one go—like zooming out to see the whole paragraph when resolving what “it” refers to.
| Mental model | RNN-style | Transformer-style |
|---|---|---|
| Reading | One token at a time | Many tokens in parallel layers |
| Long memory | Decays with distance | Attention links far-apart tokens |
| Speed | Harder to parallelize | Much more parallel in practice |
Fun Fact: The name “transformer” sounds sci-fi, but the core idea is “compare everything to everything (smartly), then mix information”—not magic, just very large math.
Try This! In one sentence, explain to a friend why “the cat sat on the mat” needs the model to connect “it” to “cat” without rereading the whole sentence five times. That’s the user story behind attention.
2. The Self-Attention Mechanism
The Cocktail Party Analogy
At a noisy party, when someone says “it,” your brain boosts the relevant voices and dims the rest. In “The cat sat on the mat because it was tired,” you lean toward cat, not mat. Self-attention is that focusing mechanism, learned from data.
How Attention Works (Simplified)
For each token, the model forms three roles (implemented as learned projections in real systems):
| Role | Plain question |
|---|---|
| Query (Q) | What am I looking for? |
| Key (K) | What do I advertise about myself? |
| Value (V) | What information do I contribute if picked? |
Scores come from comparing queries and keys; high scores mean “listen here more.” Outputs are weighted mixes of values.
Multi-Head Attention
One head might care about grammar links; another about meaning; another about position-like patterns. Multi-head just means many parallel attention patterns that later get combined—like several specialists glancing at the same sentence for different reasons.
| Single head | Multi-head |
|---|---|
| One style of “who looks at whom” | Several styles at once |
| Simpler | Richer, heavier compute |
Key Takeaway
Self-attention is how the model decides which words should strongly influence each other for the next layer’s representation.
3. Tokenization: Turning Text into Numbers
Why Tokenization Matters
The model never sees “hello”—it sees token IDs. Tokenization is the bridge: text → pieces → integers.
Think of subwords like Lego bricks: common words might be one brick; rare or long words split into a few bricks so the vocabulary stays manageable.
Types of Tokenization
| Method | “unhappiness” might become… | Vibe |
|---|---|---|
| Word-level | one token | Huge vocab, unknown words hurt |
| Character-level | many tiny tokens | Super long sequences |
| Subword (BPE-style) | un + happiness (example) | Sweet spot for many LLMs |
| SentencePiece-style | language-friendly pieces | Used in several open models |
Fun Fact: The same sentence in different languages often uses different token counts—so multilingual apps can see different costs for the “same” idea.
Token Economics (No Code Needed)
- APIs usually bill by tokens, not characters.
- A context window is “how many tokens fit in one shot.”
- Shorter prompts (without losing intent) = lower cost and latency.
| Idea | One-liner |
|---|---|
| Token | Billable atom of text for the model |
| Context window | Max tokens the model can attend to in one request |
| Temperature | Higher → more random completions; lower → more deterministic |
Try This! Open your provider’s tokenizer playground (if available) and paste a paragraph of code plus a paragraph of prose. Notice how punctuation and symbols chew tokens differently.
Key Example: See how one sentence becomes a short list of token IDs and how each ID maps back to a text piece.
[object Object], tiktoken
enc = tiktoken.encoding_for_model(,[object Object],)
text = ,[object Object],
tokens = enc.encode(text)
,[object Object],(,[object Object],)
,[object Object], token_id ,[object Object], tokens:
,[object Object],(,[object Object],)4. How GPT, Claude, and Gemini Work
The Transformer Architecture Stack
Same rough story for many chat models: tokens in → embeddings → many transformer blocks → prediction head that scores next token (decoder-style stacks).
┌─────────────────────────────────┐
│ Output Layer │ ← scores over vocabulary
├─────────────────────────────────┤
│ Transformer Block × N │ ← attention + feed-forward
├─────────────────────────────────┤
│ Positional Encoding │ ← order information
├─────────────────────────────────┤
│ Token Embedding Layer │ ← IDs → vectors
├─────────────────────────────────┤
│ Tokenizer │ ← text → token IDs
└─────────────────────────────────┘Model Comparison
| Feature | GPT-4o (OpenAI) | Claude 4 (Anthropic) | Gemini 2.5 (Google) |
|---|---|---|---|
| Shape | Decoder-style transformer stack | Decoder-style transformer stack | Often MoE-style at scale (details vary by SKU) |
| Context | Very large (check docs) | Very large (check docs) | Very large / multimodal (check docs) |
| Vibe | Strong generalist + tooling | Long docs, careful tone | Multimodal + Google ecosystem |
Exact numbers change—always check current provider docs before you budget.
The Generation Process: Next-Token Prediction
Under the hood, the model repeatedly asks: given everything so far, what token comes next? Sampling settings (temperature, top-p) reshape which high-scoring tokens actually get picked—like choosing whether the “dice” are biased toward safe choices or exploratory ones.
| Setting | Intuition |
|---|---|
| Low temperature | Stick to likely continuations |
| High temperature | More surprise, more risk |
| Top-p (nucleus) | Ignore the long tail of absurd tokens |
Key Takeaway
Chat models are fancy next-token engines with a stack of attention layers; “creativity” is mostly controlled sampling, not a separate soul.
5. Key Terminology Reference
| Term | What it means | Why you care |
|---|---|---|
| Token | Smallest chunk the model reads/writes | Cost, speed, limits |
| Context window | Max tokens in one forward pass | What fits “in memory” of the call |
| Temperature | Randomness dial on sampling | Fact vs flair |
| Top-p | Limit mass of considered tokens | Alternative to cranking temperature |
| System prompt | Hidden “job description” for the session | Shapes every answer |
| Fine-tuning | Extra training on your data | When prompting isn’t enough |
| Hallucination | Confident but wrong | Trust and safety |
| RLHF | Human preference tuning | Why assistants feel “aligned” |
Fun Fact: “Hallucination” is a cute metaphor, but operationally it’s mismatch between statistical fluency and truth—that’s why retrieval and verification matter in prod.
6. Seeing It in Action: Your First LLM API Call
Key Example: This shows the usual chat shape: roles (
system/user), a model name, and usage metadata you’ll use for cost tracking.
[object Object], openai ,[object Object], OpenAI
client = OpenAI(api_key=,[object Object],) ,[object Object],
response = client.chat.completions.create(
model=,[object Object],,
messages=[
{,[object Object],: ,[object Object],, ,[object Object],: ,[object Object],},
{,[object Object],: ,[object Object],, ,[object Object],: ,[object Object],}
],
temperature=,[object Object],,
max_tokens=,[object Object],,
)
,[object Object],(response.choices[,[object Object],].message.content)
,[object Object],(,[object Object],)
,[object Object],(,[object Object],)Practice Exercises
| Level | Idea |
|---|---|
| Beginner | Tokenize the same idea in two languages; compare counts. |
| Beginner | Write three prompts that only differ by temperature intent (factual vs creative). |
| Intermediate | Given a model window size, decide how you’d chunk a long PDF before calling the API. |
| Advanced | Same prompt to two providers; compare latency, cost, and failure modes. |
Mini-Project: Build an LLM Knowledge Card Generator
Build a small script that: (1) accepts a concept name, (2) asks an LLM for a JSON card (definition, analogy, bullets, misconceptions), (3) prints token usage, (4) saves Markdown. No need for fancy UI—CLI is enough.
Try This! Add a second step where the model critiques its own card for missing caveats—then you merge by hand.
Key Takeaways
Key Takeaway
- LLMs are next-token predictors trained on huge text—not hand-written rule engines.
- Attention is how they focus on the right words when context gets wide.
- Tokens drive cost and limits; always measure before you ship.
- Temperature / top-p trade off safety vs variety.
- Big chat models share a transformer-shaped core but differ by data, alignment, and product packaging.
Resources for Further Learning
- Attention Is All You Need — Foundational transformer paper
- The Illustrated Transformer — Visual walkthrough
- OpenAI Tokenizer Tool — Interactive tokens
- 3Blue1Brown: But what is a GPT?
- Andrej Karpathy: Let's build GPT
- Hugging Face NLP Course