How AI works

How is an AI model actually trained, step by step?

Training an AI model is a loop: guess, measure how wrong the guess was, nudge the model's numbers to be a little less wrong, repeat. Here's that loop run by hand on a one-parameter model, then scaled up to GPT-3.

By the Toorova team · Published November 24, 2026 · 14 min read · How we write these

Short answer

An AI model is trained by showing it examples where the right answer is known and adjusting its internal numbers, called parameters, until its outputs come close to those answers. Each round, the model makes predictions, a loss function scores how wrong they are, and gradient descent nudges every parameter in the direction that lowers the loss. This repeats thousands of times or more. Some data is held back as validation and test sets, to check the model works on examples it never trained on.

What training an AI model actually means

An AI model is a math function with a lot of adjustable numbers inside it. Data goes in, a prediction comes out, and the adjustable numbers, called parameters (or weights), decide what that prediction is. A spam filter turns an email into a spam score. A language model turns a sentence into a guess at the next word. The model in this article has one parameter; GPT-3 had 175 billion parameters. The basic training loop is the same for both.

Before training, the numbers are close to meaningless. Google's Machine Learning Crash Course notes that a model begins training with randomized weights and biases near zero, so its first predictions are junk. Training adjusts the parameters until the predictions match a pile of examples where the right answer is already known.

It takes four ingredients:

  • Examples with answers. Emails marked spam or not spam, houses with their sale prices, or sentences where the answer is simply the word that comes next. The answer attached to each example is called its label.
  • A model with parameters to adjust.
  • A loss function, a formula that turns "how wrong were the predictions?" into a single number.
  • An optimizer, the rule for changing the parameters to make that number smaller. It's almost always some version of gradient descent.

Then you run a loop. PyTorch's official tutorial sums up each pass: the model makes a guess about the output, calculates the error in its guess (loss), works out how that error depends on each parameter, and adjusts the parameters with gradient descent. Guess, score, nudge, repeat.

How a loss function scores a model's mistakes

Here's the example the rest of this article uses. A courier charges by distance, and you want a model that predicts the fee. You have three past deliveries. The numbers are made up to keep the arithmetic easy.

DeliveryDistanceFee
A1 mile$2
B2 miles$5
C3 miles$6

The model is as simple as models get: fee = w × miles. It has one parameter, w, the price per mile. A real pricing model would add a base fee as a second parameter, but one is enough to see every moving part. Training means finding the w that fits these deliveries best.

To say one value of w is better than another, you need a score. Google's course defines loss as a numerical metric that describes how wrong a model's predictions are. For predicting numbers, a standard choice is mean squared error (MSE): for each example, take the prediction minus the right answer, square it, then average the squares. At w = 1, for example, the misses are −1, −3 and −3, their squares are 1, 9 and 9, and the loss is 19 ÷ 3 = 6.33:

w (dollars per mile)Predicted feesSquared missesLoss (MSE)
0$0, $0, $04, 25, 3621.67
1$1, $2, $31, 9, 96.33
2$2, $4, $60, 1, 00.33
3$3, $6, $91, 1, 93.67

The loss falls from w = 0 to w = 2, then climbs again by w = 3, so the best value sits somewhere near 2. The squaring matters too. It stops a miss of −3 and a miss of +3 from canceling out, and it makes big misses count far more than small ones: at w = 3, delivery C is off by $3 and supplies 9 of the 11 points of total squared error. In Google's words, when the difference between the prediction and label is large, squaring makes the loss even larger. That's what you want when big errors are the ones that hurt. It's a problem when the data has a few wild outliers, because, as the same page notes, MSE pulls the model toward them.

The loss is the only feedback the model ever gets. It never sees "good courier pricing", only this one number, and as Google's course puts it, the goal of training a model is to minimize the loss. Classifiers use a different loss, usually based on how much probability they gave the right answer, but it plays the same role.

Gradient descent, worked out by hand with one parameter

The courier model, fee = w × miles, has a single parameter, so you could just try every value of w and keep the best. A neural network with millions of parameters can't be searched that way, so training feels its way downhill instead. Stanford's CS231n course notes give the picture: think of yourself as hiking on a hilly terrain with a blindfold on, and trying to reach the bottom. You can't see the valley, but you can feel which way the ground tilts under your feet, so you take a step downhill and feel again.

The tilt under your feet is the gradient: how fast the loss changes when you nudge w up a tiny bit. For this model and this loss, calculus gives a short recipe. For each delivery, multiply 2 × miles × (prediction − actual fee), then average the three results. At w = 0 the misses are −2, −5 and −6, so the three terms are −4, −20 and −36, and their average is −20. A negative gradient means the loss goes down as w goes up, so downhill is "raise w".

