Skip to content
AI13 min read

AI model training: how to train an AI model, from data to deployment

AI model training is the process of adjusting a model's parameters until its outputs match examples. Here is how it works step by step, how LLMs are trained, what training data you need, and a tested PyTorch loop you can run in seconds.

By

Editor

Published

Cover image for “How to train an AI model”: Step by step, with tested code, illustrated with a neural network.

The short answer

AI model training is the process of showing a model many examples, measuring how wrong its outputs are with a loss function, and nudging its internal numbers (parameters) to reduce that error, over and over. You prepare data, pick a model, run the training loop, check results on held-out data, then deploy and monitor. Most businesses fine-tune an existing model rather than train one from scratch.

Every AI product you use started as a model that knew nothing. A spam filter, a fraud score and a chatbot all became useful through the same basic process, called training. Most guides to "how to train an AI model" either stay at slogan level ("feed it data") or turn into a sales pitch, and few show what actually happens inside the loop.

This guide covers the whole process: what training does to a model, the steps from raw data to a deployed model, a short PyTorch training loop we ran and whose output we show, how large language models are trained in stages, what good training data looks like and the legal questions around it, and how to decide whether your business should prompt, retrieve, fine-tune or train from scratch.

What is AI model training?

AI model training is the process of adjusting a model's parameters until its outputs match the examples it is shown. A model is a function with adjustable numbers inside it, called parameters or weights. Before training those numbers are random, so the outputs are nonsense. Training fixes that through a loop that repeats thousands or millions of times:

  1. Predict. Feed the model a batch of examples and collect its outputs.
  2. Measure the error. A loss function turns the gap between the outputs and the correct answers into one number. Lower is better.
  3. Work out which way to move. Backpropagation calculates, for every parameter, whether nudging it up or down would reduce the loss.
  4. Update. An optimizer moves each parameter a small step in that direction. The size of the step is set by the learning rate.

One full pass over the training data is called an epoch. Settings you choose rather than learn, such as the learning rate, batch size and number of epochs, are hyperparameters. If you want the bigger picture of what a model is before going further, start with our explainer on what an AI model is, which trains a two-parameter model in scikit-learn.

How to train an AI model, step by step

The lifecycle is the same whether you are building a churn predictor or adapting a language model. What changes is the scale of each step. Our guide to machine learning in financial forecasting shows the same loop applied to one domain.

  1. Define the task and the metric. Write down what goes in, what should come out and how you will judge it: accuracy, error in minutes, a human rating. A model cannot hit a target nobody defined.
  2. Collect training data you have the right to use. Gather examples that look like the real inputs the model will see, and record where each source came from and under what license.
  3. Clean, label and split the data. Remove duplicates and errors, add correct answers where the task needs them, and set aside a validation set and a test set the model never trains on. Duplicates leaking from training into the test set make results look better than they are.
  4. Choose a model. A simple model for tabular data, a neural network for images, audio or text, or, most often for language tasks, an existing pre-trained model to fine-tune.
  5. Train. Run the loop above, watching both training loss and validation loss.
  6. Evaluate and tune. Compare against a simple baseline, adjust hyperparameters using the validation set, then check the final model once on the test set.
  7. Deploy and monitor. Serve the model behind an app or API, log its inputs and outputs, and retrain when performance drifts.
Seven steps of AI model training: define the task and metric, collect data you have the right to use, clean label and split it, choose a model, train, evaluate and tune, then deploy and monitor, looping back to retrain when performance drifts.
The AI model training lifecycle. Steps 2 and 3, the data work, usually take the most time.

Steps 2 and 3 usually take the most time. A clever architecture rarely rescues bad data, while a plain model trained on clean, representative data often performs well.

A real training loop you can run (tested)

Here is the whole idea in just over 40 lines of PyTorch, the open-source deep learning library used to train many modern models. The script trains a small neural network to fit a noisy curve, keeps 20 of the 60 points aside for validation, and uses early stopping to keep the best version. The data is synthetic, generated by the script itself. We ran it with Python 3.13 and PyTorch 2.15.0 on a two-core CPU, and it finished in under five seconds.

train_loop.py: a complete training loop with a validation split and early stopping (tested)
import torch
from torch import nn

torch.manual_seed(0)

# 1. Data (synthetic, made up for this demo): a noisy curve, y = sin(x) + noise.
x = torch.linspace(-3, 3, 60).unsqueeze(1)
y = torch.sin(x) + 0.3 * torch.randn_like(x)

