Skip to main content
LearnMLAcademy
Intermediate10 min read

How LLMs Are Trained: Data, Pretraining, Scale & Compute

Explore how modern foundation LLMs are pretrained at scale on massive compute, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Where do the model's parameters come from?

In the introduction we used “The cat sat on the ____”. The model predicts the next token, compares its probability with the observed continuation, calculates an error, and adjusts its parameters.

Pretraining is this broad learning process repeated across a very large and varied corpus so the model develops general language and pattern-prediction capability.

Training data is not just “more text”

Why preparation matters

Why preparation matters
ConcernWhy it matters
QualityLow-quality or misleading material can teach undesirable patterns
DiversityBroader examples help the model cover more language, domains, and styles
DeduplicationRepeated documents can disproportionately dominate the mixture and increase leakage/memorization risk
Held-out validationSeparate examples help measure whether training improvements generalize beyond the batches being updated

How next-token training examples are formed

For a token sequence [t₁, t₂, t₃, t₄], a causal language-model training view can use [t₁, t₂, t₃] as the available inputs while the targets are shifted one step to [t₂, t₃, t₄]. At each position, the target is the token that actually followed the available prefix.

Loss answers: how much probability did we give the correct token?

One common causal-language-model loss is negative log-likelihood. You do not need to memorize logarithms to understand the direction: assigning more probability to the observed next token gives a smaller loss.

Tiny loss comparison

Tiny loss comparison
Probability assigned to correct token−ln(probability)Interpretation
0.50≈ 0.693Higher loss
0.80≈ 0.223Lower loss because the model assigned more probability to the observed token

The loss now connects the data preparation to learning: the observed next token supplies the target, the model supplies a probability, and the training loop uses the resulting error to update parameters. Follow those responsibilities through the diagram.

Pretraining is repeated prediction plus parameter updates

STEP 1

Prepare text

STEP 2

Tokenize

STEP 3

Predict next token

STEP 4

Measure loss

STEP 5

Backpropagate

STEP 6

Update parameters

STEP 7

Repeat

The exact infrastructure can be enormous, but the learning loop is familiar: examples → prediction → error → adjustment.

A seven-stage flow shows prepared text being tokenized, used for next-token prediction, evaluated with a loss, backpropagated, followed by a parameter update, and repeated.

Pretraining versus fine-tuning

Think of pretraining as broad education and fine-tuning as additional specialist coaching. Fine-tuning starts from an already trained model and continues updating some or all parameters using a narrower dataset or objective.

Two stages, different goals

Two stages, different goals
StagePrimary goalTypical data
PretrainingLearn broad language and general patternsVery large, varied corpus
Fine-tuningShape narrower task/domain/behaviorSmaller curated examples relevant to the target

Why training needs much more memory than the saved weights

A 1-billion-parameter model stored with 16-bit weights is roughly 2 GB of raw weight values as a simple estimate. That does not mean 2 GB is enough to train it.

Training may also need activations, gradients, optimizer state, temporary buffers, and communication overhead. The exact amount depends on the optimizer, precision, sequence length, batch size, checkpointing, hardware, and parallel strategy.

Why the next lesson matters

Pretraining creates a broad language model. How do we teach it to follow instructions, reflect preferences, and specialize efficiently?

SFT, RLHF & LoRA →

Summary / Key Takeaways

  • Pretraining repeatedly performs next-token prediction, loss calculation, backpropagation, and parameter updates over a broad corpus.
  • Data quality, diversity, deduplication, and held-out validation affect what the model learns and how reliably progress is measured.
  • Causal training shifts targets so each position learns the token that follows its available prefix.
  • Giving the observed next token higher probability reduces negative log-likelihood.
  • Fine-tuning continues training an existing model for a narrower goal.
  • Raw weight memory is only one part of training memory; activations, gradients, optimizer state, and other overhead also matter.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "How LLMs Are Trained: Data, Pretraining, Scale & Compute"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is deduplication part of LLM data preparation?
Question 2 of 5interpretation
For tokens [t₁,t₂,t₃,t₄], why might [t₁,t₂,t₃] be inputs and [t₂,t₃,t₄] be targets?
Question 3 of 5numerical/formula
The correct token's probability improves from 0.50 to 0.80. Which negative log-likelihood is lower?
Question 4 of 5practical selection
The full model fits on each GPU, but the team wants greater batch throughput. Which strategy is the most direct starting point?
Question 5 of 5debugging/diagnostic
A developer estimates that a 1B-parameter 16-bit model needs only about 2 GB and concludes 2 GB is enough to train it. What is missing?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is deduplication part of LLM data preparation?▼

Correct Answer: To reduce repeated examples from disproportionately dominating the training mixture

Repeated documents can overweight particular patterns and create leakage/quality problems.

2For tokens [t₁,t₂,t₃,t₄], why might [t₁,t₂,t₃] be inputs and [t₂,t₃,t₄] be targets?▼

Correct Answer: Causal pretraining learns to predict the next observed token at each position

Each position learns the token that follows its available prefix.

3The correct token's probability improves from 0.50 to 0.80. Which negative log-likelihood is lower?▼

Correct Answer: `−ln(0.80) ≈ 0.223` is lower

Assigning more probability to the observed target reduces negative log-likelihood.

4The full model fits on each GPU, but the team wants greater batch throughput. Which strategy is the most direct starting point?▼

Correct Answer: Data parallelism

Data parallelism lets replicas process different batches and synchronize gradients when each device can hold the model.

5A developer estimates that a 1B-parameter 16-bit model needs only about 2 GB and concludes 2 GB is enough to train it. What is missing?▼

Correct Answer: Activations, gradients, optimizer state, buffers, and communication overhead

The 2 GB estimate covers idealized raw weights only; training needs substantial additional state and temporary memory.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next