Welcome to the advanced course on AI pretraining. Today we define the objectives and structure that ground a rigorous treatment of the full pretraining pipeline, from raw text to trained model.
First, the definition and significance of pretraining: self-supervised objectives such as next-token prediction let models learn transferable representations from trillions of tokens, amortizing one large training run across many downstream tasks.
Notice the data-to-loss pipeline emphasized here: it is the mechanism converting raw corpora into a scalar training signal through tokenization, batching, and cross-entropy.
We study this pipeline rigorously, from corpus curation and deduplication through loss formulation, because each stage directly shapes model quality and scaling behavior.
Finally, the course structure: modules and learning objectives sequenced from foundational concepts to current research, covering scaling laws, architectural ablations, and alignment methods through 2026.
Equations, code and original cards
Course Overview and Objectives
• Self-supervised pretraining: definition and significance
• The data-to-loss pipeline: corpus to cross-entropy
• Course objectives, modules, and structure
Moment 02 / 11
Raw Text to Tokens: Data Curation and Tokenization
This slide covers the pipeline from raw text to tokens: data curation and subword tokenization, the two stages that determine what distribution your language model actually learns from.
Data curation dominates final model quality more than most architecture choices. Sources are web crawls like Common Crawl, digitized books, and code. Filtering applies language identification, length thresholds, and boilerplate removal. Deduplication, often via MinHash locality-sensitive hashing, removes near-duplicates that otherwise inflate memorization. Quality classifiers then score documents for sampling weight, as in the LLaMA and GPT-3 pipelines.
Tokenization uses Byte-Pair Encoding, introduced for neural machine translation by Sennrich and colleagues. BPE iteratively merges the most frequent adjacent symbol pair, yielding a subword vocabulary that interpolates between character-level robustness and word-level efficiency. Typical vocabularies sit around 32,000 to 100,000 tokens.
Formally, the tokenizer is a deterministic map from raw strings to integer sequences over a fixed vocabulary. This mapping is lossless and invertible, which is what makes the autoregressive factorization over tokens well-defined.
The embedding matrix E, with shape vocabulary size by model dimension, maps each token index to a dense vector in the residual stream. These rows are learned parameters, initialized randomly and trained jointly with the rest of the network.
The PyTorch snippet shows the mechanics: build a vocabulary mapping tokens to indices, then convert a token list into an integer tensor. That tensor indexes the embedding matrix to produce the input representations.
To summarize: curation fixes the data distribution, BPE fixes the discrete units, and the embedding table lifts those units into the continuous space where training happens. Every downstream capability is bottlenecked by decisions made at this stage.
Equations, code and original cards
Raw Text to Tokens: Data Curation & Tokenization
Data Curation
• Sources: Common Crawl, books, code, articles
• Filtering: language ID, length thresholds, boilerplate removal
• Deduplication: MinHash near-duplicate detection
• Quality classifier scores documents for sampling weight
Tokenization: Byte-Pair Encoding (BPE)
• Iteratively merge most frequent adjacent pair (Sennrich et al. 2016)
• Subwords interpolate char-level robustness and word-level efficiency
• Python snippet: bpe_vocab = {} for step in range(num_merges): pairs = get_freq_pairs(corpus) merge_pair = max(pairs, key=pairs.get) bpe_vocab[step] = merge_pair corpus = merge_tokens(corpus, merge_pair)
indices = torch.tensor([vocab[t] for t in tokens])
Moment 03 / 11
Training Objective: Next Token Prediction
The training objective is next-token prediction: given a token prefix, the model must assign probability mass to the correct continuation. This single self-supervised objective, applied at trillion-token scale, is what produces general-purpose language models.
Formally, the model factorizes the sequence probability into a product of conditionals, each a softmax over the vocabulary produced from the final residual stream. Parameters are optimized to place mass on the observed next token at every position.
The loss is the token-level cross entropy: the negative log likelihood of x-t-plus-one given the prefix, averaged over all positions. Equivalently, this is the empirical cross entropy between the model distribution and the data distribution, and minimizing it minimizes KL divergence to the data up to a constant.
Gradients follow by backpropagation through the softmax and logits. A key identity: the gradient of cross entropy with respect to the logits is simply the predicted distribution minus the one-hot target, which makes the backward pass cheap and numerically stable.
In PyTorch this is a few lines: the model emits logits of shape batch by sequence by vocabulary, we flatten batch and time, and CrossEntropyLoss fuses the log-softmax with the negative log likelihood. Note we pass raw logits, never softmax outputs, for numerical stability.
Watch the loss curve: it should fall roughly as a power law in tokens seen, consistent with the Kaplan et al. scaling results. Report perplexity, the exponential of the mean loss, and watch for plateaus signaling learning-rate or capacity issues.
To summarize: next-token prediction factorizes sequence likelihood into conditionals, cross entropy gives the training signal with a closed-form logit gradient, implementation is a fused loss over raw logits, and the loss curve itself is a diagnostic governed by scaling laws.
Clarification: A linear output-layer gradient is not the gradient of all model parameters.
• Minimizing it = minimizing KL to data distribution
Z=HW_o,\quad \nabla_{W_o}L=H^\top(P-Y);\quad \nabla_\theta L\text{ uses the full chain rule}
• Backpropagate through \(\theta\) via chain rule
• Logit gradient: \(\hat{y}_t - y_t\) (softmax + CE identity)
• \(y_t\): one-hot target; \(\hat{y}_t\): predicted distribution
import torchimport torch.nn as nncriterion = nn.CrossEntropyLoss()logits = model(x) # raw logits, no softmaxloss = criterion(logits.view(-1, vocab_size), target.view(-1))loss.backward()
Loss Curve: Power-Law Decay, Perplexity = exp(mean loss)
Moment 04 / 11
Pretraining Pipeline Diagram Interactive
Trace the pretraining pipeline end to end: corpus curation, tokenizer induction, and gradient-based optimization over next-token cross-entropy.
Watch the corpus move from filtering and deduplication into byte-pair encoding; each node exposes the objective, hyperparameters, and reference implementation.
At training, inspect AdamW updates minimizing the negative log likelihood of each token given its context under causal masking.
Step through the stages with the controls and track the transformation from raw text to token ids to a residual stream shaped by learned weights.
Equations, code and original cards
Moment 05 / 11
Training at Scale: Chinchilla Scaling Laws and Compute Optimization
Welcome. Today we turn to scaling laws for large language models: the Chinchilla result of Hoffmann and colleagues, which tells us how to spend a fixed compute budget optimally.
The core principle is compute-optimal training: for a given FLOP budget, model size and token count should scale together, at roughly twenty tokens per parameter, rather than making the model alone larger.
The workhorse approximation is that total compute is about six times parameters times tokens: the factor six reflects two FLOPs per parameter for the forward pass and four for the backward pass, quantifying the training budget.
Equivalently, the Chinchilla optimum sets tokens near twenty times parameters, so a seventy-billion-parameter model wants about one point four trillion tokens; this balances model capacity against data exposure.
To fix notation: compute is measured in FLOPs, parameters count the model's weights, and tokens measure dataset size, not network depth. Reading the laws correctly depends on keeping these three quantities distinct.
These relations prevent both overtraining, where extra tokens yield diminishing returns, and undertraining, where excess parameters sit data-starved; either mistake wastes compute that a balanced allocation would use.
In short, Chinchilla supersedes the earlier Kaplan scaling picture by prescribing the twenty-to-one token-to-parameter rule and the six-times compute identity, a recipe reflected in practice from GPT-3 to Llama 3 for efficient large-model training.
Clarification: Correct token-to-parameter ratio and state its experimental scope.
Equations, code and original cards
Training at Scale: Chinchilla Scaling Laws and Compute-Optimal Allocation
• Chinchilla (Hoffmann et al. 2022): compute-optimal ratio ≈ 20 tokens per parameter
• Compute identity C ≈ 6ND; factor six = forward plus backward FLOPs
• Overtraining vs undertraining on a fixed FLOP budget
• Case studies: GPT-3 (undertrained) vs Llama 3 (token-heavy)
C \approx 6 N D
D\approx20N\quad\text{(Chinchilla training-compute heuristic, not a universal optimum)}
Compute-Optimal Scaling Relationships
C: compute (FLOPs); N: parameters; D: training tokens; optimum near T ≈ 20N
Balance parameters and tokens so neither capacity nor data becomes the bottleneck
Moment 06 / 11
Advanced Training Techniques and Optimizations
We turn to optimization levers behind recent pretraining: low-rank adaptation, data-mixture control, toxicity screening, and parameter-group schedules. The goal is stable loss descent at fixed compute, not cosmetic tricks.
Start with rank-stabilized LoRA. Standard LoRA scales the low-rank update by alpha over rank; rsLoRA uses alpha over the square root of rank, keeping update magnitude and gradient variance from shrinking as adapters widen.
Mechanically, the frozen base weight still defines the residual stream, while the adapter contributes a controlled correction in the linear layer. That prevents slow rank collapse during trillion-token runs.
Next is data governance: domain balancing and toxicity filtering. Mixture weights are adjusted across web, code, mathematical, and multilingual sources so no domain dominates the gradient, while filters remove toxic spans before tokenization.
The effect is not moral decoration; it changes the empirical distribution the cross-entropy is minimized over, reducing skewed likelihoods and lowering the chance that unsafe continuations look high-probability.
For implementation, the PyTorch pattern is simple: mark adapter parameters trainable, freeze the backbone, and let autograd allocate memory and optimizer state where gradients are needed.
Freezing is an inductive bias and a memory saving: it restricts the update Jacobian to adapter subspaces, protecting pretrained features while permitting domain shift.
Finally, use separate learning-rate schedules for embeddings, adapters, and attention blocks. A lower embedding rate limits rare-token drift, while decayed adapter rates track the loss curvature as convergence approaches.
Together these are systems-level regularizers: they stabilize optimization, shape the training distribution, and cut optimizer memory, which is what makes long-horizon pretraining reproducible rather than merely larger.
Equations, code and original cards
Advanced Training Techniques and Optimizations
Systems and optimization levers for 2024-2026 pretraining
1. Rank-Stabilized LoRA (rsLoRA)
• Low-rank update scaled by alpha over square-root rank
• Keeps gradient variance stable as adapter rank grows
2. Domain Balancing & Toxicity Filtering
• Rebalances mixture weights across web, code, math, multilingual
• Screens pretraining corpus for toxicity before tokenization
3. Sample Python/PyTorch Snippets
# Freeze backbone; train adapters onlyfor name, param in model.named_parameters(): if 'lora_' in name: param.requires_grad_(True) else: param.requires_grad_(False)
Let's walk through the implementation in Python and PyTorch, examining how the pretraining pipeline's core components—data processing, loss computation, and distributed optimization—compose in practice.
The data pipeline handles filtering and deduplication, since near-duplicate documents inflate memorization and waste compute. It then packs tokens into fixed-length sequences to saturate GPU throughput.
The function filter and batch iterates over the corpus, tracks seen documents in a hash set for exact deduplication, and packs tokenized sequences up to a budget of ten twenty-four tokens per batch.
Next, the loss and gradient computation. We define the training objective, zero accumulated gradients, and invoke backpropagation to obtain parameter gradients through automatic differentiation.
Concretely, we use cross-entropy over the vocabulary logits—the negative log likelihood of each target token given its context—then call zero grad and backward to populate gradients for the optimizer step.
The GPU training loop exploits data parallelism, sharding batches across devices and synchronizing gradients with all-reduce. Mixed precision in bfloat sixteen roughly doubles throughput on tensor cores.
For reproducibility at scale, we fix random seeds, enable deterministic kernels, and log gradient norms—essential when debugging runs consuming ten to the twenty-third FLOPs.
In summary, this walkthrough covered deduplication, token packing, cross-entropy loss, distributed training loops, and reproducibility. Next, we apply these ideas to a concrete pretraining example.
def filter_and_batch(data):
seen = set()
filtered = [x for x in data if x not in seen and (seen.add(x) or True)]
batches = batch_tokens(filtered, max_tokens=1024)
return batches
• Data parallelism with all-reduce • Mixed precision (bf16) • Gradient accumulation for large batches
Reproducibility & Scaling
• Fixed random seeds • Deterministic kernels • Gradient-norm logging
Moment 08 / 11
Continued Pretraining and Domain Adaptation
Continued pretraining is a second optimization phase under distribution shift: keep the autoregressive objective, initialize from the base checkpoint, and expose the residual stream to target-domain statistics before task tuning.
The slide’s point is narrow: sample from a corpus nearer the deployment distribution, so gradients update attention, embeddings, and layer norms toward domain tokens while the cross-entropy loss and causal masking stay fixed.
Formally, minimize expected negative log likelihood under the target corpus, initialized at the pretrained parameters; the risk shifts with the data distribution, while the loss stays fixed.
The code is ordinary teacher forcing: zero stale gradients, run the forward pass on domain batches, then compare logits against shifted labels with the same cross-entropy criterion used in pretraining.
Those logits parameterize a softmax over the vocabulary; after aligning predictions with next-token labels, the scalar loss aggregates token errors and becomes the signal for backpropagation through the residual stream.
Backward populates parameter gradients, the optimizer applies the update, and gradient-norm clipping plus a lower learning rate are the usual safeguards against catastrophic forgetting.
The recipe is cheap because it reuses the optimizer state, tokenizer, and objective while narrowing the data mixture; add replay or KL regularization if forgetting appears, and prefer LoRA or rank-stabilized LoRA when adapter capacity must stay small.
Equations, code and original cards
Continued Pretraining: Domain Adaptation under Distribution Shift
• Optimize the same autoregressive cross-entropy on target-domain corpora
• Initialize from the base checkpoint; only the empirical risk changes
• Control forgetting with replay, KL regularization, lower learning rates
• LoRA and rank-stabilized LoRA constrain adapters for deployment
# Python & PyTorch: teacher forcing on a domain batchoptimizer.zero_grad() # clear stale gradients
outputs = model(inputs) # logits over the vocabularyloss = criterion(outputs, labels) # same cross-entropy objective
loss.backward() # gradients through the residual streamoptimizer.step() # low-rate update, often with clipping
Moment 09 / 11
Open Research Questions and Cutting-Edge Variations
Let's examine the frontier of pretraining research as of 2026: alignment, efficiency, and the open problems that remain unsolved.
First, alignment and efficiency. Reinforcement learning from human feedback, as in Ouyang et al.'s InstructGPT, and its successor direct preference optimization from Rafailov et al., now shape how models match human intent at scale.
Next, novel objectives and regularization. Contrastive terms, entropy regularization, and noise injection are being studied to improve generalization and robustness under distribution shift.
We also confront unresolved questions in data curation and bias mitigation. Deduplication, quality filtering, and provenance remain critical obstacles for trustworthy models.
Finally, community trends point toward open-weight releases, reproducible scaling studies, and interdisciplinary evaluation as the field matures.
Consider the composite objective shown here: a weighted sum of cross-entropy, a contrastive term over embeddings, and a regularizer on the parameters theta.
This formulation trades off next-token prediction against representation structure and capacity control, with the coefficients alpha, beta, and gamma governing each contribution.
The PyTorch snippet shows the translation to practice: a custom loss module whose forward pass combines the three terms and returns their weighted sum for backpropagation.
In summary, these open questions define the pretraining frontier. Tracking them is essential for anyone pushing state-of-the-art models forward.
Equations, code and original cards
Open Research Questions and Cutting-Edge Variations
Frontier problems in pretraining: alignment, objectives, data, and evaluation
• Alignment and efficiency at scale
– RLHF (Ouyang et al. 2022) and DPO (Rafailov et al.) – Sparse attention and FlashAttention (Dao et al.)
• Novel objectives and regularization
– Contrastive terms for prompt robustness – Entropy regularization and noise injection
• Open problems: data curation, deduplication, and bias mitigation
• Trends: open weights, reproducible scaling studies, interdisciplinary evaluation
L = alpha * Cross-Entropy + beta * Contrastive + gamma * Regularizer on theta
import torch
import torch.nn as nn
class CompositeLoss(nn.Module):
def __init__(self, alpha, beta, gamma):
super().__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.ce = nn.CrossEntropyLoss()
# Contrastive term over embeddings
# Weight decay or norm penalty on theta def forward(self, logits, targets, embeddings):
loss_ce = self.ce(logits, targets)
loss_cl = contrastive_loss(embeddings) # InfoNCE-style
reg_loss = regularization_term(self.parameters()) # e.g. L2
return self.alpha*loss_ce + self.beta*loss_cl + self.gamma*reg_loss
Moment 10 / 11
Comprehensive Quiz: Conceptual and Computational Challenges
Time to stress-test your understanding of the pretraining pipeline. Work through each question independently before submitting — some probe conceptual recall, others demand back-of-the-envelope compute estimates. Once you finish, we'll resolve whatever remains unclear.
Equations, code and original cards
Moment 11 / 11
Course Summary and Key Takeaways
Let's close by reconstructing the pretraining pipeline as a controlled system: tokenization and byte pair encoding, deduplication, toxicity and quality filters, domain mixture weights, then AdamW optimization of the next token cross entropy with cosine decay, gradient clipping, and held out perplexity as the first alarm.
The hard lesson is that data quality is not hygiene; it is model capacity. Near duplicates, benchmark leakage, and skewed mixtures move loss more than small architecture tweaks, while Kaplan and Chinchilla scaling laws tie compute, parameters, and tokens to generalization rather than to intuition.
Transfer learning is the practical default: initialize from a pretrained residual stream, adapt with low rank updates or full finetuning, and measure catastrophic forgetting. Meta learning optimizes fast adaptation across task distributions, an inductive bias for foundation models.
Build expertise by implementing the loop in PyTorch: dataset ablations, learning rate sweeps, gradient norm tracking, and evaluation beyond accuracy. Then read NeurIPS and ICML papers with a replication mindset, asking which claim survives a cleaner baseline.
The throughline is disciplined empiricism: define the objective, control the data, respect compute optimal scaling, and ablate before you believe. Carry that workflow into research or production, and prefer a measured failure over a persuasive demo.
Equations, code and original cards
Course Summary: Pretraining as a Controlled System
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.