# 2. Split: hold out data the model never trains on.
idx = torch.randperm(len(x))
train_idx, val_idx = idx[:40], idx[40:]
x_train, y_train = x[train_idx], y[train_idx]
x_val, y_val = x[val_idx], y[val_idx]

# 3. Model: a small neural network with randomly initialized parameters.
model = nn.Sequential(nn.Linear(1, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1))
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)  # learning rate is a hyperparameter

best_val, best_epoch, best_state = float("inf"), 0, None
for epoch in range(1, 2001):
    # 4. Training step: predict, measure error, backpropagate, update.
    model.train()
    loss = loss_fn(model(x_train), y_train)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    # 5. Evaluation on held-out data, without updating anything.
    model.eval()
    with torch.no_grad():
        val_loss = loss_fn(model(x_val), y_val).item()
    if val_loss < best_val:
        best_val, best_epoch = val_loss, epoch
        best_state = {k: v.clone() for k, v in model.state_dict().items()}
    if epoch in (1, 50, 100, 200, 500, 1000, 2000):
        print(f"epoch {epoch:4d}  train loss {loss.item():.3f}  val loss {val_loss:.3f}")

# 6. Early stopping: keep the parameters from the best validation epoch.
model.load_state_dict(best_state)
print(f"best val loss {best_val:.3f} at epoch {best_epoch}; restored those weights")
print(f"trainable parameters: {sum(p.numel() for p in model.parameters()):,}")

After pip install torch, running python3 train_loop.py printed exactly this (the fixed random seed makes it repeatable on the same setup):

Output
epoch    1  train loss 0.777  val loss 0.541
epoch   50  train loss 0.107  val loss 0.127
epoch  100  train loss 0.070  val loss 0.067
epoch  200  train loss 0.061  val loss 0.098
epoch  500  train loss 0.035  val loss 0.110
epoch 1000  train loss 0.009  val loss 0.068
epoch 2000  train loss 0.000  val loss 0.099
best val loss 0.058 at epoch 887; restored those weights
trainable parameters: 4,353

Read the two loss columns side by side, because they tell the most important story in model training:

  • Early on, both losses fall together. By epoch 100 the model has learned the shape of the curve, and validation loss has dropped from 0.541 to 0.067.
  • Then the model starts memorizing. By epoch 2000, training loss is 0.000: the network passes through every training point, noise included. Validation loss is 0.099, worse than its best. That gap is overfitting, and it is why you never judge a model on the data it trained on.
  • Early stopping keeps the good version. Validation loss is bumpy along the way, which is normal with this little data. The script saved the parameters from the epoch with the lowest validation loss (epoch 887) and restored them at the end. Large training runs do the same thing with checkpoints.
  • The loop is the same one used for LLMs. optimizer.zero_grad(), loss.backward() and optimizer.step() are the predict, measure and adjust steps. A frontier model runs this loop on trillions of tokens across thousands of chips instead of 40 points on one CPU, but the logic does not change.

How large language models are trained: pre-training, fine-tuning and RLHF

Large language models go through the same loop, but in stages, each with different data. Our guide to what LLM stands for explains next-token prediction itself; here is how the training pipeline fits together.

The main stages of LLM training
StageTraining dataWhat the model learnsRelative cost
Pre-trainingHuge amounts of general text and code, often trillions of tokensGrammar, facts, reasoning patterns, by predicting the next tokenBy far the largest: months on large GPU clusters
Supervised fine-tuning (SFT)Thousands of example prompts with good responses written by peopleTo follow instructions and answer in a helpful formatMuch smaller
Preference tuning (RLHF or similar)Human rankings of several model answers to the same promptWhich answers people prefer, including safer and more useful onesSmall compared with pre-training
Task fine-tuning (optional)Your own examples for one jobYour format, tone or domainSmall, especially with LoRA

The SFT and preference stages were popularized by work such as OpenAI's 2022 InstructGPT paper led by Long Ouyang. The team first collected labeler demonstrations (opens in a new tab) to fine-tune GPT-3 with supervised learning, then collected rankings of model outputs to fine-tune it further with reinforcement learning from human feedback. The result showed how much these later stages matter:

outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3, despite having 100x fewer parameters.
Ouyang et al., Training language models to follow instructions with human feedback (2022)

