OpenAI disclosed in 2020 that training GPT-3 used about 3.14 million compute hours on specialized GPU clusters and cost several million dollars. The model never encountered the real world, never spoke in a conversation and never experienced anything.

The system ran through 570 gigabytes of text (about 400 billion tokens) and adjusted billions of numerical parameters until what it had learned could predict the next word in a sequence with remarkable accuracy.

That process (turning raw data into a system that can generate coherent text, identify images, or recommend products) is what we mean by "training" an AI model. Understanding how it works demystifies much of what AI can and cannot do.

Training is not programming in the usual way. In a traditionally programmed system, rules that are explicit govern what happens next. If condition A is true, take action B. An AI model trained through training has no explicit rules.

The model has instead billions of numerical parameters known as weights. These were adjusted step by step to minimize the error between what the model outputs and the correct outputs across a large training dataset.

The weights encode, in a distributed and opaque way, whatever statistical regularities exist in the training data that are useful for the task.

Rule-based programming differs from learned parameters in what gives AI models their character. Complex or context-dependent tasks that cannot be stated as explicit rules get done by them, such as face recognition or language translation. Meanwhile, the model fails in ways an explicitly programmed system would never fail. It asserts false facts with confidence and it fails on small changes to its input.


"Training a machine learning model is the process of finding a set of parameters that minimizes prediction error on a dataset.[6] Everything else (architecture choices, regularization, optimization algorithms) exists in service of that single goal."

Andrej Karpathy, 2022

The Core Training Loop

Training ParadigmDescriptionData RequirementTypical Use Case
Supervised learningModel trains on labeled input-output pairs; minimizes prediction errorLarge labeled dataset; labeling is often expensiveImage classification, spam detection, sentiment analysis
Unsupervised learningModel finds structure in unlabeled data; no explicit labels neededLarge unlabeled datasetClustering, dimensionality reduction, anomaly detection
Self-supervised learningModel generates its own labels from structure in the dataLarge unlabeled dataset (labels implicit in structure)Language model pre-training (predict next word); masked image modeling
Reinforcement learningAgent learns by receiving rewards for actions in an environmentReward function and simulated or real environmentGame-playing AI, robotics control, recommendation optimization
Reinforcement learning from human feedback (RLHF)Human preferences used to train reward model that guides policy optimizationHuman preference ratings on model outputsFine-tuning large language models for helpful, harmless behavior
Transfer learningModel pre-trained on large dataset is fine-tuned on smaller domain-specific datasetSmall labeled domain dataset plus large pre-training datasetAdapting general LLMs to medical, legal, or domain-specific tasks

Whatever the particular model type or task, training an AI model follows the same logical pattern. Once the loop is grasped, how training works and what limits it become clear.

The Four-Step Training Loop

Step 1, forward pass. In this step, the model takes in an input such as text, an image or a data sequence and generates an output using its present parameter values. A language model would take the first part of a sentence as input and give as output its prediction of what follows.

An image classifier takes an image as input and gives as output a probability distribution over possible categories.

Step 2, loss calculation. In supervised learning the model output goes against the correct answer that is the label and in self-supervised language model training it goes against the next token.

Prediction minus correct answer is measured as a "loss" that is a single number showing how wrong the model was. Cross-entropy loss is what a model uses for classification and mean squared error is what it uses for regression.

Step 3: Backward pass (backpropagation) - The loss is used to calculate gradients: numerical values for each model parameter indicating how much the loss would change if that parameter were increased or decreased slightly.

Rumelhart, Hinton and Williams brought backpropagation as a practical training algorithm into use in the 1980s. It efficiently calculates the gradients by sending error signals backward through the neural network from output to input.[7]

Step 4: Parameter update. In this step, each parameter is moved slightly in the direction that would cut the loss. How much each move is controlled by the learning rate, which is a hyperparameter that decides how quickly the model adjusts in reaction to each training sample.

An optimizer makes this adjustment and the most widely used ones are variants of Stochastic Gradient Descent (SGD). Adam is one of them and it adapts the learning rate for each parameter according to the history of gradients.

