LLM // 101 AI & Transformers From Scratch
First-Principles Engineering Guide

How AI & Large Language Models Work From Scratch

A complete, self-contained developer manual explaining how neural networks learn language—from statistical next-token prediction and Byte-Pair Encoding to causal self-attention, PyTorch implementation, and RLHF/DPO alignment.

Prerequisites: Basic Python & High School Algebra Stack: Pure Python, NumPy, PyTorch Includes: 4 Interactive Labs + Runnable Micro-GPT + Training Corpus
Module 01 // Foundations

How AI Learns: From Rules to Next-Token Prediction

Traditional software relies on explicit human-written rules (if condition: do_action). Artificial Intelligence flips this paradigm: instead of programming rules, we feed an algorithm vast amounts of data and let it optimize mathematical parameters (weights) to minimize prediction errors.

At their core, Large Language Models (LLMs) such as GPT, Claude, and Llama solve one deceptively simple task: autoregressive next-token prediction. Given a sequence of tokens x1, x2, ..., xt, the model outputs a probability distribution over its entire vocabulary for what comes next: P(xt+1 | x1, ..., xt).

Why Next-Token Prediction Creates Intelligence: To accurately predict the next word in a textbook, Python script, or legal contract, a model cannot rely on shallow memorization. Compressing trillions of words into billions of weights forces the network to learn grammar, world facts, code syntax, and logical reasoning.

Interactive Lab 1: N-Gram Probability Explorer

Before neural networks, language models used Markov chains (bigrams and trigrams)—counting how often word B follows word A in a training corpus. Test how context length sharpens predictions below:

Next-Word Probability Distribution LIVE IN BROWSER

From Counting to Neural Networks

N-gram tables fail when encountering unseen phrases because they treat words as isolated symbols. Neural networks solve this by projecting words into continuous geometric space and updating weights via Gradient Descent using Cross-Entropy Loss:

bigram_neural_step.py — Minimal Neural Next-Token Loss in NumPy
import numpy as np

# Vocabulary: 4 tokens -> ["ai", "learns", "from", "data"]
vocab_size = 4
# Weight matrix W acts as a lookup table of next-token logits (4x4)
rng = np.random.default_rng(42)
W = rng.normal(0, 0.1, size=(vocab_size, vocab_size))

def softmax(logits):
    exp_x = np.exp(logits - np.max(logits))
    return exp_x / np.sum(exp_x)

# Training example: input token 0 ("ai") -> target token 1 ("learns")
x_idx, target_idx = 0, 1
lr = 0.5

for step in range(5):
    logits = W[x_idx]                     # Forward pass: fetch row 0
    probs = softmax(logits)               # Convert raw scores to probabilities
    loss = -np.log(probs[target_idx])     # Cross-entropy loss

    # Backward pass: gradient of cross-entropy + softmax is (probs - one_hot_target)
    grad = probs.copy()
    grad[target_idx] -= 1.0
    W[x_idx] -= lr * grad                 # Gradient descent weight update

    print(f"Step {step+1} | P('learns' | 'ai') = {probs[target_idx]:.4f} | Loss = {loss:.4f}")
Module 02 // Representation

Tokenization & Vector Embeddings

Neural networks cannot multiply text strings—they only operate on floating-point tensors. Converting raw text into numerical representations requires two steps: Tokenization and Embedding.

  • Subword Tokenization (BPE): Character-level vocabularies are too short (sequences become overly long), while word-level vocabularies explode in size and fail on typos. Modern LLMs use Byte-Pair Encoding (BPE) to split text into common subwords (e.g., "token" + "ization"), typically yielding a vocabulary of 32,000 to 128,000 tokens.
  • Dense Embeddings: Each token ID looks up a row in an embedding matrix E of shape (vocab_size, d_model). Similar concepts cluster together in this high-dimensional space, enabling semantic arithmetic (e.g., king − man + woman ≈ queen).
  • Positional Encoding: Because transformers process all tokens simultaneously rather than sequentially, we add positional vectors so the model distinguishes "dog bites man" from "man bites dog".