How much data and compute pre-training uses

Pre-training size is a budgeting decision: for a fixed amount of compute, you can train a bigger model on less data or a smaller model on more. DeepMind's 2022 Chinchilla paper, led by Jordan Hoffmann, found that model size and training tokens should be scaled equally (opens in a new tab): for every doubling of model size, the number of training tokens should also double. Its 70-billion-parameter Chinchilla model, trained on four times more data than the larger Gopher, outperformed Gopher (280B) and GPT-3 (175B) on a wide range of tasks.

The scale at the frontier keeps growing. Epoch AI, a research group that tracks AI trends, estimates that training compute for frontier language models (opens in a new tab) has grown about 5 times per year since 2020, and that the cost to train them has risen about 3.5 times per year. Stanford's 2026 AI Index (opens in a new tab) reports that leading models were trained "on tens of trillions of tokens over periods exceeding 100 days," and notes that parameter counts "have stayed near 1 trillion for three years." The same report says most frontier labs no longer disclose dataset sizes or training duration, so many public figures are estimates.

A model that large does not fit on one chip, which is where distributed training comes in. Training platforms split the work across many GPUs: each copy of the model can process different batches of data in parallel, or the model itself can be split across chips. For a business fine-tuning a model, managed AI platforms handle this behind the scenes; you rarely need to configure it unless you train very large models yourself.

AI training data: quality, quantity and licensing

The model learns whatever patterns the data contains, including mistakes and biases. That makes training data the part of AI model training you control most, and the part most worth getting right.

What good training data looks like

  • Representative. It matches the inputs the model will see in real use: the same languages, formats, customer types and edge cases.
  • Correctly labeled. Wrong answers in the training set teach wrong answers. Spot-check labels, and have two people label a sample to see how often they disagree.
  • Deduplicated and separated. No copies of test examples in the training set, or your evaluation will be too optimistic.
  • Balanced enough. If 99% of transactions are legitimate, a model that always says "legitimate" is 99% accurate and useless. Measure what matters for the rare cases.
  • Documented. Record sources, dates, licenses and any personal data, so you can answer questions later.

Quality beats volume for fine-tuning. OpenAI's fine-tuning guide says the minimum number of examples is 10 (opens in a new tab) and recommends starting with 50 well-crafted demonstrations and evaluating the results before adding more. If 50 good examples do not help, more of the same rarely will; rethink the task or the prompt first.

Where training data comes from now carries real legal and financial weight. In July 2026 a US federal court gave final approval to the Bartz v. Anthropic class settlement. According to the Association of American Publishers (opens in a new tab), it requires Anthropic to pay $1.5 billion to the authors and publishers of nearly half a million books downloaded from pirate sites, and to destroy the original files and copies made from them. The lesson for anyone building a dataset: how you acquire data matters, not just what you do with it.

Regulation is adding disclosure duties too. The European Commission published a mandatory template (opens in a new tab) in July 2025 for providers of general-purpose AI models to publicly summarize the data used to train their models, listing main data collections and other sources, with EU rules for these models applying from 2 August 2025. Copyright law on AI training is still unsettled and differs by country, so treat the checklist below as a starting point, not legal advice:

  • Use data you own, data licensed for training, or public-domain and openly licensed data whose license allows your use.
  • Keep a record of every source, its license and the date you collected it.
  • Do not download from piracy sites or scrape behind logins or paywalls.
  • Remove or protect personal data, and check privacy rules such as GDPR where they apply.
  • Read the license of any pre-trained model you fine-tune; open weights do not always permit commercial use.

How a business can train or fine-tune its own model

"Train our own AI model" usually means one of four things, and the cheapest one that works is the right choice. Try them roughly in this order.

Prompting, RAG, fine-tuning or training from scratch
ApproachWhat changesBest forData neededCost and effort
PromptingOnly the instructions you sendMost tasks; always try firstA few examples in the promptLowest
RAG (retrieval)The documents the model reads at question timeAnswers grounded in your own, changing documentsYour documents, no labelsLow to medium
Fine-tuning (often LoRA)A small set of extra or adjusted parametersA consistent format, tone or narrow skill that prompting cannot holdDozens to thousands of good examplesMedium
Training from scratchEvery parameterUnique data types or very large organizationsMillions of examples to trillions of tokensHighest by far