How big a step to take is set by the learning rate, a number you choose. The update rule is the entire algorithm:

new w = old w − learning rate × gradient

With a learning rate of 0.05, the first step goes from 0 to 0 − 0.05 × (−20) = 1. At w = 1 the misses are −1, −3 and −3, the gradient works out to −10.67, and the next step lands on 1 + 0.05 × 10.67 = 1.533. Keep going and you get this:

StepwLossGradientChange in w
0021.67−20.00+1.000
11.0006.33−10.67+0.533
21.5331.97−5.69+0.284
31.8180.73−3.03+0.152
41.9690.38−1.62+0.081
52.0500.28−0.86+0.043
102.1390.238−0.04+0.002
A U-shaped curve of loss against w, the price per mile. Loss is 21.7 at w = 0 and lowest, 0.24, at w = 2.14. Dots mark gradient descent's first steps at w = 0, 1, 1.53, 1.82 and 1.97, each a smaller step closer to the bottom.lossstart: w = 0, loss 21.7step 1: w = 1best: w = 2.1401234w, the price per mile ($)
Gradient descent on the courier example, learning rate 0.05. Each dot is one step.

Look at the last column of the table. The learning rate never changed, yet the steps shrink on their own, because the slope gets gentler near the bottom. Here each step closes about 47% of the remaining gap to the best value, about 2.143, or $2.14 a mile. By step 10, w is within half a cent of it. That's what Google's course calls convergence: when a model converges, additional iterations don't reduce loss more.

For a problem this small you could find the best w with algebra instead: add up miles × fee (30), divide by the sum of miles squared (14), and you get 2.143. A neural network has no such shortcut, but gradient descent still works there because it only ever needs the local slope. Every parameter gets its own gradient, and a procedure called backpropagation computes all of them in one backward sweep through the network. Our explainer on what a neural network is runs one backpropagation step by hand.

Picking the step size: the learning rate

The learning rate is a hyperparameter: a setting you choose before training, as opposed to a parameter the model learns. Google's course defines it as a floating point number you set that influences how quickly the model converges. Here's the courier problem with three different choices, all starting from w = 0:

Learning ratew after steps 1, 2, 3, 4Loss after 4 stepsWhat happens
0.0050.100, 0.195, 0.286, 0.37314.86Crawls: only 0.81 after 10 steps
0.051.000, 1.533, 1.818, 1.9690.38Settles near 2.14 in about 10 steps
0.255.000, −1.667, 7.222, −4.630214.3Overshoots further on every step

At 0.25, every step jumps clean over the bottom of the bowl and lands higher up the far side than where it started. The loss goes 21.7, 38.3, 68.0, 120.6, 214.3 and keeps climbing. Google's course describes exactly this: a learning rate that's too large never converges because each iteration either causes the loss to bounce around or continually increase. For this problem the cutoff works out to about 0.21. Between roughly 0.11 and 0.21, w zigzags back and forth across the bottom but still settles. Above 0.21 it blows up.

CS231n calls the learning rate one of the most important (and most headache-inducing) hyperparameter settings in training a neural network. Good values don't carry over from one model to another, because the right step depends on how sharply that particular loss curves. Even inside one paper they move: according to Table 2.1 of the GPT-3 paper, its smallest model used a peak learning rate of 0.0006 and its largest used 0.00006, ten times smaller.

Batches and epochs: how training scales up to huge datasets

The courier model looked at all three deliveries before every step. With a million examples, that would mean a million predictions per step. So real training estimates the slope from a small random handful of examples instead, called a batch. In Google's description of mini-batch stochastic gradient descent, the model chooses the examples included in each batch at random, averages their gradients, then updates the parameters once per batch. Each estimate is a little noisy but far cheaper, and many cheap steps usually beat a few exact ones. CS231n notes that for a large image dataset a typical batch contains 256 examples from the entire training set of 1.2 million.

An epoch is one full pass through the training data. Google's course does the arithmetic: given a training set with 1,000 examples and a mini-batch size of 100 examples, it will take the model 10 iterations to complete one epoch. Train for 20 epochs and the parameters get updated 200 times. Learning rate, batch size and number of epochs are the three settings PyTorch's beginner tutorial sets before it trains anything: a learning rate of 0.001, batches of 64, and 5 epochs (10 in its final run).

In code, the tutorial's loop looks like this, lightly simplified:

for epoch in range(epochs):
    for inputs, answers in batches:
        predictions = model(inputs)
        loss = loss_fn(predictions, answers)
        loss.backward()        # backpropagation: a gradient for every parameter
        optimizer.step()       # move every parameter a little downhill
        optimizer.zero_grad()  # clear the gradients before the next batch

