LLM Masterclass / Module 1 of 10 Phase 1: Foundations, Tokenization & Transformer Internals

History of Language Models — From Shannon N-Grams & RNNs to Transformers, Scaling Laws & Reasoning Models

26 min study + 2 Live Wasm Labs
⚡ Answer-First Executive Summary (TL;DR) Module 1 Key Takeaways
  • ✓ Before 2017, Recurrent Neural Networks (RNNs, LSTMs, GRUs) processed tokens sequentially (h_t = f(h_{t-1}, x_t)), preventing parallel GPU training across sequence positions and losing long-range context to vanishing gradients.
  • ✓ The June 2017 "Attention Is All You Need" paper replaced recurrence entirely with parallelizable Self-Attention, enabling direct O(1)-path-length information flow between any two tokens regardless of distance.
  • ✓ While early Transformers branched into Encoder-Only (BERT for embeddings/classification) and Encoder-Decoder (T5), Autoregressive Decoder-Only models (GPT, Claude, Gemini, Llama, DeepSeek) won the frontier scaling race due to causal next-token pre-training efficiency and emergent zero/few-shot in-context learning.
  • ✓ Two laws govern modern frontier LLMs: Chinchilla Pre-Training Scaling (C ≈ 6ND, balancing ~20 tokens per parameter) and Test-Time Compute Scaling (RL-trained reasoning chains in Claude Opus 5.5, GPT-6 Astra, and DeepSeek-R1).

01. The 5 Architectural Eras of Language Modeling (1948–2026)

Every language model—from Claude Shannon’s 1948 character Markov tables to 1-million-token 2026 Mixture-of-Experts reasoning systems—solves the exact same fundamental probability estimation problem: given a sequence of context tokens x₁, x₂, …, xₜ₋₁, estimate the conditional distribution over the next token P(xₜ | x₁, …, xₜ₋₁) so that the joint probability of a document factors via the chain rule:

P(x₁, …, xT) = ∏t=1..T P(xt | x<t)
Table 1.1 — 75-Year Evolution of Language Models & Architectural Bottlenecks
Era & Years Canonical Architectures Core Mathematical Formulation Why the Era Hit a Wall
1. Statistical N-Grams (1948–2002) Shannon Markov Chains, Kneser-Ney Smoothing, BM25 P(xt | xt-n+1:t-1) = Count(xt-n+1:t) / Count(xt-n+1:t-1) Combinatorial sparsity (|V|n parameter explosion) and zero semantic generalization across synonyms.
2. Dense Embeddings & RNNs (2003–2016) Bengio NPLM, Word2Vec (Skip-gram/CBOW), GloVe, LSTM, GRU, Seq2Seq + Bahdanau Attention ht = tanh(Whh ht-1 + Wxh e(xt)) Sequential O(T) recurrence prevented parallel GPU training across tokens; information bottleneck compressing long prefixes into one fixed vector ht.
3. Early Transformers (2017–2019) Vaswani Transformer (2017), BERT (Encoder), T5 (Enc-Dec), GPT-1 & GPT-2 (Decoder) Attention(Q,K,V) = softmax(QKT / √dk) V O(T²) attention matrix memory and lack of instruction alignment (base models completed text rather than following user intent).
4. Scaling Laws & RLHF Alignment (2020–2023) GPT-3 (175B), InstructGPT, Chinchilla (70B), GPT-4, Claude 2, LLaMA 1 & 2 C ≈ 6ND, SFT + RLHF (PPO) + FlashAttention + GQA Dense parameter activation cost (100% weights active per token) and single-pass System-1 surface reasoning on hard math/code.
5. Sparse MoE, Multimodal & Reasoning (2024–2026) Claude Opus 5.5, GPT-6 Astra/Sol, Gemini 3.8, Llama 4 Maverick/Scout, DeepSeek-V3/R1, Qwen 3.8 Fine-grained MoE + MLA/GQA + GRPO Test-Time RLVR + 1M–10M context Current frontier: balancing inference FinOps ($/task), memory bandwidth, and verifiable agentic tool execution.

02. Transformer Taxonomy: Encoder-Only vs. Encoder-Decoder vs. Causal Decoder-Only

1. Encoder-Only (Bidirectional)
Examples: BERT, RoBERTa, DeBERTa, ModernBERT, BGE, ColPali