Two notes on the middle options. Retrieval is often what people actually need when they say "train it on our documents": the model stays the same and looks up your current content each time, as explained in our guide to RAG in AI. Better prompts are the cheapest fix of all; our Claude prompt engineering guide shows techniques that work across models.

Fine-tuning has become far cheaper thanks to parameter-efficient methods. LoRA, introduced in a 2021 paper led by Edward Hu, freezes the original model and trains small add-on matrices instead. Compared with fully fine-tuning GPT-3 175B, the authors report that LoRA can reduce trainable parameters by 10,000 times (opens in a new tab) and the GPU memory requirement by 3 times. That is why teams can now fine-tune open-weight models on a single GPU, and why a fine-tuned small language model is often cheaper to run than a large general one.

Common AI model training mistakes

  • Judging the model on its training data. Our demo reached zero training loss while getting worse on new data. Always report validation and test results.
  • No baseline. Compare against a simple rule or the plain pre-trained model. If training does not beat it, you have learned something cheaply.
  • Fine-tuning before setting up evaluation. Build a fixed set of test cases first, so you can tell whether each change helps.
  • Training on data you cannot defend. Unclear licenses and personal data are harder to fix after a model ships than before.
  • Forgetting the model ages. Products, prices and customer language change. Schedule re-evaluation and retraining.

If you want to build the skills to do this yourself, our step-by-step path on how to learn machine learning lists free courses, and machine learning for beginners covers the core concepts in plain English.

The bottom line

AI model training is one loop, predict, measure the error and adjust, run on data until the model generalizes to examples it has never seen. The hard parts are around the loop: clean, representative and properly licensed training data, honest evaluation on held-out sets, and choosing the cheapest approach that works. For most businesses that means better prompts or retrieval first, fine-tuning with a method like LoRA second, and training from scratch almost never. For more practical explainers on models, agents and tools, browse our AI guides.

Common questions

How do you train an AI model?

Define the task and how you will measure success, collect and clean data, split off validation and test sets, choose a model or a pre-trained base model, run the training loop, then evaluate on the held-out data before deploying. Keep monitoring after launch, because real-world data drifts.

How long does it take to train an AI model?

It ranges from seconds to months. The small network in this guide trains in under five seconds on an ordinary CPU, while Stanford's 2026 AI Index reports that leading models are trained on tens of trillions of tokens over periods exceeding 100 days.

How much training data do you need?

It depends on the task and on whether you start from a pre-trained model. Fine-tuning can work with very little: OpenAI's fine-tuning guide sets a minimum of 10 examples and recommends starting with 50 well-crafted ones. Training a large language model from scratch needs trillions of tokens.

What is the difference between training and fine-tuning?

Training from scratch starts with random parameters and learns everything from your data. Fine-tuning starts from a model that is already trained and continues training on a smaller, task-specific dataset, which is far cheaper and is what most teams actually do.

What is AI training data?

It is the set of examples a model learns from: text, images, audio or tables, often paired with the correct answer (a label). Its quality, coverage and legal right to use matter as much as the model choice.

Can I train an AI model on copyrighted data?

That is legally unsettled and varies by country, so get legal advice for anything commercial. How data is acquired matters a lot: Anthropic agreed to pay $1.5 billion over books downloaded from pirate sites, and the EU now requires general-purpose model providers to publish a summary of their training content.

Sources

  1. Trends in Artificial Intelligence, Epoch AI
  2. AI Index Report 2026, Chapter 1: Research and Development, Stanford HAI
  3. Training language models to follow instructions with human feedback, arXiv (Ouyang et al.)
  4. Training Compute-Optimal Large Language Models, arXiv (Hoffmann et al.)
  5. LoRA: Low-Rank Adaptation of Large Language Models, arXiv (Hu et al.)
  6. Supervised fine-tuning, OpenAI API documentation
  7. AAP Welcomes Court's Final Settlement Approval in Bartz v. Anthropic, Association of American Publishers
  8. Commission presents template for General-Purpose AI model providers to summarise the data used to train their model, European Commission

About Marcus E.

Qualified software engineer with 10+ years of experience building payments and machine learning infrastructure

Marcus is a qualified software engineer who spent 10+ years building payment and machine learning infrastructure before joining GeeklyPlug. He writes AI and technology guides, with a focus on models, machine learning and the tools developers use.

ai model trainingtraining datafine-tuningmachine learningllms

Keep reading

More from AI, then the rest of the archive.