The same loop at GPT-3's scale

Large language models run this exact loop with much bigger numbers. Their label for each example is simply the next token of real text, as our guide to how large language models work explains. The GPT-3 paper's appendix lists the training settings. The optimizer was Adam, a widely used variant of gradient descent. The learning rate warmed up over the first 375 million tokens, then slowly decayed to a tenth of its peak. And the batch size grew from a small value (32k tokens) to the full value over the first 4-12 billion tokens. For the largest model, the full value was 3.2 million tokens per batch, and every model size trained on 300 billion tokens in total. Divide one by the other and you get roughly 94,000 updates (a few more in practice, since the early batches were smaller), most of them averaging the gradient over 3.2 million next-token guesses.

"Epoch" gets fuzzy at that size. GPT-3's training mix drew more often from sources the team judged higher quality, so, in the paper's words, some datasets are seen up to 3.4 times during training while other datasets are seen less than once. The filtered web crawl that made up 60% of the mix got through only 0.44 of an epoch.

Why the data is split into training, validation and test sets

A model graded on its own training data can cheat without meaning to. The scikit-learn documentation is blunt about it: learning the parameters of a prediction function and testing it on the same data is a methodological mistake. A model that just repeated the labels it had seen would score perfectly and still be useless on anything new. So before training starts, the data gets divided into three groups with different jobs:

SetWhat it's forWhen you look at itShare in Google's example
TrainingThe only data gradient descent fits the parameters toEvery step70%
ValidationComparing choices: learning rate, model size, when to stopAfter each experiment15%
TestA final check on the one model you pickedIdeally once, at the end15%

The percentages come from an example split in Google's course. They're a common starting point, not a rule.

Why three sets and not two? Because every time you check the test score and change something in response, a little information about the test set leaks into your choices. The scikit-learn docs warn that when you tune settings there's a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. The validation set soaks up that tuning, so the test set stays a fair exam. Even then, Google's course notes that test sets and validation sets still "wear out" with repeated use.

The other way a test set goes bad is overlap. If the same example sits in both the training and test data, part of the test is a memory check. Google's course says to delete any examples in the validation set or test set that are duplicates of examples in the training set. At web scale that's harder than it sounds. The GPT-3 team searched their training text for copies of the benchmark questions they planned to test on, then reported that a bug in the filtering caused us to ignore some overlaps, and due to the cost of training it was not feasible to retrain the model. They spent a section of the paper measuring how much the leftover overlap affected their results.

Overfitting: when a lower training loss makes a worse model

Google's course defines overfitting as creating a model that matches (memorizes) the training set so closely that the model fails to make correct predictions on new data.

Take the courier data from earlier (1 mile for $2, 2 miles for $5, 3 miles for $6) and swap the one-parameter line, fee = w × miles, for a model with three parameters: fee = a × miles² + b × miles + c. Three parameters and three deliveries means it can hit every point exactly, with a = −1, b = 6 and c = −3. Check it: 1 mile gives −1 + 6 − 3 = $2, 2 miles gives −4 + 12 − 3 = $5, and 3 miles gives −9 + 18 − 3 = $6. Training loss: exactly 0. The straight line's best was 0.238, so on the training numbers the curve wins.

Now bring in a fourth delivery that neither model trained on: 4 miles for $9 (made up, like the other three). That's a one-example validation set.

ModelParametersTraining lossPredicts for 4 miles (actual: $9)Predicts for 6 miles
Straight line, $2.14 a mile10.238$8.57$12.86
Curve through every point30$5.00−$3.00
Fee against miles. Filled dots are the training deliveries (1 mile $2, 2 miles $5, 3 miles $6); a hollow dot is the held-out delivery, 4 miles $9. A straight line at $2.14 a mile passes near all four. A dashed curve hits the three training dots exactly, predicts $5 at 4 miles and falls to minus $3 at 6 miles.fee ($)0612line: $2.14 a mileheld out: 4 mi, $9off by $4training datacurve: −$3 at 6 mi02 mi4 mi6 mi
The curve has zero training loss and is the worse model. The straight line misses every training delivery slightly and gets the held-out one within 43 cents.

To pass through all three training points, the curve has to bend, and past 3 miles it turns downward. It predicts that a 4-mile trip costs less than a 3-mile one, and that at 6 miles the courier pays you. It fit the three examples perfectly and learned nothing about pricing. Training loss is only a stand-in for what you want, which is generalization: in Google's words, a model that generalizes well makes good predictions on new data.

How overfitting shows up during training