The four-step loop runs through millions or billions of iterations and in each one the model sees a batch of training examples and its parameters get adjusted.

As time goes on, the model's parameters move closer to values that give low loss on the training data. That means the model has "learned" the patterns found in that data.

What the Model Actually Learns

Instead of a set of explicit rules what comes out of this process is a distributed representation. That is a pattern of weights across the network together encoding statistical regularities in the training data.

Weights in a language model trained on text capture the statistical structure of language that includes grammar, factual connections, common reasoning patterns as well as the characteristic style of different kinds of writing.

The model does not have a rule that says "don't put an adjective after a period and before a noun" - it has weights that make grammatically incorrect sequences statistically unlikely in its outputs.

For an image classifier: the weights encode visual features that distinguish one category from another. Early layers of the network learn low-level features like edges and colors; later layers combine these into more abstract features like textures and shapes; the final layers combine these into category-specific representations.

The distributed and statistical way models learn accounts for both their power and their limitations. Patterns too complex and context dependent to write as explicit rules can be recognized by them. At the same time they cannot reliably tell apart real statistical patterns from spurious correlations in the training data.


Types of Learning

Dependent on how much labeled data is available and what the learning task is, the training approach changes markedly.

Supervised Learning

In supervised learning, the model is trained on a dataset where each input comes with a known correct output (label) that the model learns to match. It does this by minimizing the loss between what the model predicts and what the labels say.

Supervised learning calls for labeled data. That means human-annotated examples of the correct output for each input and making up this labeled data is most often expensive and time consuming.

Crowd-sourced annotation efforts had to be huge to build image classification datasets such as ImageNet (1.4 million images labeled across 1,000 categories). Thousands of images need to be labeled by expert physicians for medical AI datasets.

Applications. Image classification, object detection, named entity recognition, sentiment analysis, spam detection and fraud detection. Any task where you can define what the correct output should be and gather enough labeled examples.

Example: When Gmail users clicked Report spam, millions of labeled emails (spam versus not spam) went into Google's supervised learning to develop a spam filter for Gmail. Patterns in email content, sender details and metadata that pointed to whether users would mark an email as spam were what the model learned. This was crowdsourced labeling and the training data got updated continuously with new examples.

Unsupervised Learning

In unsupervised learning, the model is trained on unlabeled data to discover structure or patterns without being given correct answers. The model must find regularities in the data on its own.

Clustering methods such as K-means and DBSCAN group similar data points together without beginning with any predefined categories. Dimensionality reduction tools including PCA, t-SNE and UMAP find low-dimensional representations of high-dimensional data that hold onto what is important.

Generative models, including autoencoders and variational autoencoders, learn to compress and then reconstruct data and in doing that they capture the essential structure of how the data is distributed.

Without enough labeled data or when it costs too much, unsupervised learning becomes useful yet it is harder to measure how well the model performs. There is no clear right answer so telling if the model has picked up anything meaningful needs domain expertise as well as thorough analysis.

Self-Supervised Learning

Self-supervised learning occupies a middle ground between supervised and unsupervised learning. The model is trained to predict some part of the input from other parts, creating a supervised learning signal from unlabeled data by using the data itself as labels.

Language models train the model to predict the next word from all that came before (like GPT-style models do) or to fill in masked words from the context around them (like BERT-style models do).

Since the training signal comes straight out of the text itself where the actual next word becomes the label and no human annotation is required, this makes it possible to train on text corpora as large as the internet.

For vision: models can be trained to predict the color of an image from its grayscale version, to predict the relative positions of image patches, or to predict one view of a scene from another. These pretext tasks require no labels while forcing the model to learn useful visual representations.

Self-supervised learning is the paradigm that enabled the scale of current large language models. Training on hundreds of billions of tokens of unlabeled text from the internet would be impossible if each token required human annotation.

Example: The development of BERT (Bidirectional Encoder Representations from Transformers) by Google in 2018 demonstrated the power of self-supervised pre-training for language understanding. BERT was pre-trained on 3.3 billion words of text using masked language modeling (predicting randomly masked words) and next sentence prediction.

