Generative AI & LLM

Module 1 of 16

Module 01: What Are LLMs? Architecture Intuition

8 min read1,416 words
What you'll learn
Trace the evolution of NLP from rule-based systems to transformersExplain the self-attention mechanism using intuitive analogiesDescribe how tokenization converts text into numbers LLMs can processDefine key LLM terminology: tokens, context window, temperature, top-p, and moreCompare the architecture approaches behind GPT, Claude, and Gemini

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:

EraApproachExampleLimitation
1950s–1990sRule-basedELIZA, grammar parsersBrittle, bad with ambiguity
2000s–2012StatisticalBag-of-words, TF-IDFThrew away order and nuance
2013–2017Neural (RNNs/LSTMs)Seq2seq, word2vecLong documents were painful
2017–presentTransformersGPT, BERT, Claude, GeminiToday’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 modelRNN-styleTransformer-style
ReadingOne token at a timeMany tokens in parallel layers
Long memoryDecays with distanceAttention links far-apart tokens
SpeedHarder to parallelizeMuch 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):

RolePlain 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 headMulti-head
One style of “who looks at whom”Several styles at once
SimplerRicher, 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-levelone tokenHuge vocab, unknown words hurt
Character-levelmany tiny tokensSuper long sequences
Subword (BPE-style)un + happiness (example)Sweet spot for many LLMs
SentencePiece-stylelanguage-friendly piecesUsed 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.
IdeaOne-liner
TokenBillable atom of text for the model
Context windowMax tokens the model can attend to in one request
TemperatureHigher → 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.

python
[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

FeatureGPT-4o (OpenAI)Claude 4 (Anthropic)Gemini 2.5 (Google)
ShapeDecoder-style transformer stackDecoder-style transformer stackOften MoE-style at scale (details vary by SKU)
ContextVery large (check docs)Very large (check docs)Very large / multimodal (check docs)
VibeStrong generalist + toolingLong docs, careful toneMultimodal + 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.

SettingIntuition
Low temperatureStick to likely continuations
High temperatureMore 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

TermWhat it meansWhy you care
TokenSmallest chunk the model reads/writesCost, speed, limits
Context windowMax tokens in one forward passWhat fits “in memory” of the call
TemperatureRandomness dial on samplingFact vs flair
Top-pLimit mass of considered tokensAlternative to cranking temperature
System promptHidden “job description” for the sessionShapes every answer
Fine-tuningExtra training on your dataWhen prompting isn’t enough
HallucinationConfident but wrongTrust and safety
RLHFHuman preference tuningWhy 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.

python
[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

LevelIdea
BeginnerTokenize the same idea in two languages; compare counts.
BeginnerWrite three prompts that only differ by temperature intent (factual vs creative).
IntermediateGiven a model window size, decide how you’d chunk a long PDF before calling the API.
AdvancedSame 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

Next Module: Prompt Engineering Mastery →