Skip to content
MAMasterAI Now
8 / 11قراءة 15 دقيقةالمستوى: Intermediate5 بطاقات

التدريب المسبق والخسارة

التنبّؤ بالرمز التالي، على نطاق يظهر فيه الذكاء العام.

⚠ هذه المرحلة مترجمة بنسبة 3% إلى العربية؛ وتُعرض البطاقات المتبقية بالإنجليزية. لاحظت خطأ؟ تصحيحات الترجمة مرحّب بها.

تقدّم القراءة0%
Card 1 — the objectiveالبطاقة 1 من 5

The whole training job is one sentence

Given everything so far, how surprised are you by the next token?

Pre-training a large language model optimises exactly one thing: predict the next token. That is it. Feed it a trillion tokens of raw text, mask the future, and ask for the next one every time. Grammar, facts, translation, arithmetic procedures and reasoning patterns all emerge as side effects of getting very good at this single task.

Analogy
Reading with the last word covered

Imagine every page of every book with the final word of each sentence hidden. To fill them in well you must learn vocabulary, syntax, facts, idiom and causality. Nobody teaches you those explicitly — the task forces them out of you. That is pre-training.

The training signal is self-supervised: the label is simply the next token from the real text, so no human annotation is needed. That is what makes internet-scale training possible at all.

NoteA useful reframing

The model is not being taught answers; it is being taught a probability distribution over the entire vocabulary at every position. The output layer therefore emits vocab_size numbers per token — for a 128k vocabulary, that is a very large matrix multiply per position.

تحقّق سريع قبل البطاقة التالية

What is the training objective of LLM pre-training?

5 اختبارات

🔒

المختبر مغلق

أكمل بطاقات المرحلة (5) واختباراتها لفتح هذه المحاكاة.

Read the full stage transcript (all 5 cards, no JavaScript required)
Card 1 — the objective

1. The whole training job is one sentence

Given everything so far, how surprised are you by the next token?

Pre-training a large language model optimises exactly one thing: predict the next token. That is it. Feed it a trillion tokens of raw text, mask the future, and ask for the next one every time. Grammar, facts, translation, arithmetic procedures and reasoning patterns all emerge as side effects of getting very good at this single task.

Analogy
Reading with the last word covered

Imagine every page of every book with the final word of each sentence hidden. To fill them in well you must learn vocabulary, syntax, facts, idiom and causality. Nobody teaches you those explicitly — the task forces them out of you. That is pre-training.

The training signal is self-supervised: the label is simply the next token from the real text, so no human annotation is needed. That is what makes internet-scale training possible at all.

NoteA useful reframing

The model is not being taught answers; it is being taught a probability distribution over the entire vocabulary at every position. The output layer therefore emits vocab_size numbers per token — for a 128k vocabulary, that is a very large matrix multiply per position.

Knowledge check: What is the training objective of LLM pre-training?

  • a. Predict the next token given all previous tokens← correct
  • b. Classify documents into categories
  • c. Maximise the number of facts memorised

Everything else is emergent. Instruction tuning and RLHF (stages 9 and 10) come later and adapt this base model to be useful.

Card 2 — the scoreboard

2. Cross-entropy and perplexity

Loss measures surprise. Perplexity tells you how many options the model is torn between.

L = −(1/N) · Σ log p(correct token) Perplexity = e^L
Cross-entropy loss penalises low probability assigned to the token that actually occurred.

Cross-entropy is minimised when the model puts probability 1.0 on the correct token. Because it uses the logarithm, being confidently wrong is punished brutally: assigning 0.01 to the right answer costs 4.6, while assigning 0.9 costs only 0.105. This asymmetry is exactly the pressure we want — it forces the model to spread probability sensibly instead of guessing.

LossPerplexityInterpretation
7.6≈ 2000Random-ish guessing over a large vocabulary
3.0≈ 20Torn between about twenty plausible continuations
1.5≈ 4.5Strong grasp of the language and the topic
Analogy
Perplexity as a shortlist

Perplexity 20 means the model behaves as if it is choosing among roughly twenty equally plausible next words. Lower is better, but beware: perplexity is only comparable between models that use the same tokenizer, since it is measured per token.

Knowledge check: Why is perplexity only comparable across models that share a tokenizer?

  • a. Because it is computed per token, and different tokenizers split text into different numbers of tokens← correct
  • b. Because perplexity depends on GPU count
  • c. Because perplexity is measured in seconds

A coarser tokenizer has fewer, larger predictions to make, which flatters the score. Always compare like with like, or switch to bits-per-byte.

Card 3 — the dials

3. Learning-rate schedules, warmup and AdamW

A billion-dollar run usually dies from a badly chosen learning rate.