Once pre-trained, the model could be fine-tuned on small labeled datasets for specific tasks such as question answering, sentiment analysis and natural language inference. It went on to perform far better than models that were trained from scratch on those same small datasets.

BERT's success put self-supervised pre-training followed by supervised fine-tuning at the center of the paradigm for language AI.

Reinforcement Learning

In reinforcement learning (RL), an agent learns to take actions in an environment to maximize cumulative reward. Unlike supervised learning (where correct outputs are provided) or unsupervised learning (where structure is discovered), RL learns from the consequences of actions.

Actions by the agent bring in reward signals that are positive for good outcomes and negative for bad ones. The agent uses them to update its policy (the function that maps states to actions) in order to maximize what it expects to gain in the future.

Feedback comes late and is sparse and this is the challenge. A chess-playing agent does not know which moves were good until the game is over.

Reinforcement learning applications: Game playing (AlphaGo, AlphaStar), robotics control, recommendation systems optimization, and, critically, the alignment training of large language models through Reinforcement Learning from Human Feedback (RLHF).

Example: In 2017, DeepMind's AlphaGo Zero was trained entirely through self-play reinforcement learning that started with random play. In 40 days developed superhuman Go skills without using any human game data.[5] Games were played against earlier versions of itself and win/loss gave the reward signal for the training loop.

The result was a player that developed strategies that human Go players had never discovered in thousands of years of playing the game.


The Architecture of Modern Language Models

Understanding what is being trained requires understanding the Transformer architecture, which underlies virtually all state-of-the-art language models since its introduction in 2017.[1]

The Transformer Architecture

In the paper "Attention Is All You Need," Vaswani et al. at Google brought out the Transformer that replaced the recurrent neural networks that had dominated language AI until then. Dynamic focus on different parts of the input when processing each token was the key innovation that came in the form of the attention mechanism.

Attention mechanism. In processing each token, the model calculates "attention scores" for that token against every other token in the context. That tells the model how much each other token should affect the representation of the current token.

Long-range dependencies that recurrent networks found hard to capture get captured by the model because higher attention scores go to tokens that are semantically related or syntactically connected.

Multi-head attention: The Transformer uses multiple parallel attention computations (multiple "heads"), each learning to attend to different types of relationships - one head might learn syntactic dependencies, another semantic similarity, another coreference.

Scale: The key characteristic of current large language models is scale: they have hundreds of billions (GPT-4, Gemini Ultra, Claude) of parameters. This scale comes from stacking many Transformer layers and widening the attention and feed-forward components within each layer.

Empirically, performance on language tasks has been found to improve smoothly and predictably with scale in compute, data, and parameter count - the "scaling laws" documented by Kaplan et al. at OpenAI in 2020.

Pre-Training and Fine-Tuning

The dominant training paradigm for large language models has two stages:

Pre-training: The model is trained on a massive corpus of text using self-supervised learning (next-token prediction). This stage is computationally expensive (training frontier models requires thousands of specialized chips running for weeks or months) but produces a model with broad language capabilities and extensive world knowledge.

Fine-tuning: The pre-trained model is further trained on a smaller, more targeted dataset to adapt it for specific purposes. Instruction fine-tuning trains the model to follow natural language instructions.

RLHF fine-tunes the model to be helpful, harmless, and honest based on human preference ratings.[9] Domain fine-tuning adapts a general model for a specific domain like medicine or law.

Many apps can share the cost of pre-training through the two-stage method. The model gets customized for each app by much cheaper fine-tuning.


Training Challenges and Solutions

The Vanishing/Exploding Gradient Problem

Early deep neural networks suffered from gradients that either became vanishingly small (preventing effective learning in early layers) or explosively large (causing training instability) as they were backpropagated through many layers.

