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
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.
Classical discriminative ML only labels existing inputs (spam vs. ham, price = $420k); Generative AI unlocks open-ended reasoning, code generation, summarization, and multimodal creation.
Understanding that an LLM is a next-token probability engine immediately demystifies hallucinations, context limits, prompt caching, and temperature.
Every production LLM optimization (KV-cache, speculative decoding, quantization, RAG) flows directly from the autoregressive token loop.
Knowing when to use a 5ms classical classifier vs. a 500ms Generative LLM saves 100× in cloud bills.
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.'
When you send a 3-turn chat to an LLM API, how does the model 'remember' Turn 1 during Turn 3?
- 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.
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
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).
| Property | Classical Discriminative ML | Generative AI (LLMs & Diffusion) |
|---|---|---|
| Math Objective | Learn boundary | Learn data distribution or |
| Output | Label, probability, or scalar number | Open-ended text, code, JSON, images, audio |
| Examples | XGBoost fraud detector, Logistic Regression | GPT, Gemini, Claude, Llama, Flux, Veo |
| Latency / Cost | Microseconds (CPU) | 100ms – 10s (GPU) |
2. The 3 Training Stages of a Frontier LLM
- 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).
- Supervised Fine-Tuning (SFT): Train on curated
(User, Assistant)dialogue pairs so the model learns to answer questions and follow instructions. - Preference Alignment & Reasoning RL (DPO / RLHF / GRPO): Refine helpfulness, safety, and multi-step verification using human preferences and verifiable coding/math rewards.
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!
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.
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))