Every token attends to both left and right context simultaneously. Trained via Masked Language Modeling (MLM). Today’s gold standard for RAG dense/sparse vector embeddings, cross-encoder rerankers, and sub-5ms PII/toxicity classifiers.

2. Encoder-Decoder (Seq2Seq)
Examples: Original 2017 Transformer, T5, Flan-T5, BART, Whisper

A bidirectional Encoder compresses the input sequence, and a causal Decoder attends via Cross-Attention. Still widely used in Speech-to-Text (Whisper) and specialized translation encoders.

3. Decoder-Only (Causal Autoregressive)
Examples: GPT-6, Claude 5.5, Gemini 3.8, Llama 4, Qwen 3.8, DeepSeek

Uses a lower-triangular causal mask (Mij = -∞ for j > i) so token i only attends to prefix j ≤ i. Trains on 100% of tokens in parallel during pre-training and reuses past token states via the KV Cache during generation.

03. The End-to-End 4-Stage Frontier LLM Training Pipeline

┌────────────────────────────────────────────────────────────────────────────────────────┐
│ STAGE 1: SELF-SUPERVISED PRE-TRAINING (98% of Compute FLOPs • 10T–20T Tokens)          │
│   • Next-Token Causal Cross-Entropy over Web, Code, Math & Synthetic Textbooks         │
│   • Output: Base Foundation Model (High world knowledge, zero instruction following)   │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ STAGE 2: LONG-CONTEXT EXTENSION & ANNEALING (100B–500B High-Quality Tokens)            │
│   • RoPE Base Frequency Scaling (ABF / YaRN) from 8K ──▶ 128K ──▶ 1M–10M Context       │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ STAGE 3: SUPERVISED FINE-TUNING / SFT (100K–2M Curated Multi-Turn Trajectories)        │
│   • ChatML formatting, tool-call schemas, coding traces (Assistant-only loss masking)  │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ STAGE 4: PREFERENCE & REASONING ALIGNMENT (DPO / RLHF / GRPO Verifiable Rewards)       │
│   • Aligns helpfulness/safety (DPO/PPO) + trains test-time Chain-of-Thought (GRPO)     │
└────────────────────────────────────────────────────────────────────────────────────────┘

💻 Hands-On WebAssembly LLM Engineering Labs (Module 1)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 1.1: Chinchilla Compute-Optimal Scaling Law & Over-Training FinOps Simulator

Run this live Python script to calculate exact pre-training FLOPs (C ≈ 6ND), H100/B200 GPU-hours, Chinchilla-optimal parameter/token ratios, and why Llama-4/Qwen-3 intentionally over-train compact models.

import math

def analyze_llm_training_run(name: str, params_b: float, tokens_t: float, active_params_b: float | None = None):
    # For Sparse MoE models, FLOPs per token depend on ACTIVE parameters per forward/backward pass!
    eff_b = active_params_b if active_params_b is not None else params_b
    n_params = eff_b * 1e9
    d_tokens = tokens_t * 1e12

    # Fundamental Transformer Pre-Training Compute Equation: C ≈ 6 * N_active * D
    total_flops = 6.0 * n_params * d_tokens
    tokens_per_total_param = d_tokens / (params_b * 1e9)

    # H100 SXM5 sustained BF16 throughput at ~45% MFU (Model FLOPs Utilization) ≈ 445 TFLOP/s
    h100_sustained_flops = 989e12 * 0.45
    h100_gpu_hours = total_flops / (h100_sustained_flops * 3600)

    print(f"Model: {name:<26} | Total={params_b:>5.1f}B (Active={eff_b:>4.1f}B) | Data={tokens_t:>5.1f}T tokens")
    print(f"  • Compute Budget (6ND):   {total_flops:.2e} FLOPs")
    print(f"  • Tokens / Total Param:   {tokens_per_total_param:>6.1f} tok/param (Chinchilla baseline = 20.0)")
    print(f"  • Cluster Cost Estimate:  {h100_gpu_hours:>10,.0f} H100 GPU-Hours")
    print("-" * 78)