Interactive Lab 2: Live Subword Tokenizer & Cosine Similarity

Type any sentence below to see how a subword tokenizer splits text into token IDs, and click any word in our built-in embedding space to inspect its nearest semantic neighbors via Cosine Similarity:

Subword Tokenizer & Embedding Inspector INTERACTIVE
bpe_tokenizer.py — Minimal Byte-Pair Encoding (BPE) Trainer in Python
from collections import Counter

def get_stats(ids):
    """Count frequency of adjacent token pairs."""
    return Counter(zip(ids, ids[1:]))

def merge_pair(ids, pair, new_id):
    """Replace all occurrences of `pair` with `new_id`."""
    merged = []
    i = 0
    while i < len(ids):
        if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
            merged.append(new_id)
            i += 2
        else:
            merged.append(ids[i])
            i += 1
    return merged

text = "low lower lowest newer wider"
tokens = list(text.encode("utf-8"))  # Start with raw UTF-8 bytes (0..255)
merges = {}

for step in range(5):
    stats = get_stats(tokens)
    top_pair = max(stats, key=stats.get)
    new_token_id = 256 + step
    tokens = merge_pair(tokens, top_pair, new_token_id)
    merges[top_pair] = new_token_id
    print(f"Merge {step+1}: {top_pair} -> ID {new_token_id} (count={stats[top_pair]})")
Module 03 // Core Architecture

Self-Attention & The Transformer Architecture

Introduced in "Attention Is All You Need" (2017), the Transformer replaced slow sequential Recurrent Neural Networks (RNNs) with Scaled Dot-Product Self-Attention. Self-attention lets every token look back at earlier tokens to gather contextual meaning—for example, resolving what "it" refers to in "The robot stopped because it ran out of battery."

Queries (Q), Keys (K), and Values (V)

Each token embedding x is multiplied by three learned weight matrices to produce three vectors:

  • Query (Q): What information am I currently looking for?
  • Key (K): What information do I contain that others might search for?
  • Value (V): What content do I actually pass forward if selected?

We compute compatibility scores via dot products, divide by √dk to keep gradients stable, apply a Causal Mask (setting future positions to -∞ so tokens cannot cheat by peeking ahead), and normalize with Softmax:

Attention(Q, K, V) = softmax( (Q · KT) / √dk + CausalMask ) · V

Interactive Lab 3: Causal Self-Attention Heatmap

Click any token in the sentence below to inspect its causal attention weights. Notice how future tokens are strictly masked out (0.00), while earlier relevant words receive high attention weights:

Causal Attention Weight Inspector CLICK A TOKEN
Module 04 // Implementation

Complete From-Scratch PyTorch Micro-GPT & Sample Data

Below is a complete, self-contained, runnable PyTorch implementation of a decoder-only GPT language model. It includes character/subword tokenization, Causal Self-Attention, Multi-Head Attention, Feed-Forward MLP blocks, Residual Connections, LayerNorm, the AdamW training loop, and autoregressive generation.

ai_corpus.txt — Built-in Sample Training Dataset
Artificial intelligence learns patterns from data using mathematical optimization.
Neural networks transform input tokens into dense vector embeddings.
Self-attention computes query, key, and value projections for every token.
Causal masking prevents a language model from seeing future tokens during training.
Transformers stack multi-head attention and feed-forward layers with residual paths.
Gradient descent updates model weights to minimize cross-entropy prediction loss.
Pretraining builds broad knowledge, while fine-tuning aligns behavior with human intent.
micro_gpt.py — Complete Runnable GPT Model From Scratch (PyTorch)
import torch
import torch.nn as nn
import torch.nn.functional as F

# 1. Hyperparameters
torch.manual_seed(1337)
batch_size = 16
block_size = 48       # Maximum context window length
max_iters = 600
eval_interval = 150
learning_rate = 3e-3
device = "cuda" if torch.cuda.is_available() else "cpu"
n_embd = 64           # Embedding dimension (d_model)
n_head = 4            # Number of attention heads (head_size = 64 / 4 = 16)
n_layer = 3           # Number of Transformer blocks
dropout = 0.1