Modern solutions include:

  • Residual connections (skip connections that add the layer's input to its output), pioneered in ResNet, which allow gradients to bypass layers directly[8]
  • Layer normalization, which normalizes activations at each layer to prevent scale problems
  • Careful weight initialization schemes that ensure initial gradients are in a useful range
  • Gradient clipping, which caps gradient values at a maximum magnitude

Overfitting

A model that memorizes its training data rather than learning general patterns will perform well on training data but poorly on new data - a failure mode called overfitting.

Solutions:

  • Regularization techniques (dropout, weight decay) that penalize complexity and discourage memorization
  • Data augmentation that artificially increases the diversity of training examples
  • Early stopping that halts training when validation set performance stops improving
  • Increasing data size. Overfitting becomes less of a problem as the ratio of dataset size to model size grows.

Computational Cost

Major tech companies and well-funded research groups are the only ones that have the computing power to train today's large language models. Bringing that training power together in one place brings up big questions about who will make frontier AI models and how benefits and risks are split up.

Research directions that aim to improve compute efficiency include:

  • Mixture of Experts (MoE) architectures that activate only a fraction of model parameters for each input
  • Improved data curation that extracts more learning signal from less data
  • Distillation methods that train smaller models to replicate the behavior of larger ones
  • Quantization and pruning that reduce model size after training without proportional quality loss

Example: In 2023 Mistral AI was founded by former DeepMind and Meta researchers and the company put out the Mistral 7B model. Architectural innovations as well as careful data curation enabled it to beat Meta's much larger LLaMA 2 13B model on many benchmarks.[10]

Smaller models that get better training have shown they can compete against much larger models with standard training and this commercially important finding has changed how models are developed going forward.


After Training: Evaluation and Deployment

Evaluation

Model evaluation is a field in itself. Training a model well and evaluating it well are distinct challenges.

Benchmark evaluation. Academic standards like MMLU for multi-task knowledge, HumanEval for coding and BIG-Bench for diverse reasoning give standardized ways to compare across models. At the same time, benchmarks can be gamed by training or evaluating models on test data and they may not show what a model can do in the real world.

Human evaluation. Human evaluators grade model outputs on specific criteria or line them up against each other for qualitative work. Real-world quality gets captured better by human eval than by benchmarks yet the method is expensive and difficult to scale.

Red teaming. This is adversarial testing set up to find failure modes. Those are responses the model should not give and behaviors that break safety rules as well as capability limits in high-stakes fields.

Deployment metrics. In the end, the most meaningful test is how the model does in deployment by user engagement, task completion rates and outcome measures such as diagnostic accuracy or customer satisfaction in high-stakes applications.

Deployment Considerations

A trained model that performs well in evaluation may still fail in deployment if:

  • Distribution shift: The deployment distribution differs from the training and evaluation distribution
  • Adversarial users: Users actively try to elicit outputs that the model was not trained to produce
  • Integration failures: The model interacts with other systems in unexpected ways
  • Scale: Performance that is acceptable at low volume may degrade at scale due to tail failures that rare inputs expose

Monitoring, filtering and feedback systems that detect and respond to the problems are part of how modern AI gets deployed. Trained model weights mark the start of a deployed AI system. They do not mark the end.

Both more mechanical than most people think and more remarkable than most realize, training AI models is an optimization process that iterates over data to cut a loss function. It is also where simple objectives applied at scale give rise to sophisticated capabilities.

What makes AI development both exciting and in important ways unpredictable is the gap between these two descriptions. That is the gap between the mechanical process and what emerges from it.


What Research Shows About AI Training Methods and Scaling

Some of the most consequential results in modern AI research come from looking empirically at what happens when neural networks are trained at larger and larger scale. They give direct clues to why current large language models behave as they do.

Jared Kaplan, Sam McCandlish, and colleagues at OpenAI published "Scaling Laws for Neural Language Models" in January 2020, documenting that language model performance (measured as cross-entropy loss on test data) improves as a smooth power law with increases in model size, dataset size, and compute budget - across many orders of magnitude.[2]

Model size and training compute were found by the paper to matter more for language model performance than architectural details. The paper also set up quantitative formulas to predict how much performance gain a given rise in compute would bring.

Predictable scaling of performance with compute led to a quick shift in how researchers approach things. If performance scales predictably with compute, the way to get better is by scaling up. That is why GPT-2 (1.5 billion parameters in 2019) was followed so fast by GPT-3 (175 billion parameters in 2020) and then by an estimated 1+ trillion parameters for GPT-4 in 2023.

For a set compute budget, training a larger model on less data is more efficient than training a smaller model on more data and that is the finding later revised by Hoffmann et al. in DeepMind's 2022 "Chinchilla" paper. The paper showed that Kaplan's original models were undertrained relative to their size and that allocating the best amount of compute trains a model with about 20 tokens per parameter.

At OpenAI (now at the Alignment Research Center), Paul Christiano created Reinforcement Learning from Human Feedback (RLHF). This was done as a practical method to line up what a language model does with what humans prefer.

In "Learning to Summarize from Human Feedback" (Stiennon et al., NeurIPS 2020), a reward model was trained on human preferences between pairs of model outputs and that model was used to fine-tune GPT-3 for summarization.

In tasks where it is hard to specify quality algorithmically, human feedback works as a signal far more data-efficient than labeled examples. A model trained through RLHF was chosen by human evaluators 70 percent of the time over one that got only supervised training with 10 times as much data.

This result set up RLHF as the practical alignment method that was then used to train InstructGPT, ChatGPT and related conversational AI systems.

At OpenAI, Long Ouyang led the InstructGPT paper from 2022. It showed that human evaluators chose an 85 percent majority of the time a 1.3 billion parameter RLHF-trained model over a 175 billion parameter base GPT-3 model on instruction-following tasks. That is a strong showing that alignment training can get past a 100 times difference in model size.

Through systematic experiments, Jordan Hoffmann and colleagues at DeepMind showed in their 2022 paper "Training Compute-Optimal Large Language Models" (informally known as the Chinchilla paper) that the compute-optimal way to train a model calls for training it on many more tokens than had been assumed before.

For any given compute budget, the best ratio is about equal numbers of parameters and training tokens (about 20 tokens per parameter) and the paper trained 400 language models ranging from 70 million to 16 billion parameters on datasets that went from 5 billion to 400 billion tokens.

With the same compute budget that Gopher (280 billion parameters, 300 billion tokens) used, DeepMind trained Chinchilla (70 billion parameters, 1.4 trillion tokens) and despite having four times fewer parameters, Chinchilla substantially outperformed Gopher when this finding was applied.

Getting AI research away from just maximizing model size and toward raising data quality and training duration was the Chinchilla finding that influenced the design of Meta's LLaMA models, Google's Gemini and Anthropic's Claude series.

Geoffrey Hinton, Yann LeCun, and Yoshua Bengio (jointly awarded the 2018 Turing Award for their foundational contributions to deep learning) have each commented on the emergence of capabilities that appear during training as models scale past certain size thresholds.

Jason Wei formalized this observation in "Emergent Abilities of Large Language Models" (2022) at Google Brain. More than 100 capabilities appear in the document that seem to emerge discontinuously as models get larger. Multi-step arithmetic, analogical reasoning, chain-of-thought reasoning and certain language translation tasks are among them. They gave near-zero performance at small scales but gained big capability once the model passed a certain size threshold.

If the emergence finding holds at continued scales instead of being a measurement artifact, it has large implications for planning AI development. It points to future training runs giving capabilities that are qualitatively new and hard to predict ahead of time.


Real-World Case Studies in AI Training and Deployment

GPT-3 and the Economics of Large-Scale Pre-Training. OpenAI's GPT-3, trained in 2020, provided the first public demonstration that a single pre-trained model could perform competently on a wide variety of tasks through in-context learning, without any task-specific fine-tuning.[3]

About 3.14 million GPU hours ran the training on NVIDIA V100 GPUs and that took an estimated cloud compute cost of $4.6 million (based on 2020 spot prices).

Without the task-specific training that earlier AI systems needed, the model can do tasks including translation, code generation and arithmetic through prompting alone and that gave the foundation model approach its commercial value. Train once at large scale and put it to use many times.

The API that OpenAI next opened up to serve GPT-3 to developers brought in revenue that made continued development of the model possible.

Amortizing the cost across many downstream applications and users who each need only the cheaper inference cost instead of the full training cost showed in the GPT-3 case that large-scale pre-training has economic advantages when its cost gets spread that way.

DeepMind's AlphaFold 2, scientific training data and validated outcomes. The 2021 Nature paper by John Jumper and colleagues at DeepMind describes how AlphaFold 2 was trained on the Protein Data Bank (PDB). This is a curated dataset of about 170,000 protein structures determined experimentally and collected over 50 years of work in structural biology.

Multiple sequence alignments showing how related proteins vary across species were combined with self-supervised learning on structure prediction in the training method. Experimental structures along with high-confidence predicted structures from earlier model iterations were used to grow the training set.

On the CASP14 benchmark, AlphaFold 2 hit a median RMSD of 0.96 angstroms against experimental structures and did so within the margin of experimental error. That amounts to solving the problem of predicting protein structures.

As of 2022, DeepMind had put out a database of predicted structures for more than 200 million proteins that covered virtually every known protein.

Over 1 million research projects have made use of AlphaFold predictions since its release and drug discovery in malaria, antibiotic resistance and cancer research has sped up according to DeepMind's 2024 impact report.

Meta's LLaMA: Open Training and the Democratization of Foundation Models. Meta AI's LLaMA models (released in 2023 and 2024) were trained with a specific design philosophy: use more training tokens than the Chinchilla-optimal amount to produce smaller models that perform better at inference time, rather than larger models that perform better per training token but are more expensive to deploy.

LLaMA 1 came out in February 2023. It trained a 7 billion parameter model on 1 trillion tokens (about 10 times as many as Chinchilla says are needed for a model of that size) and got performance similar to GPT-3 (with 175 billion parameters) on many benchmarks.

In July 2023, LLaMA 2 extended the model to 70 billion parameters trained on 2 trillion tokens. The model also got RLHF alignment training with around 1 million human preference labels that Meta's own annotation program collected.

Over 30,000 derivative models were made within a year by following Hugging Face's tracking data. That is how LLaMA model weights being openly released for research and commercial use let more than 30,000 derivative models get made. It also lowered dramatically the barrier to putting capable language models into production and gave academic researchers who do not have big compute budgets the chance to study frontier-class models.

Google's BERT in Search: Training for Real-World Impact. Google's BERT (Bidirectional Encoder Representations from Transformers), described in a 2018 paper, was the first large-scale demonstration of the self-supervised pre-training paradigm for natural language understanding tasks.[4]

Google subsequently deployed BERT in Google Search in late 2019, describing it at the time as "the biggest leap forward in the past five years, and one of the biggest leaps forward in the history of Search."

In a Google Webmaster Conference presentation, Search Liaison Danny Sullivan described BERT as helping Google better understand the intent behind queries - particularly long, conversational queries and queries where prepositions (like "to" and "for") change meaning substantially.

Google estimated that BERT affected approximately 10 percent of all English-language searches at launch.

Validation at an unprecedented scale came through the production deployment. It showed that self-supervised language model pre-training picks up semantic understanding useful for real-world information retrieval. That was the first time a large pre-trained transformer appeared in a system dealing with billions of daily queries.


Sources & Further Reading

  1. Vaswani, Ashish et al. "Attention Is All You Need." NeurIPS, 2017. View source
  2. Kaplan, Jared et al. "Scaling Laws for Neural Language Models." OpenAI, 2020. View source
  3. Brown, Tom et al. "Language Models are Few-Shot Learners (GPT-3)." NeurIPS, 2020. View source
  4. Devlin, Jacob et al. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." NAACL, 2019. View source
  5. Silver, David et al. "Mastering the game of Go without human knowledge." Nature, 2017. View source
  6. Goodfellow, Ian, Bengio, Yoshua, and Courville, Aaron. Deep Learning. MIT Press, 2016.
  7. Rumelhart, David, Hinton, Geoffrey, and Williams, Ronald. "Learning representations by back-propagating errors." Nature, 1986. View source
  8. He, Kaiming et al. "Deep Residual Learning for Image Recognition." CVPR, 2016. View source
  9. Anthropic. "Claude's Constitution." Anthropic.
  10. Jiang, Albert et al. "Mistral 7B." arXiv, 2023. View source