With a real model you can't eyeball the fit, so you watch two numbers as training runs: training loss and validation loss. Early on, both fall together. The warning sign, as Google's course describes it, is when loss declines or holds steady (converges) for the training set, but increases for the validation set. CS231n makes the same point with accuracy: the gap between the training and validation accuracy indicates the amount of overfitting. The usual fixes:

  • Stop early. Google's course describes early stopping as ending training before the model fully converges, for instance once validation loss starts rising. You keep the parameters from the point where validation loss was lowest.
  • Use a simpler model, with fewer parameters or fewer inputs, so it has less room to memorize. That's the line versus the curve.
  • Get more data. A three-parameter curve can hit three points exactly. It can't hit three thousand, so it has to settle for the general trend.
  • Regularize. One common kind of regularization adds a penalty for large parameter values, nudging the model toward simpler fits. GPT-3 used a mild version called weight decay to provide a small amount of regularization, and its team removed near-duplicate documents from the training data, partly to prevent overfitting.

The simple story says a model with more parameters than examples will memorize them, yet big neural networks often have more parameters than training examples and still do well on new data. A 2017 paper on this puzzle showed that standard image networks trained with stochastic gradient methods easily fit a random labeling of the training data, memorizing labels that were pure noise. They can overfit spectacularly, and on real data they mostly don't. Exactly why is still an open research question, so the practical rule stands: judge a model on validation and test data, never on training loss alone.

Where beginners go wrong about how AI models are trained

  • "Lower training loss means a better model." A model can memorize its examples, score a perfect 0 and still be useless; the three-parameter courier curve above did exactly that, then predicted a negative fee. The number to trust is the loss on data the model didn't train on.
  • "The model stores its training data." Training changes parameters; the examples themselves aren't kept. Large models can still memorize some passages almost word for word, which is why the GPT-3 paper worried about models with the capacity to memorize vast amounts of content having already seen the test questions.
  • "Gradient descent finds the best possible answer." The one-parameter courier model's loss is a single smooth bowl, so walking downhill with a sensible learning rate always reaches the bottom. A neural network's loss is more like the hiker's hilly terrain, full of dips and flat stretches. Gradient descent finds a good low spot with no guarantee it's the lowest one, which is one reason the same network trained twice from different random starting values ends up with different parameters.

Common questions

What's the difference between a parameter and a hyperparameter?

Parameters are the numbers the model learns during training, like the price per mile in the courier example. Hyperparameters are settings you choose before training, such as the learning rate, batch size and number of epochs. You usually compare different hyperparameter choices on the validation set.

What's the difference between training and inference?

Training adjusts a model's parameters using examples and a loss. Inference is using the finished model to make predictions, with its parameters frozen. Training happens once or occasionally and is expensive; inference happens every time someone uses the model.

What is an epoch in machine learning?

An epoch is one full pass through the training data. With 1,000 examples and batches of 100, one epoch is 10 parameter updates. Small models often train for many epochs, while GPT-3 saw some of its data sources less than once.

Is fine-tuning the same as training?

Fine-tuning is more training, started from a model that's already trained instead of from random parameters. It usually uses a much smaller, focused dataset and runs the same loop: predict, score with a loss, update the parameters.

Learn it properly

This article trained a one-parameter model by hand. Machine Learning, Demystified builds from there in short lessons with exercises: how machines learn from examples, deep learning and backpropagation, tensors and how models train, and bias, variance and regularization. Along the way you train a model yourself and watch it overfit.

See Machine Learning, Demystified in the Toorova catalog →

Sources

  1. Linear regression: Loss · Google Machine Learning Crash Course
  2. Linear regression: Gradient descent · Google Machine Learning Crash Course
  3. Linear regression: Hyperparameters · Google Machine Learning Crash Course
  4. Datasets: Dividing the original dataset · Google Machine Learning Crash Course
  5. Overfitting · Google Machine Learning Crash Course
  6. Overfitting: Regularization · Google Machine Learning Crash Course
  7. CS231n: Optimization, Stochastic Gradient Descent · Stanford University
  8. CS231n: Neural Networks Part 3, Learning and Evaluation · Stanford University
  9. Optimizing Model Parameters · PyTorch Tutorials
  10. Cross-validation: evaluating estimator performance · scikit-learn documentation
  11. Language Models are Few-Shot Learners (GPT-3), abstract · Brown et al., arXiv, 2020
  12. Language Models are Few-Shot Learners (GPT-3), full paper · Brown et al., arXiv, 2020
  13. Understanding deep learning requires rethinking generalization · Zhang et al., ICLR 2017 (arXiv)

Read next