# 2. Training Corpus & Character-Level Tokenizer
corpus = """Artificial intelligence learns patterns from data using mathematical optimization.
Neural networks transform input tokens into dense vector embeddings.
Self-attention computes query, key, and value projections for every token.
Causal masking prevents a language model from seeing future tokens during training.
Transformers stack multi-head attention and feed-forward layers with residual paths.
Gradient descent updates model weights to minimize cross-entropy prediction loss.
Pretraining builds broad knowledge, while fine-tuning aligns behavior with human intent.\n""" * 20

chars = sorted(list(set(corpus)))
vocab_size = len(chars)
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for i, ch in enumerate(chars)}
encode = lambda s: [stoi[c] for c in s]
decode = lambda l: "".join([itos[i] for i in l])

data = torch.tensor(encode(corpus), dtype=torch.long)
n = int(0.9 * len(data))
train_data, val_data = data[:n], data[n:]

def get_batch(split):
    src = train_data if split == "train" else val_data
    ix = torch.randint(len(src) - block_size, (batch_size,))
    x = torch.stack([src[i : i + block_size] for i in ix])
    y = torch.stack([src[i + 1 : i + block_size + 1] for i in ix])
    return x.to(device), y.to(device)

# 3. Causal Self-Attention Head
class Head(nn.Module):
    def __init__(self, head_size):
        super().__init__()
        self.key = nn.Linear(n_embd, head_size, bias=False)
        self.query = nn.Linear(n_embd, head_size, bias=False)
        self.value = nn.Linear(n_embd, head_size, bias=False)
        self.register_buffer("tril", torch.tril(torch.ones(block_size, block_size)))
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        B, T, C = x.shape
        k = self.key(x)    # (B, T, head_size)
        q = self.query(x)  # (B, T, head_size)
        wei = q @ k.transpose(-2, -1) * (k.shape[-1] ** -0.5)
        wei = wei.masked_fill(self.tril[:T, :T] == 0, float("-inf"))
        wei = F.softmax(wei, dim=-1)
        wei = self.dropout(wei)
        v = self.value(x)
        return wei @ v

# 4. Multi-Head Attention & Transformer Block
class MultiHeadAttention(nn.Module):
    def __init__(self, num_heads, head_size):
        super().__init__()
        self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
        self.proj = nn.Linear(head_size * num_heads, n_embd)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        out = torch.cat([h(x) for h in self.heads], dim=-1)
        return self.dropout(self.proj(out))

class FeedForward(nn.Module):
    def __init__(self, n_embd):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.GELU(),
            nn.Linear(4 * n_embd, n_embd),
            nn.Dropout(dropout),
        )

    def forward(self, x):
        return self.net(x)

class Block(nn.Module):
    def __init__(self, n_embd, n_head):
        super().__init__()
        head_size = n_embd // n_head
        self.sa = MultiHeadAttention(n_head, head_size)
        self.ffwd = FeedForward(n_embd)
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)

    def forward(self, x):
        x = x + self.sa(self.ln1(x))     # Pre-LayerNorm + Residual connection
        x = x + self.ffwd(self.ln2(x))
        return x

# 5. Complete Micro-GPT Language Model
class MicroGPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
        self.position_embedding_table = nn.Embedding(block_size, n_embd)
        self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
        self.ln_f = nn.LayerNorm(n_embd)
        self.lm_head = nn.Linear(n_embd, vocab_size)

    def forward(self, idx, targets=None):
        B, T = idx.shape
        tok_emb = self.token_embedding_table(idx)
        pos_emb = self.position_embedding_table(torch.arange(T, device=device))
        x = tok_emb + pos_emb
        x = self.blocks(x)
        x = self.ln_f(x)
        logits = self.lm_head(x)

        loss = None
        if targets is not None:
            B, T, C = logits.shape
            loss = F.cross_entropy(logits.view(B * T, C), targets.view(B * T))
        return logits, loss

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, temperature=0.8):
        for _ in range(max_new_tokens):
            idx_cond = idx[:, -block_size:]
            logits, _ = self(idx_cond)
            logits = logits[:, -1, :] / temperature
            probs = F.softmax(logits, dim=-1)
            idx_next = torch.multinomial(probs, num_samples=1)
            idx = torch.cat((idx, idx_next), dim=1)
        return idx