print("CHINCHILLA SCALING LAWS vs. MODERN OVER-TRAINED & SPARSE MoE FRONTIER RUNS")
print("=" * 78)
analyze_llm_training_run("GPT-3 (2020 Undertrained)", params_b=175.0, tokens_t=0.3)
analyze_llm_training_run("Chinchilla (2022 Optimal)", params_b=70.0, tokens_t=1.4)
analyze_llm_training_run("Llama-3 8B (2024 Overtrained)", params_b=8.0, tokens_t=15.0)
analyze_llm_training_run("DeepSeek-V3 / Llama-4 MoE", params_b=400.0, tokens_t=15.0, active_params_b=17.0)
▶ Interactive Wasm Lab

Lab 1.2: Why N-Grams & Fixed-Window Markov Models Fail Long-Range Context vs. Attention

Execute a live side-by-side experiment showing how a Bigram/Trigram Markov chain loses subject-verb agreement across clauses while Attention scores link arbitrary token positions directly.

from collections import defaultdict
import math

corpus = [
    "the autonomous agent that queried the remote mcp database servers returned valid json",
    "the autonomous agents that queried the remote mcp database server returned valid schemas",
]

# 1. Build a Bigram Markov Model: P(w_t | w_{t-1})
bigram_counts = defaultdict(lambda: defaultdict(int))
for doc in corpus:
    words = doc.split()
    for w1, w2 in zip(words, words[1:]):
        bigram_counts[w1][w2] += 1

print("[1] Bigram Local Window Limitation (Only sees immediate predecessor 'server(s)'):")
for prev_word in ["server", "servers"]:
    next_dist = dict(bigram_counts[prev_word])
    print(f"    After {prev_word!r:<9} -> Bigram next-token counts: {next_dist}")

# 2. Simulated Self-Attention Query-Key Alignment over Long Distance
# Notice how 'returned' (verb at pos 10) attends directly back to subject 'agent' (pos 2)
tokens = ["the", "autonomous", "agent", "that", "queried", "the", "remote", "mcp", "database", "returned"]
# Synthetic 3D embeddings [syntax_noun_subject, clause_modifier, verb_target]
embeddings = {
    "agent":    [0.95, 0.10, 0.90],
    "database": [0.20, 0.85, 0.15],
    "returned": [0.92, 0.05, 0.94],
}

def dot(u, v):
    return sum(a * b for a, b in zip(u, v)) / math.sqrt(len(u))

q_verb = embeddings["returned"]
score_subject = dot(q_verb, embeddings["agent"])
score_distractor = dot(q_verb, embeddings["database"])
w_subj = math.exp(score_subject) / (math.exp(score_subject) + math.exp(score_distractor))
w_dist = 1.0 - w_subj

print("\n[2] Direct O(1)-Path Self-Attention Alignment (Distance = 8 tokens apart):")
print(f"    Attention('returned' -> 'agent' [True Subject]):      {w_subj:.1%}")
print(f"    Attention('returned' -> 'database' [Local Noun]):     {w_dist:.1%}")

Frequently Asked Staff LLM Interview Questions (Module 1)

Why did Decoder-Only Transformers (GPT/Llama/Claude) beat Encoder-Only (BERT) and Encoder-Decoder (T5) architectures at scale? ▸

Encoder-only Masked Language Models (BERT) only compute loss on ~15% of masked tokens per forward pass and cannot naturally generate free-form text. Decoder-only causal models compute next-token prediction loss on 100% of sequence tokens simultaneously via a causal lower-triangular mask, unify pre-training and generation into a single interface, and cache past Key/Value states cleanly during autoregressive inference.

What is the Chinchilla Scaling Law (Hoffmann et al., 2022) and how did it change LLM training? ▸

Early scaling laws (Kaplan et al., 2020) scaled model parameters N much faster than training tokens D (e.g., 175B GPT-3 was trained on only 300B tokens). DeepMind’s Chinchilla paper proved that for a fixed compute budget C ≈ 6ND FLOPs, parameters N and dataset tokens D should scale in equal proportion (~20 tokens per parameter)—And modern open-weight models (Llama 3/4, Qwen 3) push even further to 100–200+ tokens/param ("over-training") to minimize downstream inference VRAM.

What changed in 2024–2026 with Test-Time Compute Scaling and Reasoning Models? ▸

Instead of relying purely on larger pre-training clusters, frontier models (OpenAI o1/o3/GPT-6 Astra, DeepSeek-R1, Claude Opus 5.5) use Reinforcement Learning with Verifiable Rewards (RLVR / GRPO) to allocate variable "thinking tokens" at inference time—searching, backtracking, and self-verifying before emitting the final response.