A large language model (LLM) is usually developed through multiple stages rather than trained once for every future task. Pretraining establishes broad language-modeling capabilities using large datasets. Fine-tuning adapts the pretrained model to particular tasks or response behaviors. Alignment refers to methods for making model behavior better match intended instructions, preferences, safety requirements, and other objectives.
These stages are related but not interchangeable. A model can learn to predict text well without reliably following instructions; it can follow instructions without always giving correct answers; and it can perform well on a benchmark while failing in a new setting. Understanding the training lifecycle helps explain both the strengths and limits of modern AI assistants.
Start with a simple example
Imagine starting with a model trained to predict the next word-like token in large collections of text. It may be good at continuing passages but poor at responding directly to instructions like “Explain recursion to a beginner in five sentences.” Instruction-focused training can teach it to follow that request more reliably.
This motivates three different stages:
- Pretraining develops broad statistical representations and capabilities, often by predicting text or other training targets at scale.
- Fine-tuning continues training an existing model using more targeted examples or objectives, such as question–answer pairs.
- Alignment methods seek to better match behavior to intended preferences, policies, and constraints; they can include supervised examples and preference-based optimization.
For a small illustrative dataset, a fine-tuning record might pair an instruction “Define a vector” with a desired explanation. Repeating this across many examples can change the model’s weights toward the demonstrated behavior. Merely including the same instruction in a prompt does not change those weights.
Better instruction following does not imply perfect truthfulness, fairness, or safety. The training data, objectives, evaluation procedures, and deployment controls all affect actual behavior.
1. The LLM development lifecycle
A simplified development workflow has several connected stages:
| Stage | Main question | Typical output |
|---|---|---|
| Data preparation | What data is appropriate and legally permissible to use? | Curated training corpora |
| Pretraining | What statistical patterns can the model learn from data? | Base model |
| Supervised fine-tuning (SFT) | How should the model respond to examples of tasks and instructions? | Instruction- or task-adapted model |
| Preference optimization | Which of several plausible responses better meets intended criteria? | Model optimized for a defined preference signal |
| Evaluation | Does the model work reliably on representative and difficult cases? | Test results, identified limitations, and release decisions |
| Deployment and monitoring | Does the system behave acceptably under actual use? | Served model and operational feedback |
Evaluation is not a final step alone. Data checks, training diagnostics, safety testing, and performance measurement should occur throughout development.
2. Pretraining: learning from large datasets
Pretraining is an initial learning stage in which a model adjusts its parameters using a broad training dataset and a general objective, often without human-authored labels for each individual example.
For a common autoregressive language model, training examples consist of token sequences. The model repeatedly predicts the next token from preceding tokens. This is a form of self-supervised learning because the target token is obtained from the sequence itself.
Given tokens and model parameters , the next-token objective is commonly written as:
The model assigns probability to the correct token at each position, and optimization aims to reduce the negative log-likelihood. In practice, training averages or sums this objective across many sequences and batches.
What happens during pretraining?
- Collect and curate data. Text is sourced, filtered, deduplicated, and checked for quality, privacy, and permitted use.
- Train or select a tokenizer. Text is converted into token identifiers according to a vocabulary.
- Construct sequences and batches. Tokens are arranged into manageable training examples; padding and attention masks may be required.
- Run the forward pass. The model produces probability distributions over possible tokens.
- Calculate loss. Predicted probabilities are compared with target tokens.
- Compute gradients and update parameters. Backpropagation and an optimizer change the weights.
- Validate and checkpoint. Held-out evaluation and stored checkpoints help monitor learning and recover training progress.
A model does not acquire a verified database of facts during this process. It learns parameter values that support predictions across many contexts. Its learned information may be incomplete, outdated, biased, or incorrectly recalled.
Pretraining versus training from scratch
Training from scratch initializes a new model and develops its parameters through an initial training run. Continued pretraining starts from an existing pretrained model and further trains it on additional data using a language-modeling objective. Continued pretraining may emphasize a domain, language, or distribution, but it can also change earlier capabilities and introduce forgetting.
Pretraining usually requires considerable data, computation, engineering, and evaluation. Most application developers instead begin with an existing model and adapt or integrate it.
3. Fine-tuning: adapting a pretrained model
Fine-tuning updates some or all of a pretrained model’s parameters using data selected for a new task, domain, or behavior. It starts from previously learned weights instead of beginning with random weights.
Examples include adapting a language model to:
- Follow instructions in a consistent format.
- Classify support requests into defined categories.
- Produce structured outputs under an expected schema.
- Handle terminology common in a specialized domain.
- Respond in a particular supported language or style.
Fine-tuning is not automatically the best tool for adding frequently changing facts. When the primary requirement is access to current or private documents, retrieval-augmented generation may be more appropriate. Fine-tuning and retrieval can also be combined.
Supervised fine-tuning (SFT)
In supervised fine-tuning, a dataset provides inputs paired with desired outputs. For instruction tuning, an example might contain a user instruction and an appropriate assistant response.
| Instruction | Desired response |
|---|---|
| “Classify: ‘Please reset my password.’” | account-access |
| “Convert 3 hours to minutes.” | 180 minutes |
| “Explain a vector in one sentence.” | A vector is an ordered collection of values. |
The model is trained to increase the likelihood of the desired response tokens given the instruction and available context. An autoregressive SFT objective often has the form:
where is the input instruction and is a token in its target response. Implementations often mask prompt tokens so that the loss is applied to answer tokens only.
SFT teaches patterns from demonstrations. If demonstrations are wrong, narrow, contradictory, or unrepresentative, the model may learn those defects. It does not prove that every future response will follow the examples correctly.
Full fine-tuning and parameter-efficient fine-tuning
| Method | What changes | Practical trade-off |
|---|---|---|
| Full fine-tuning | Many or all original model weights | Flexible but memory- and compute-intensive |
| Parameter-efficient fine-tuning (PEFT) | A relatively small set of added or selected trainable parameters | Often cheaper to train and store, with some adaptation constraints |
| LoRA (Low-Rank Adaptation) | Learned low-rank updates to selected weight matrices | Common PEFT method for adapting large models |
In LoRA, a weight update can be represented approximately as a product of two smaller matrices:
where is an existing weight matrix and and are lower-rank trainable matrices of compatible shapes. The original weights can remain frozen while the added matrices are learned. Actual LoRA implementations may include a scaling factor.
Fine-tuning is not the same as prompting. Prompting changes the information supplied to the model at inference time; fine-tuning changes learned parameters during training.
4. Alignment: optimizing for intended behavior
In LLM development, alignment describes efforts to make model behavior more consistent with specified human intentions, instructions, policies, and quality criteria. It is an engineering goal rather than a single algorithm or a guarantee of safety.
An aligned assistant may be trained to respond helpfully, acknowledge uncertainty, avoid unsupported claims, respect limits, and handle harmful requests appropriately. These requirements can sometimes conflict, so their operational definitions and evaluation criteria matter.
Preference data
Instead of providing one correct output, a preference dataset may compare two candidates for the same prompt:
- Prompt: “Explain overfitting to a beginner.”
- Response A: A clear explanation with an accurate example.
- Response B: A confident but incorrect explanation.
- Preference: A is preferred to B for the specified quality criteria.
Such comparisons are informative, but preferences can reflect annotator disagreement, unclear instructions, bias, or incomplete criteria. A preferred response is not necessarily factually correct.
Reinforcement learning from human feedback (RLHF)
A common historical RLHF workflow uses three broad steps:
- Fine-tune a model on examples of desired responses.
- Collect preference comparisons and train a reward model to approximate those preferences.
- Optimize the language model against the learned reward signal, commonly with reinforcement-learning algorithms and constraints that discourage excessive divergence from a reference model.
For example, PPO (Proximal Policy Optimization) has been used for this type of post-training. Not every approach described as RLHF uses the same optimizer or pipeline.
A central risk is reward hacking: a model can learn outputs that score well under an imperfect reward model without satisfying the underlying human objective.
Direct Preference Optimization (DPO)
DPO is an alternative preference-learning method that directly trains a policy using preference pairs and a reference policy, without requiring a separately trained reward model in its standard formulation.
Its common objective is:
where is the preferred response, the less-preferred response, the model being optimized, a reference model, and a parameter controlling the preference objective. This equation is included for recognition; understanding the inputs and purpose matters more initially than deriving it.
| Approach | Training signal | Distinguishing feature |
|---|---|---|
| SFT | Demonstrations of desired outputs | Imitates examples |
| RLHF with a reward model | Preference comparisons, then estimated rewards | Optimizes a learned reward signal |
| DPO | Pairs of preferred and rejected outputs | Uses a direct preference-learning objective |
The techniques can be used in combination, and their effectiveness depends heavily on data quality and evaluation.
5. A small example: preparing supervised instruction data
The following Python code illustrates dataset construction, not the actual fine-tuning of a large model. It creates instruction-response examples, serializes them, and verifies that each record has the expected structure.
import json
from pathlib import Path
examples = [
{
"instruction": "Define supervised learning in one sentence.",
"response": "Supervised learning trains a model using labeled examples.",
},
{
"instruction": "What is the purpose of a validation dataset?",
"response": "It helps select models and tune settings during development.",
},
{
"instruction": "State one risk of evaluating on training data.",
"response": "The result can overestimate performance on unseen examples.",
},
]
path = Path("instruction_examples.jsonl")
with path.open("w", encoding="utf-8") as file:
for item in examples:
assert set(item) == {"instruction", "response"}
assert all(isinstance(value, str) and value.strip()
for value in item.values())
file.write(json.dumps(item, ensure_ascii=False) + "\n")
with path.open(encoding="utf-8") as file:
loaded = [json.loads(line) for line in file]
print(f"Validated {len(loaded)} examples")
Expected output:
Validated 3 examples
A production SFT workflow would additionally require model-specific chat formatting, tokenization, target masking, data splits, optimizer settings, compute resources, checkpointing, and evaluation. It would also require substantially larger, more representative, and quality-controlled datasets. Never put secrets, private records, or copyrighted material into training data without appropriate permission and safeguards.
6. Data quality, contamination, and safety
Training results depend on what is in the data and how it was obtained.
Data quality considerations
- Source provenance: Know where examples came from and what permissions govern their use.
- Deduplication: Limit repeated or near-duplicate records that distort the training distribution.
- Representation: Examine underrepresented languages, domains, and user groups.
- Instruction consistency: Check whether examples teach contradictory or incorrect responses.
- Privacy: Minimize personal data and prevent exposure of confidential information.
- Contamination: Keep evaluation questions and answers out of training data where possible.
- Annotation quality: Audit disagreements and ambiguous preference criteria.
Training on a benchmark’s answers can make a model appear more capable than it is on genuinely new questions. Even when datasets are separated by file, duplicates and paraphrases can leak between splits.
7. Evaluating a trained or aligned LLM
Model development should assess both capability and behavior. No single benchmark is sufficient.
| Evaluation area | Questions to ask |
|---|---|
| Language modeling | How well does the model predict held-out tokens? |
| Task performance | Does it correctly solve the tasks that matter? |
| Instruction following | Does it respect content, format, and other constraints? |
| Factual reliability | Are important claims correct and appropriately supported? |
| Robustness | Does performance persist across paraphrases and unfamiliar cases? |
| Safety and privacy | Does it resist harmful requests and avoid disclosing sensitive information? |
| Fairness | Are error rates and outcomes acceptable across relevant groups? |
| Efficiency | What are the memory, latency, throughput, and financial costs? |
Some tests use exact-match or task-specific scoring; others need human review. For open-ended responses, automatic model-based graders can be useful but may also introduce bias and error. The final evaluation should include representative real-world workflows, adversarial cases, and monitoring after deployment.
Common failure modes
Catastrophic forgetting: Fine-tuning on narrow data can degrade capabilities learned earlier.
Overfitting: A model can memorize training examples or preferred response patterns without generalizing.
Hallucinations: A model can generate plausible statements that are false. Preference optimization does not eliminate this.
Distribution shift: Real users may provide inputs unlike those seen during training and evaluation.
Misalignment of metrics: High preference scores can coexist with factual mistakes, long-winded responses, or unsafe behavior.
8. Choosing between pretraining, fine-tuning, and other methods
| Your requirement | Start by considering | Reason |
|---|---|---|
| Develop a new base model with substantial resources | Pretraining | Learns broad parameters from an initial objective |
| Adapt a model to a fixed output format or task | Prompting, then SFT if necessary | Often begins with cheaper instruction control |
| Incorporate frequently changing private documents | RAG | Retrieves relevant information at request time |
| Improve responses based on comparative quality judgments | Preference optimization | Uses explicit preferences about outputs |
| Improve task success in an existing application | Evaluation and system design first | The problem may be retrieval, prompts, tools, or data rather than weights |
Before beginning an expensive training run, measure an existing baseline, identify concrete failure cases, and decide how improvement will be tested. Model training is a means to solve a problem, not a requirement for every AI product.
9. Relationship to inference and deployment
Training changes model parameters. Inference uses learned parameters to generate predictions from new inputs. During inference, decoding strategies such as greedy selection, temperature sampling, top-k sampling, and top-p sampling influence the generated sequence but ordinarily do not update the model weights.
This distinction is explored in LLM Inference, Decoding, and Sampling. Once a model is deployed, application-level components, retrieval, tool access, monitoring, and safeguards continue to influence the behavior of the full AI system.
10. Related concepts
- Large Language Models: Foundations and Capabilities provides the foundations for understanding what training changes.
- The Transformer Architecture explains a common model architecture used in LLMs.
- Attention, Self-Attention, and Multi-Head Attention explains a central Transformer computation.
- Model Training, Overfitting, and Generalization covers general machine-learning training problems.
- Training Neural Networks introduces loss, optimizers, and regularization.
- Prompting vs. RAG vs. Fine-Tuning compares different ways to adapt an AI application.
- Evaluating Machine Learning Models introduces validation principles that remain useful in LLM development.
11. Further reading
- Hugging Face LLM Course — tokenization, Transformers, and model adaptation.
- Hugging Face PEFT documentation — parameter-efficient fine-tuning methods.
- LoRA: Low-Rank Adaptation of Large Language Models — original LoRA method.
- Training Language Models to Follow Instructions with Human Feedback — instruction tuning and RLHF.
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model — DPO method and motivation.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.