# 6. Train & Sample Text
model = MicroGPT().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)

for step in range(max_iters):
    xb, yb = get_batch("train")
    logits, loss = model(xb, yb)
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()
    if step % eval_interval == 0:
        print(f"Step {step:3d} | Train Loss: {loss.item():.4f}")

prompt = torch.tensor([encode("Transformers ")], dtype=torch.long, device=device)
print("\n--- Generated Output ---")
print(decode(model.generate(prompt, max_new_tokens=160, temperature=0.7)[0].tolist()))

Interactive Lab 4: Live Browser Mini-GPT Simulator

Test autoregressive text generation directly in your browser using a lightweight variable-order language model trained on the sample corpus above. Adjust Temperature to see how low values produce deterministic completions while high values increase creativity (and randomness):

Mini-GPT Prompt & Temperature Simulator CLIENT-SIDE ENGINE
Click "Generate Tokens" to run autoregressive sampling...
Module 05 // Post-Training Pipeline

Pretraining, Fine-Tuning (SFT), & Alignment (RLHF / DPO)

A raw pretrained GPT model is a document completer, not a helpful assistant. If you ask a base pretrained model "What is the capital of France?", it might reply with another quiz question like "What is the capital of Germany?" because it saw exam sheets during pretraining. Turning a base model into a reliable assistant takes three distinct stages:

Training Stage Dataset Scale Objective & Algorithm Resulting Capability
1. Pretraining 1T – 15T+ tokens (Web, code, books, papers) Next-token cross-entropy loss across massive GPU clusters World knowledge, grammar, coding, multi-language fluency
2. Supervised Fine-Tuning (SFT) 10K – 1M curated (Prompt, Ideal Response) pairs Next-token loss masked solely on the assistant's response tokens Instruction following, Q&A formatting, conversational tone
3. Preference Alignment (RLHF / DPO) 50K – 500K human/AI ranked pairs (Chosen vs. Rejected) Proximal Policy Optimization (PPO) or Direct Preference Optimization (DPO) Helpfulness, truthfulness, refusal of harmful requests

How Direct Preference Optimization (DPO) Works

Traditional RLHF trains a separate Reward Model and uses Reinforcement Learning (PPO), which is complex and memory-heavy. DPO simplifies alignment into a single classification-style loss that directly increases the probability of a human-preferred response (yw) relative to a rejected response (yl), while staying close to the reference SFT model (πref):

dpo_loss.py — Direct Preference Optimization Loss in PyTorch
import torch
import torch.nn.functional as F

def dpo_loss(policy_chosen_logps, policy_rejected_logps,
             ref_chosen_logps, ref_rejected_logps, beta=0.1):
    """
    Computes Direct Preference Optimization (DPO) loss.
    All inputs are sequence-summed log-probabilities of shape (batch_size,).
    """
    chosen_rewards = beta * (policy_chosen_logps - ref_chosen_logps)
    rejected_rewards = beta * (policy_rejected_logps - ref_rejected_logps)
    logits = chosen_rewards - rejected_rewards
    return -F.logsigmoid(logits).mean()

# Example batch of 2 preference pairs
loss = dpo_loss(
    policy_chosen_logps=torch.tensor([-12.1, -8.4]),
    policy_rejected_logps=torch.tensor([-15.8, -11.2]),
    ref_chosen_logps=torch.tensor([-12.5, -8.6]),
    ref_rejected_logps=torch.tensor([-14.0, -10.5]),
    beta=0.1
)
print(f"DPO Alignment Loss: {loss.item():.4f}")