Artificial Intelligence • Generative AI and Language Models • 14 min read

LLM Pretraining, Fine-Tuning, and Alignment

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:

  1. Pretraining develops broad statistical representations and capabilities, often by predicting text or other training targets at scale.
  2. Fine-tuning continues training an existing model using more targeted examples or objectives, such as question–answer pairs.
  3. 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:

A language-model development pipeline from raw data through pretraining, supervised fine-tuning, preference alignment, evaluation, and deployment.
Typical development stages. The order and methods vary between projects; some models omit or combine stages.
StageMain questionTypical output
Data preparationWhat data is appropriate and legally permissible to use?Curated training corpora
PretrainingWhat 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 optimizationWhich of several plausible responses better meets intended criteria?Model optimized for a defined preference signal
EvaluationDoes the model work reliably on representative and difficult cases?Test results, identified limitations, and release decisions
Deployment and monitoringDoes 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 x1,x2,…,xTx_1, x_2, \ldots, x_T and model parameters θ\theta, the next-token objective is commonly written as:

Lpretrain(θ)=−∑t=1Tlog⁡Pθ(xt∣x1,…,xt−1).\mathcal{L}_{\mathrm{pretrain}}(\theta) = -\sum_{t=1}^{T}\log P_{\theta}(x_t\mid x_1,\ldots,x_{t-1}).

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?

  1. Collect and curate data. Text is sourced, filtered, deduplicated, and checked for quality, privacy, and permitted use.
  2. Train or select a tokenizer. Text is converted into token identifiers according to a vocabulary.
  3. Construct sequences and batches. Tokens are arranged into manageable training examples; padding and attention masks may be required.
  4. Run the forward pass. The model produces probability distributions over possible tokens.
  5. Calculate loss. Predicted probabilities are compared with target tokens.
  6. Compute gradients and update parameters. Backpropagation and an optimizer change the weights.
  7. 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.

InstructionDesired 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:

LSFT(θ)=−∑i=1N∑t=1Tilog⁡Pθ(yi,t∣xi,yi,<t),\mathcal{L}_{\mathrm{SFT}}(\theta) = -\sum_{i=1}^{N}\sum_{t=1}^{T_i} \log P_{\theta}(y_{i,t}\mid x_i,y_{i,<t}),

where xix_i is the input instruction and yi,ty_{i,t} 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

MethodWhat changesPractical trade-off
Full fine-tuningMany or all original model weightsFlexible but memory- and compute-intensive
Parameter-efficient fine-tuning (PEFT)A relatively small set of added or selected trainable parametersOften cheaper to train and store, with some adaptation constraints
LoRA (Low-Rank Adaptation)Learned low-rank updates to selected weight matricesCommon PEFT method for adapting large models

In LoRA, a weight update can be represented approximately as a product of two smaller matrices:

W′=W+ΔW,ΔW=BA,W' = W + \Delta W, \qquad \Delta W = BA,

where WW is an existing weight matrix and AA and BB 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:

  1. Fine-tune a model on examples of desired responses.
  2. Collect preference comparisons and train a reward model to approximate those preferences.
  3. 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:

LDPO=−E(x,yw,yl)[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))],\mathcal{L}_{\mathrm{DPO}} = -\mathbb{E}_{(x,y_w,y_l)}\left[ \log\sigma\left( \beta\log\frac{\pi_{\theta}(y_w\mid x)}{\pi_{\mathrm{ref}}(y_w\mid x)} -\beta\log\frac{\pi_{\theta}(y_l\mid x)}{\pi_{\mathrm{ref}}(y_l\mid x)} \right)\right],

where ywy_w is the preferred response, yly_l the less-preferred response, πθ\pi_{\theta} the model being optimized, πref\pi_{\mathrm{ref}} a reference model, and β\beta a parameter controlling the preference objective. This equation is included for recognition; understanding the inputs and purpose matters more initially than deriving it.

ApproachTraining signalDistinguishing feature
SFTDemonstrations of desired outputsImitates examples
RLHF with a reward modelPreference comparisons, then estimated rewardsOptimizes a learned reward signal
DPOPairs of preferred and rejected outputsUses 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 areaQuestions to ask
Language modelingHow well does the model predict held-out tokens?
Task performanceDoes it correctly solve the tasks that matter?
Instruction followingDoes it respect content, format, and other constraints?
Factual reliabilityAre important claims correct and appropriately supported?
RobustnessDoes performance persist across paraphrases and unfamiliar cases?
Safety and privacyDoes it resist harmful requests and avoid disclosing sensitive information?
FairnessAre error rates and outcomes acceptable across relevant groups?
EfficiencyWhat 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 requirementStart by consideringReason
Develop a new base model with substantial resourcesPretrainingLearns broad parameters from an initial objective
Adapt a model to a fixed output format or taskPrompting, then SFT if necessaryOften begins with cheaper instruction control
Incorporate frequently changing private documentsRAGRetrieves relevant information at request time
Improve responses based on comparative quality judgmentsPreference optimizationUses explicit preferences about outputs
Improve task success in an existing applicationEvaluation and system design firstThe 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.

11. Further reading

Related articles in

Image preview

Fit