Pre-training rarely uses a constant learning rate. The standard recipe is warmup then decay: start near zero, ramp up over the first few hundred to few thousand steps, then decay smoothly (cosine) toward the end. Warmup exists because early gradients are huge and unreliable — taking full-size steps immediately destabilises the run.

HyperparameterTypical value (base model)What goes wrong otherwise
Peak learning rate1e-4 to 3e-4Too high → loss spike or divergence
Warmup steps0.5–2% of totalToo short → early instability, loss spikes
Batch size (tokens)0.5–4M tokensToo small → noisy gradients, poor hardware use
Weight decay0.1 (AdamW)Zero → weaker generalisation
Gradient clip norm1.0Unclipped → NaN explosions

AdamW maintains a running mean and variance of each parameter's gradient and divides by the square root of the variance, giving every parameter its own effective step size. It is memory-hungry — two extra tensors per parameter — which is why optimiser state is a large part of what you must fit in GPU memory when fine-tuning.

Watch outLoss spikes

Large runs occasionally show a sudden loss jump. The usual recovery playbook: roll back a few hundred steps, skip the offending data shard, lower the learning rate briefly, then resume. Modern stacks automate this.

Knowledge check: Why do pre-training runs use a learning-rate warmup?

  • a. Early gradients are unreliable, so small steps prevent an unstable start← correct
  • b. To save GPU electricity
  • c. Because AdamW cannot process large gradients

Warmup lets the optimiser statistics settle before full-size steps begin. Removing it is one of the most common causes of early loss spikes and divergence.

Card 4 — the recipe

4. Scaling laws: how big, and how much data

Model size and data size must grow together. Starving a big model is expensive and pointless.

Loss falls predictably as a power law in model parameters, dataset size and compute. That predictability is remarkable: results from small runs let you forecast a large one before spending the money. The practical consequence came from the Chinchilla result — for a fixed compute budget, most models of that era were far too large for the amount of data they saw.

optimal tokens ≈ 20 × parameters
The Chinchilla guideline: a 10B-parameter model wants roughly 200B tokens for compute-optimal training.
  • Compute-optimal means best loss per FLOP. Inference-optimal means best loss per served request — which is why production models are often trained far beyond the Chinchilla point.
  • Data quality changes the exponent: cleaner corpora shift the whole curve down.
  • Diminishing returns are real but slow — you keep paying linearly for logarithmically better loss.
  • Small-scale experiments are genuinely predictive, which is why ablation studies on 100M-parameter models remain standard practice.
Good to knowThe engineering takeaway

Before scaling anything, over-train a tiny model on your exact data pipeline. If the loss curve on the small model has a problem, the large one will simply have it more expensively.

Knowledge check: What does the Chinchilla finding say about training a model compute-optimally?

  • a. Model size and dataset size should scale roughly together, near 20 tokens per parameter← correct
  • b. Bigger models always win regardless of data
  • c. Data does not matter beyond a fixed threshold

Many earlier large models were undertrained relative to their size. Matching data to parameters gives far better loss for the same compute.

Card 5 — the run

5. What a pre-training run actually looks like

Weeks of hardware, one number to watch, and a thousand ways for it to break.

  1. 1Collect and clean the corpus (dedup, filter, tokenize, shard into fixed-length sequences).
  2. 2Shuffle and stream the shards so no epoch ordering leaks into the model.
  3. 3Forward pass on a batch, compute cross-entropy on the next token at every position.
  4. 4Backward pass, clip gradients, step AdamW on the schedule.
  5. 5Log loss, gradient norm, learning rate and throughput. Watch for spikes.
  6. 6Checkpoint regularly — a crash at week three without one is a catastrophe.
py
for step, batch in enumerate(loader):
    lr = schedule(step)                 # warmup -> cosine decay
    for g in opt.param_groups:
        g['lr'] = lr

    out = model(**batch)                # labels shifted inside the loss
    out.loss.backward()

    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    opt.zero_grad(set_to_none=True)

    if step % 50 == 0:
        log(loss=out.loss.item(), lr=lr, step=step)
Good to knowThe whole lifecycle, so far

Data curation (Stage 4) → tokenization (Stage 5) → embeddings (Stage 6) → attention (Stage 7) → next-token pre-training (this stage). What remains is making the result behave: instruction tuning and alignment.

Knowledge check: Why is gradient clipping standard in large pre-training runs?

  • a. A single large gradient can produce NaN weights and destroy the run← correct
  • b. It reduces GPU memory usage
  • c. It makes the learning rate unnecessary

Clipping caps the update norm, trading a tiny amount of fidelity for the ability to survive occasional pathological batches.