Chapter 1 of 40 · ~16 min read & lab+60 XP
Chapter 1 · Generative AI

What Is Generative AI & How Do LLMs Actually Work? (Next-Token Prediction From Zero)

The beginner-first blueprint of Generative AI: Discriminative vs. Generative models, the 4-stage Token → Transformer → Probabilities → Sampling loop, and Pretraining vs. Post-Training

What Is It?

Generative AI builds models (like Large Language Models and Diffusion models) that create brand-new text, code, images, or audio by learning the underlying probability distribution of real data—for LLMs, predicting one next token at a time.

Why Is It Required?

Classical discriminative ML only labels existing inputs (spam vs. ham, price = $420k); Generative AI unlocks open-ended reasoning, code generation, summarization, and multimodal creation.

Everyday Analogy: Like an autocomplete engine that read the entire internet, every textbook, and every GitHub repo—so well that predicting the next token forces it to learn grammar, math, and logic.
Why ML Engineers & Data Scientists Actually Need This

Understanding that an LLM is a next-token probability engine immediately demystifies hallucinations, context limits, prompt caching, and temperature.

ML / AI Engineer

Every production LLM optimization (KV-cache, speculative decoding, quantization, RAG) flows directly from the autoregressive token loop.

Data Scientist

Knowing when to use a 5ms classical classifier vs. a 500ms Generative LLM saves 100× in cloud bills.

Interview & Debug Edge

Opening question in almost every AI Engineer screen: 'Walk me through what physically happens inside an LLM from the moment a user sends a prompt to the first token appearing on screen.'

Step 0 · Test Your Gut Before Any Math!

When you send a 3-turn chat to an LLM API, how does the model 'remember' Turn 1 during Turn 3?

What You Will Master in This Chapter
  • Contrast Discriminative AI (predicts P(y | x)) vs. Generative AI (learns P(x) to sample new content).
  • Trace the exact 4-step LLM inference pipeline: Text → Token IDs → Transformer Logits → Next-Token Sampling.
  • Distinguish the 3 lifecycle stages of every modern LLM: Pretraining (base model), SFT (chat follower), and RL/DPO Alignment (helpful & safe assistant).
  • Understand why LLMs are stateless functions of their input prompt—not databases with fixed memory.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
P(wt∣w1,…,wt−1)P(w_t \mid w_1, \dots, w_{t-1})Say aloud:“Autoregressive next-token probability”
Plain-English Meaning
Probability of every vocabulary token being the next word given all previous tokens.
Everyday Example
Given 'The capital of France is', 'Paris' gets ~99.2% probability.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Strip away the hype and every Large Language Model (GPT, Gemini, Claude, Llama) runs one astonishingly simple loop: (1) Split text into token IDs, (2) Pass them through stacked Transformer layers, (3) Output a probability over 100,000+ vocabulary tokens, (4) Sample one token, append it, and repeat!

1. Discriminative vs. Generative AI

Everyday Story First (Zero Math Yet!)

Think of an art critic versus a painter: the critic looks at a painting and says 'Impressionist' (Discriminative); the painter picks up a brush and creates a brand-new painting (Generative).

PropertyClassical Discriminative MLGenerative AI (LLMs & Diffusion)
Math ObjectiveLearn boundary P(y∣x)P(y \mid x)Learn data distribution P(x)P(x) or P(x∣prompt)P(x \mid \text{prompt})
OutputLabel, probability, or scalar numberOpen-ended text, code, JSON, images, audio
ExamplesXGBoost fraud detector, Logistic RegressionGPT, Gemini, Claude, Llama, Flux, Veo
Latency / CostMicroseconds (CPU)100ms – 10s (GPU)

2. The 3 Training Stages of a Frontier LLM

  1. Pretraining (98% of compute): Next-token prediction across trillions of web, book, and code tokens → produces a raw Base Model (smart autocomplete, not yet a polite chatbot).
  2. Supervised Fine-Tuning (SFT): Train on curated (User, Assistant) dialogue pairs so the model learns to answer questions and follow instructions.
  3. Preference Alignment & Reasoning RL (DPO / RLHF / GRPO): Refine helpfulness, safety, and multi-step verification using human preferences and verifiable coding/math rewards.
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Subword tokens (typically ~¾ of an English word) handle rare words, code identifiers, and typos cleanly without needing a 10-million-word vocabulary. You'll explore BPE tokenization in the very next chapter!

Interactive Visual Lab
Lab Challenge: Watch how raw text becomes token IDs at the very first stage of the LLM pipeline.
Interactive Animation • 1.1 Deep Lab

Byte Pair Encoding (BPE) Iterative Compression Animator

Watch BPE greedily merge frequent adjacent pairs step-by-step, shrinking sequence length while growing the learned subword vocabulary.

Sequence Length: 11 tokens (from 11 bytes)Compression: 0% · Vocab: 256
n
e
u
r
a
l
_
n
e
t
s
0%
Step 0: Initial Bytes
Intuition Takeaway: Every LLM is a stateless next-token probability engine shaped by 3 stages (Pretraining → SFT → Alignment/RL) that generates coherent reasoning one appended token at a time.
Production NumPy & PyTorch Code Patterns
import numpy as np

# Toy Autoregressive Next-Token Generation Loop (How Every LLM Generates Text)
vocab = ["the", "cat", "sat", "on", "mat", "<EOS>"]
# Simplified transition logits: current_token -> next_token logits
TRANSITIONS = {
    "the": [0.0, 3.2, 0.1, 0.0, 2.8, -2.0],
    "cat": [0.0, -1.0, 4.0, 0.2, 0.0, -1.0],
    "sat": [0.0, -1.0, -1.0, 4.2, 0.0, -1.0],
    "on":  [3.5, 0.2, -1.0, -1.0, 2.0, -1.0],
    "mat": [-1.0, -1.0, -1.0, -1.0, -1.0, 5.0],
}

tokens = ["the", "cat"]
for _ in range(6):
    logits = np.array(TRANSITIONS[tokens[-1]])
    probs = np.exp(logits - logits.max())
    probs /= probs.sum()
    next_tok = vocab[int(np.argmax(probs))]  # greedy step
    if next_tok == "<EOS>":
        break
    tokens.append(next_tok)
print("Autoregressively generated:", " ".join(tokens))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Saying LLMs 'look up answers from an internal database of memorized web pages.'
Best Practice: LLMs compress statistical patterns into neural weights and synthesize tokens probabilistically—which is why they can generalize to brand-new code AND why they can hallucinate plausible-sounding falsehoods.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Which statement accurately describes how a chat LLM maintains context across a 5-turn conversation?

Apply What You Learned — Solve Matching Coding Problems