LLM Training Pipeline: Pretraining, Fine-Tuning & RLHF

Training a modern Large Language Model (LLM) is not a single training run. A model trained only to predict the next token from large amounts of raw text may produce fluent language, but it does not automatically know how to follow instructions, answer questions helpfully, maintain a conversational format, or respect safety requirements.

Transforming raw neural network weights into a useful AI assistant requires multiple stages of training, data preparation, evaluation, and alignment.

A widely used conceptual framework consists of three major stages:

  1. Pretraining: Acquiring language patterns, general knowledge, and foundational capabilities.
  2. Supervised Fine-Tuning (SFT): Learning to follow instructions and generate desired responses.
  3. Preference Alignment (RLHF, DPO, and related methods): Improving responses according to human or other preference signals.

These stages build on one another, but real-world training pipelines can contain additional steps, repeated training cycles, and specialized optimization techniques.

       Large-Scale Text and Code Data
                    |
                    v
          1. PRETRAINING
          Next-Token Prediction
                    |
                    v
                BASE MODEL
                    |
                    |
          Curated Instruction Data
                    |
                    v
       2. SUPERVISED FINE-TUNING
                  (SFT)
                    |
                    v
              INSTRUCT MODEL
                    |
                    |
         Human Preference Comparisons
                    |
                    v
       3. PREFERENCE ALIGNMENT
          RLHF / PPO / DPO
                    |
                    v
            ALIGNED ASSISTANT
                    |
                    v
       Evaluation, Safety & Deployment

In this guide, we will explore how each stage works, the mathematics behind the training objectives, practical Python examples, the differences between RLHF and DPO, and how the complete pipeline fits together.


1. Understanding the LLM Training Pipeline

Before exploring individual stages, it is important to understand what an LLM actually learns.

A language model is a neural network trained to estimate probability distributions over possible tokens.

Given a sequence of tokens:

\[ x_1,x_2,\ldots,x_t \]

the model predicts a probability distribution for the next token:

\[ P(x_{t+1}\mid x_1,x_2,\ldots,x_t) \]

For example, consider:

Input:

Machine learning is a branch of

The model might assign probabilities such as:

Candidate next tokenIllustrative probability
artificial0.65
computer0.15
mathematics0.10
science0.07
other tokens0.03

The model samples or selects a token based on its decoding strategy, appends it to the context, and predicts the next token again.

This repeated process is called autoregressive generation.

A model's training pipeline determines more than its ability to predict plausible text. It also influences its ability to interpret prompts, produce structured answers, and respond according to desired behavior.

The three stages at a glance

StageMain objectiveTraining dataResult
PretrainingLearn general language patterns and representationsLarge-scale text, code, and other dataBase model
SFTLearn to follow instructionsCurated prompt-response examplesInstruction-tuned model
Preference alignmentPrefer desirable responsesHuman or AI preference comparisonsPreference-aligned model

2. Stage 1: Pretraining — Building Foundational Knowledge

Pretraining is the initial large-scale training process in which a language model learns statistical patterns, linguistic structures, and useful representations from a massive dataset.

For a decoder-only autoregressive LLM, the common objective is next-token prediction.

The model receives a sequence of tokens and learns to predict each next token using the preceding context.

2.1 How next-token prediction works

Consider the sentence:

Artificial intelligence is changing the world.

After tokenization, it might become a sequence resembling:

[Artificial, intelligence, is, changing, the, world, .]

The model learns multiple prediction tasks:

ContextTarget token
Artificialintelligence
Artificial intelligenceis
Artificial intelligence ischanging
Artificial intelligence is changingthe
Artificial intelligence is changing theworld
Artificial intelligence is changing the world.

The actual training process generally handles many token positions together rather than performing six independent training runs.

2.2 The mathematical objective

For a token sequence:

\[ x_1,x_2,\ldots,x_T \]

the autoregressive model factorizes the sequence probability as:

\[ P(x_1,\ldots,x_T) = \prod_{t=1}^{T} P(x_t\mid x_1,\ldots,x_{t-1}) \]

The training objective is to maximize the likelihood of the observed training sequences.

Equivalently, the model minimizes negative log-likelihood, commonly implemented as cross-entropy loss:

\[ \mathcal{L}_{\text{pretrain}} = -\sum_{t=1}^{T} \log P_\theta(x_t\mid x_{<t}) \]

Where:

  • \(T\) = number of prediction positions.
  • \(x_t\) = target token.
  • \(x_{<t}\) = all preceding tokens.
  • \(P_\theta\) = probability predicted by the model's parameters.
  • \(\theta\) = trainable model parameters.

The model updates its weights through backpropagation and an optimization algorithm such as AdamW.

2.3 What does a model learn during pretraining?

Pretraining exposes the model to patterns from which it can learn:

  • Grammar and sentence structure.
  • Vocabulary and language relationships.
  • Common facts and associations.
  • Reasoning patterns represented in training data.
  • Programming syntax and code structures.
  • Writing styles and document formats.
  • Contextual relationships between words and concepts.

However, pretraining does not guarantee that every learned fact is correct, current, or consistently accessible.

The model learns statistical representations from its training data rather than building a perfectly verified database of facts.

2.4 Pretraining data

Training datasets can contain:

Data sourceExamples
Web textArticles, documentation, educational websites
BooksPublicly available or appropriately licensed books
CodeProgramming repositories and technical documentation
ResearchScientific papers and technical publications
ConversationAppropriately sourced dialogue datasets
Multilingual dataText in different languages
Structured dataTables and other serialized information

Real training pipelines must consider licensing, privacy, data quality, duplication, harmful content, and representation across different languages and domains.

2.5 Data preprocessing and tokenization

Raw text cannot simply be passed directly into a neural network. It must be converted into numerical token IDs.

A common process is:

Raw Text
   |
   v
Data Collection
   |
   v
Filtering and Cleaning
   |
   v
Deduplication
   |
   v
Tokenization
   |
   v
Token IDs
   |
   v
Training Sequences

Tokenization converts text into smaller units called tokens.

For example:

Input: "Machine learning is powerful."

Possible tokens:
["Machine", " learning", " is", " powerful", "."]

The exact tokens depend on the tokenizer.

Popular tokenization approaches include:

  • Byte Pair Encoding (BPE)
  • WordPiece
  • Unigram Language Model
  • Byte-level tokenization

A tokenizer maps tokens to integer IDs:

text = "Machine learning is powerful."

tokens = tokenizer.tokenize(text)
token_ids = tokenizer.encode(text)

print("Tokens:", tokens)
print("Token IDs:", token_ids)

The model processes token IDs through its embedding and Transformer layers.

2.6 Pretraining infrastructure

Training a modern LLM can require large-scale distributed computing.

Important components include:

  • GPUs or other accelerators.
  • Distributed training frameworks.
  • High-bandwidth communication between devices.
  • Efficient attention implementations.
  • Data loading and preprocessing pipelines.
  • Checkpoint storage.
  • Learning-rate scheduling.
  • Training and validation monitoring.

Common technologies include:

TechnologyPurpose
PyTorchDeep learning framework
Hugging Face TransformersModel architectures and training utilities
DeepSpeedDistributed and memory-efficient training
FSDPDistributed parameter sharding
Megatron-LMLarge-scale Transformer training
FlashAttentionEfficient attention computation
Weights & BiasesExperiment tracking
TensorBoardTraining visualization

2.7 What is a base model?

After pretraining, the resulting model is commonly called a base model.

A base model can:

  • Complete text.
  • Generate code.
  • Answer some questions.
  • Continue conversations represented in its training data.
  • Produce fluent and contextually relevant language.

However, it has not necessarily been trained to behave like a conversational assistant.

For example:

Prompt:

Explain machine learning in simple words.

A base model might continue the text in several possible ways:

Explain machine learning in simple words.
It is a field of computer science...

Or it might produce an article continuation, a different question, or another plausible text completion.

The model is primarily optimized to predict text, not to satisfy an explicit instruction-following objective.

Stage 1 output: Base LLM


3. Stage 2: Supervised Fine-Tuning (SFT) — Teaching the Model to Follow Instructions

Pretraining teaches a model to recognize and generate language patterns. However, a useful assistant must also learn how to respond to instructions.

This is where Supervised Fine-Tuning (SFT) comes into the pipeline.

SFT trains a pretrained model using curated examples of prompts and desirable responses.

Instead of simply learning from arbitrary text continuation, the model learns from demonstrations of the behavior expected from an assistant.

3.1 What does SFT mean?

Supervised Fine-Tuning is a process in which a pretrained model is further trained on labeled examples.

Each training example typically contains:

  • An instruction or user message.
  • Optional conversational context.
  • A target assistant response.

For example:

User instructionDesired assistant response
What is Python?Python is a high-level programming language.
Explain AI in simple words.Artificial intelligence enables computers to perform tasks that normally require human intelligence.
Write a Python function to add two numbers.def add(a, b): return a + b
Summarize this paragraph.A concise summary of the supplied paragraph.

The model learns to produce the target response when it receives the corresponding prompt.

3.2 SFT training architecture

       Pretrained Base Model
                 |
                 v
       Curated Instruction Dataset
                 |
                 v
         Prompt + Target Response
                 |
                 v
          Tokenization and Masking
                 |
                 v
          Supervised Fine-Tuning
                 |
                 v
         Instruction-Tuned Model

3.3 SFT mathematical objective

Let:

  • \(x\) = input prompt.
  • \(y=(y_1,y_2,\ldots,y_T)\) = target response.
  • \(\theta\) = model parameters.

The SFT objective is to maximize the probability of the desired response given the prompt:

\[ \mathcal{L}_{\text{SFT}} = -\sum_{t=1}^{T} \log P_\theta(y_t\mid x,y_{<t}) \]

In simple terms, the model learns to generate the expected answer token by token.

In many implementations, the loss is calculated primarily over assistant response tokens. Prompt tokens are provided as context but are masked from the supervised response loss.

This distinction is important in conversational fine-tuning.

3.4 Example: Pretraining vs. SFT

Consider this prompt:

User: What is machine learning?

A base model might continue with a broad text completion.

An instruction-tuned model is trained to produce a direct response:

Assistant: Machine learning is a branch of artificial
intelligence that enables computers to learn patterns
from data and make predictions or decisions without
being explicitly programmed for every task.

The important change is not that the model suddenly acquires all its knowledge during SFT. It learns to use its pretrained capabilities in a more instruction-oriented way.

3.5 Types of SFT datasets

SFT datasets can contain different kinds of examples.

1. Question-answering data

Question: What is supervised learning?

Answer: Supervised learning trains a model using
labeled examples.

2. Instruction-following data

Instruction: Write a Python program to reverse a string.

Response:
text = "hello"
print(text[::-1])

3. Multi-turn conversation data

User: What is Python?

Assistant: Python is a programming language.

User: Where is it used?

Assistant: Python is used in web development,
automation, data science, machine learning, and AI.

4. Reasoning and task-specific examples

Examples may teach structured problem-solving, code generation, mathematical explanations, or domain-specific workflows.

The quality and diversity of these examples strongly influence the model's behavior.

3.6 Practical SFT example using Hugging Face

The following example illustrates how to fine-tune a small pretrained causal language model using instruction-response data.

It is a simplified demonstration, not a recipe for training a production-scale LLM.

from datasets import Dataset
from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    Trainer,
    TrainingArguments,
    DataCollatorForLanguageModeling
)

model_name = "distilgpt2"

tokenizer = AutoTokenizer.from_pretrained(model_name)

if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(model_name)

# Small demonstration dataset
data = {
    "text": [
        "User: What is Python?\nAssistant: Python is a high-level programming language.",
        "User: What is AI?\nAssistant: AI enables machines to perform tasks that normally require human intelligence.",
        "User: What is ML?\nAssistant: Machine learning allows computers to learn patterns from data."
    ]
}

dataset = Dataset.from_dict(data)

def tokenize_function(examples):
    return tokenizer(
        examples["text"],
        truncation=True,
        max_length=128
    )

tokenized_dataset = dataset.map(
    tokenize_function,
    batched=True
)

training_args = TrainingArguments(
    output_dir="./sft_model",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    learning_rate=5e-5,
    logging_steps=1,
    save_strategy="epoch",
    report_to="none"
)

data_collator = DataCollatorForLanguageModeling(
    tokenizer=tokenizer,
    mlm=False
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    data_collator=data_collator
)

trainer.train()

Important implementation note: This is full-sequence causal language-model training on prompt-response strings. It does not implement a production chat template or mask the user prompt from the loss. A production SFT pipeline should use the model's correct chat format and response-only loss masking where appropriate.

3.7 Parameter-Efficient Fine-Tuning (PEFT)

Full fine-tuning updates a large number of model parameters.

For large models, this can require substantial GPU memory and compute.

Parameter-Efficient Fine-Tuning (PEFT) reduces the number of trainable parameters.

Popular methods include:

  • LoRA (Low-Rank Adaptation)
  • QLoRA (Quantized Low-Rank Adaptation)
  • Adapter layers
  • Prefix tuning
  • Prompt tuning

LoRA explained

LoRA keeps the original model weights mostly frozen and learns small low-rank update matrices.

Instead of directly updating a large weight matrix \(W\), LoRA represents its update as:

\[ W'=W+\Delta W \]

\[ \Delta W=BA \]

Where:

  • \(W\) = original pretrained weight matrix.
  • \(A\) and \(B\) = trainable low-rank matrices.
  • \(r\) = selected low rank.

For a scaling factor \(\alpha\), a common implementation uses:

\[ W'=W+\frac{\alpha}{r}BA \]

This can significantly reduce the number of trainable parameters.

LoRA implementation using PEFT

from peft import LoraConfig, get_peft_model, TaskType

lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=8,
    lora_alpha=16,
    lora_dropout=0.1,
    target_modules=["c_attn"]
)

model = get_peft_model(model, lora_config)

model.print_trainable_parameters()

The target module names depend on the model architecture. For example, attention projection names differ across GPT, Llama, and other model families.

QLoRA combines quantized base-model weights with trainable LoRA adapters, making fine-tuning more accessible on limited hardware.

Stage 2 output: Instruction-tuned model


4. Stage 3: Preference Alignment — Teaching the Model Which Responses Are Better

After SFT, the model can follow instructions and produce structured responses.

However, multiple responses may be valid for the same prompt, and not all are equally useful.

Consider:

Prompt:

Explain artificial intelligence to a beginner.

Response A:

AI is the simulation of human intelligence by machines.

Response B:

Artificial intelligence, or AI, is technology that helps
computers perform tasks such as understanding language,
recognizing images, and making predictions. For example,
a voice assistant uses AI to understand spoken questions.

Both responses may be technically reasonable, but Response B may be more helpful for a beginner because it includes explanations and an example.

Preference alignment aims to make the model more likely to produce responses that humans or other evaluators prefer.

Two widely discussed approaches are:

  1. Reinforcement Learning from Human Feedback (RLHF).
  2. Direct Preference Optimization (DPO).

They are related approaches, but they are not identical and are not necessarily used one after the other.


5. RLHF: Reinforcement Learning from Human Feedback

RLHF is a family of methods that uses human preference feedback to improve model behavior.

A common RLHF pipeline has three major components:

  1. Collect human preference comparisons.
  2. Train a reward model.
  3. Optimize the language model using reinforcement learning.

5.1 Step 1: Collect human preference data

The current model generates multiple responses to the same prompt.

Human annotators compare those responses and identify which one they prefer according to defined criteria.

For example:

Prompt:

How can I protect my online accounts?

Response A:

Use the same password everywhere so you can remember it.

Response B:

Use unique passwords, enable multi-factor authentication,
and avoid clicking suspicious links.

A human evaluator would generally prefer Response B.

A preference dataset can be represented as:

\[ (x,y_w,y_l) \]

Where:

  • \(x\) = prompt.
  • \(y_w\) = preferred or winning response.
  • \(y_l\) = less-preferred response.

This is called a preference pair.

5.2 Step 2: Train a reward model

The reward model learns to assign higher scores to responses that humans prefer.

For a prompt \(x\) and response \(y\), the reward model produces:

\[ r_\phi(x,y) \]

Where \(\phi\) represents the reward model's trainable parameters.

A commonly used pairwise preference objective is:

\[ \mathcal{L}_{RM} = -\log \sigma \left( r_\phi(x,y_w)-r_\phi(x,y_l) \right) \]

Where:

  • \(y_w\) = preferred response.
  • \(y_l\) = less-preferred response.
  • \(\sigma\) = sigmoid function.

The reward model learns to assign a higher score to the preferred response.

Example:

ResponseReward score
Response A0.25
Response B0.85

These numbers are illustrative. Reward scores are learned values, not necessarily calibrated probabilities of human approval.

5.3 Step 3: Optimize the language model using PPO

The reward model can provide a training signal to improve the language model.

A widely known RLHF implementation uses Proximal Policy Optimization (PPO).

The language model acts as a policy:

\[ \pi_\theta(y\mid x) \]

It generates responses, receives reward-model scores, and updates its parameters to increase expected reward.

However, maximizing reward without constraints can cause the model to exploit weaknesses in the reward model.

For example, a model might learn to generate overly long responses because the reward model mistakenly associates length with helpfulness.

To reduce excessive deviation from the supervised model, RLHF commonly includes a KL-divergence penalty.

A simplified objective is:

\[ \max_\theta \mathbb{E}{y\sim\pi\theta} \left[ r_\phi(x,y) - \beta D_{KL} \left( \pi_\theta(\cdot\mid x) \parallel \pi_{\text{ref}}(\cdot\mid x) \right) \right] \]

Where:

  • \(r_\phi\) = reward-model score.
  • \(\pi_\theta\) = policy being optimized.
  • \(\pi_{\text{ref}}\) = reference model, often the SFT model.
  • \(\beta\) = coefficient controlling the KL penalty.

The KL penalty discourages the updated policy from moving too far from the reference model.

5.4 PPO in simple terms

PPO is a policy-gradient reinforcement-learning algorithm designed to make controlled policy updates.

A simplified training loop looks like this:

        Instruction Prompt
                |
                v
         Current LLM Policy
                |
                v
        Generate Responses
                |
                v
         Reward Model Score
                |
                v
       Calculate Training Signal
                |
                v
          PPO Optimization
                |
                v
       Updated Language Model
                |
                +------ Repeat

PPO uses a clipped policy objective to limit how much the policy changes in a single update.

A common PPO clipped objective is:

\[ L^{CLIP}(\theta) = \mathbb{E}_t \left[ \min \left( r_t(\theta)A_t, \operatorname{clip}(r_t(\theta),1-\epsilon,1+\epsilon)A_t \right) \right] \]

Where:

  • \(r_t(\theta)\) = ratio of new and old policy probabilities.
  • \(A_t\) = advantage estimate.
  • \(\epsilon\) = clipping parameter.

This objective helps prevent excessively large policy updates.

5.5 Advantages and limitations of RLHF

Advantages

  • Incorporates human preference feedback.
  • Can improve instruction-following behavior.
  • Supports optimization of qualities that are difficult to express using simple supervised labels.
  • Can balance multiple response qualities through reward design.

Limitations

  • Human preference labeling can be expensive.
  • Reward models can learn evaluator biases.
  • Reward hacking can occur.
  • PPO training can be computationally demanding.
  • The resulting model may over-optimize the reward model rather than genuinely improve every aspect of response quality.

6. DPO: Direct Preference Optimization

Direct Preference Optimization (DPO) is an alternative preference-optimization method that learns directly from preference pairs without requiring a separately trained reward model and a conventional online PPO loop.

Instead of explicitly training a reward model and using it to guide reinforcement learning, DPO derives a preference objective that directly updates the language model relative to a reference model.

6.1 Why DPO was introduced

A traditional RLHF pipeline may require:

  • Human preference data.
  • Reward-model training.
  • Policy optimization.
  • Reference-model management.
  • Additional reinforcement-learning infrastructure.

DPO simplifies the optimization process by directly using preferred and rejected responses.

6.2 DPO training data

A DPO dataset typically contains:

PromptChosen responseRejected response
Explain Python.A clear beginner-friendly explanationAn inaccurate explanation
Write a secure password tip.Recommend unique passwords and MFARecommend reusing passwords
Explain overfitting.Accurate explanation with an exampleConfusing or incorrect explanation

The model learns to increase the relative likelihood of preferred responses and reduce the relative likelihood of rejected responses.

6.3 DPO mathematical objective

A commonly used DPO objective is:

\[ \mathcal{L}_{DPO} = -\mathbb{E} \left[ \log\sigma \left( \beta \left[ \log\frac{\pi_\theta(y_w\mid x)} {\pi_{\text{ref}}(y_w\mid x)} - \log\frac{\pi_\theta(y_l\mid x)} {\pi_{\text{ref}}(y_l\mid x)} \right] \right) \right] \]

Where:

  • \(\pi_\theta\) = policy model being trained.
  • \(\pi_{\text{ref}}\) = reference model.
  • \(y_w\) = preferred response.
  • \(y_l\) = rejected response.
  • \(\beta\) = temperature or regularization-related scaling parameter.
  • \(\sigma\) = sigmoid function.

In simple terms, DPO encourages the model to assign a higher relative probability to the preferred response than to the rejected response, compared with the reference model.

6.4 DPO workflow

       Instruction-Tuned Model
                  |
                  v
          Preference Dataset
                  |
          +-------+-------+
          |               |
          v               v
     Chosen Answer   Rejected Answer
          |               |
          +-------+-------+
                  |
                  v
          DPO Training Objective
                  |
                  v
         Preference-Optimized Model

6.5 Advantages and limitations of DPO

Advantages

  • Directly uses preference pairs.
  • Avoids a separate reward-model training stage in the standard formulation.
  • Does not require the conventional PPO rollout and policy-optimization loop.
  • Can be easier to implement than traditional PPO-based RLHF.

Limitations

  • Still requires reliable preference data.
  • Results depend on data quality and preference consistency.
  • Sensitive to training configuration and the reference model.
  • Does not automatically eliminate bias or reward-related problems.
  • Can overfit to narrow preference datasets.

7. RLHF vs. DPO: Key Differences

DimensionRLHF with PPODPO
Main approachReward-guided reinforcement learningDirect preference optimization
Preference dataHuman or evaluator comparisonsHuman or evaluator comparisons
Separate reward modelCommonly usedNot required in standard DPO
PPOCommonly used in the described pipelineNot required
Training complexityGenerally higherOften simpler
Policy optimizationUses reinforcement-learning updatesUses a preference-based supervised-style objective
Reference modelCommonly used for regularizationUsed in the objective
Main challengeReward quality and stable RL optimizationPreference data and objective behavior

Important: DPO is not simply another name for RLHF. It is an alternative approach to learning from preference data. RLHF is a broader family of techniques, and DPO is often discussed alongside RLHF as a preference-alignment method.


8. The Complete LLM Training Pipeline: A Worked Example

Imagine building a conversational AI assistant that helps users learn programming.

The training process could look like this.

Stage 1: Pretraining

Collect a large, appropriately sourced dataset containing:

  • Programming tutorials.
  • Documentation.
  • Books and technical articles.
  • General language data.
  • Code examples.

Train a Transformer model to predict the next token.

Result: A base model that has learned broad language and code patterns.

Stage 2: Supervised Fine-Tuning

Prepare high-quality instruction-response examples:

Prompt:
Explain Python lists to a beginner.

Target response:
A Python list is a collection that stores multiple
items in a single variable. Lists are ordered and
can be modified after creation.

Fine-tune the base model on these examples.

Result: An instruction-following programming assistant.

Stage 3: Preference Alignment

Generate multiple responses to programming questions.

Ask evaluators to compare:

  • Accuracy.
  • Clarity.
  • Completeness.
  • Helpfulness.
  • Safety.
  • Relevance.

Use preference data to train through PPO-based RLHF or DPO.

Result: A model optimized to produce responses that better match the defined preferences.

Complete pipeline

StageInputTraining methodOutput
PretrainingLarge-scale text and codeNext-token predictionBase model
SFTCurated demonstrationsSupervised fine-tuningInstruction model
Preference alignmentChosen and rejected responsesRLHF/PPO or DPOPreference-aligned model
EvaluationTest prompts and scenariosAutomated and human evaluationDeployment decision

9. Important Training Concepts Beyond the Three Main Stages

The three-stage pipeline is a useful framework, but modern LLM development often includes additional techniques.

9.1 Continued pretraining

A model can receive additional pretraining on domain-specific data after its original pretraining stage.

For example:

  • Medical literature.
  • Legal documents.
  • Financial reports.
  • Programming repositories.
  • Scientific publications.

This can improve domain-specific language representations, subject to data quality and evaluation.

Continued pretraining is different from SFT: it generally continues a language-model objective rather than training primarily on instruction-response demonstrations.

9.2 Instruction tuning

Instruction tuning is a form of supervised fine-tuning designed specifically to improve a model's ability to respond to instructions across different tasks.

It can use examples for:

  • Summarization.
  • Translation.
  • Question answering.
  • Classification.
  • Code generation.
  • Reasoning.
  • Structured output.

9.3 Synthetic data generation

Training examples can also be generated by another model or automated process.

A typical workflow is:

       Seed Instructions
              |
              v
       Teacher LLM
              |
              v
      Synthetic Responses
              |
              v
      Filtering and Review
              |
              v
       Training Dataset
              |
              v
        Student Model

Synthetic data can increase the scale and diversity of training examples, but poor-quality generated data can reinforce errors or biases.

It should be filtered, evaluated, and supplemented with reliable sources where appropriate.

9.4 Rejection sampling

Rejection sampling generates multiple candidate responses and selects those that meet a quality criterion.

For example:

  1. Generate five responses to a prompt.
  2. Score them using an evaluator or reward model.
  3. Retain responses that meet a predefined quality threshold.
  4. Use selected responses for additional training.

This can improve training-data quality without requiring every candidate response to be used.

9.5 Safety training and evaluation

Safety is not a single final training step.

It can involve:

  • Curated safety demonstrations.
  • Preference comparisons.
  • Adversarial examples.
  • Policy-based evaluations.
  • Refusal behavior training.
  • Privacy and data-handling tests.
  • Red-team exercises.

A model that scores well on general helpfulness may still fail on harmful requests, sensitive information, or adversarial prompts.

Safety must be assessed throughout the development process.


10. Evaluating an LLM After Training

Completing pretraining, SFT, or preference alignment does not automatically mean the model is ready for production.

The model should be evaluated across several dimensions.

Evaluation areaWhat it measuresExample
Language qualityFluency and coherenceHuman review
KnowledgeFactual performanceMMLU-style benchmarks
ReasoningMulti-step problem solvingMathematical and reasoning benchmarks
CodingProgramming abilityHumanEval-style evaluation
Instruction followingAbility to satisfy promptsInstruction-following test sets
SafetyHandling harmful or sensitive requestsRed-team evaluations
TruthfulnessReliability of factual claimsFact-checking and targeted benchmarks
EfficiencyServing cost and speedTokens per second, latency
RobustnessStability under varied inputsAdversarial and out-of-distribution tests

Benchmarks are useful for comparisons, but no single benchmark proves that an LLM is reliable in every real-world situation.

Important evaluation concepts

1. Perplexity

Perplexity measures how well a language model predicts a sequence of tokens.

\[ PP(W)= \exp \left( -\frac{1}{N} \sum_{i=1}^{N} \log P(w_i\mid w_{<i}) \right) \]

Lower perplexity generally indicates better predictive performance on the evaluated dataset.

However, lower perplexity does not automatically mean better instruction following, factual accuracy, or safety.

2. Human evaluation

Human evaluators can compare responses based on:

  • Helpfulness.
  • Correctness.
  • Clarity.
  • Relevance.
  • Completeness.
  • Safety.

Human evaluations are valuable, but results depend on the evaluation guidelines, annotator expertise, and consistency.

3. Automated evaluation

Automated metrics and model-based judges can help scale evaluation.

However, automated judges can have their own biases and may prefer certain writing styles over more accurate responses.

A reliable evaluation strategy combines automated testing, human review, and application-specific checks.


11. Common Challenges in LLM Training

1. High computational cost

Large models require significant accelerator memory, compute, storage, and networking resources.

Possible approaches:

  • Mixed-precision training.
  • Distributed training.
  • Gradient checkpointing.
  • Efficient attention.
  • Parameter-efficient fine-tuning.
  • Optimized data loading.

2. Poor-quality training data

Incorrect, duplicated, irrelevant, or biased data can negatively affect model behavior.

Possible approaches:

  • Deduplication.
  • Data filtering.
  • Source-quality checks.
  • Privacy-aware preprocessing.
  • Dataset documentation.
  • Evaluation across different data categories.

3. Catastrophic forgetting

During fine-tuning, a model can lose some capabilities acquired during pretraining, especially when training data is narrow or updates are too aggressive.

Possible approaches:

  • Carefully selected learning rates.
  • Diverse fine-tuning data.
  • Parameter-efficient methods.
  • Evaluation against general capability benchmarks.
  • Mixing appropriate general and domain-specific examples.

4. Hallucinations

A language model can generate plausible-sounding but incorrect information.

Preference alignment may improve response quality, but it does not guarantee factual correctness.

Possible supporting approaches include:

  • Retrieval-Augmented Generation (RAG).
  • Reliable external tools.
  • Source-grounded generation.
  • Factuality evaluation.
  • Explicit uncertainty handling.

5. Alignment tax and over-optimization

A model optimized for certain preferences may become overly cautious, verbose, or biased toward the preferences represented in its training data.

Teams should evaluate whether alignment improves the intended behavior without unnecessarily damaging other capabilities.

6. Data contamination

If evaluation examples appear in training data, benchmark results can become misleading.

Careful dataset management and contamination checks are important for reliable evaluation.


12. Pretraining vs. Fine-Tuning vs. RLHF vs. DPO

FeaturePretrainingSFTRLHF with PPODPO
Main goalLearn general language patternsFollow instructionsOptimize human-preferred behaviorOptimize human-preferred behavior
Typical dataLarge text and code datasetsPrompt-response examplesPreference comparisonsPreference comparisons
Main objectiveNext-token predictionResponse likelihoodReward-guided policy optimizationDirect preference objective
Human feedbackNot essential to the objectiveOften used to create demonstrationsCentral to preference labelsCentral to preference labels
Reward modelNoNoCommonly yesNo separate reward model required
Typical outputBase modelInstruct modelPreference-aligned modelPreference-aligned model

13. Frequently Asked Questions

Q1. What is pretraining in an LLM?

Pretraining is the initial process of training a language model on large-scale data to learn language patterns and useful representations. Decoder-only models commonly use next-token prediction as their training objective.

Q2. What is the difference between a base model and an instruction-tuned model?

A base model is trained primarily to predict or generate text. An instruction-tuned model receives additional supervised training on instruction-response examples so that it can better follow user requests.

Q3. What is Supervised Fine-Tuning (SFT)?

SFT is a training method that uses curated examples of prompts and desired responses to teach a pretrained model how to perform specific tasks and follow instructions.

Q4. What does RLHF stand for?

RLHF stands for Reinforcement Learning from Human Feedback. It uses human preference feedback to guide model optimization. A common implementation trains a reward model and then uses an algorithm such as PPO to optimize the language model.

Q5. What is the difference between RLHF and DPO?

Traditional PPO-based RLHF commonly uses a separate reward model and reinforcement-learning optimization. DPO directly optimizes the model using preferred and rejected response pairs without requiring that conventional reward-model-plus-PPO pipeline.

Q6. Is DPO better than RLHF?

Neither method is universally better. DPO can simplify preference optimization, while PPO-based RLHF offers a flexible reinforcement-learning framework. The best approach depends on data quality, model architecture, compute, optimization requirements, and evaluation results.

Q7. Does fine-tuning teach a model completely new knowledge?

Fine-tuning can change the model's behavior and can introduce domain-specific information, but it is not a reliable replacement for a continuously updated knowledge source. For frequently changing or source-sensitive information, retrieval-based systems can be more appropriate.

Q8. What is LoRA?

LoRA is a parameter-efficient fine-tuning method that learns low-rank weight updates while keeping most original model parameters frozen. It reduces the number of trainable parameters and can lower fine-tuning resource requirements.

Q9. Does RLHF eliminate hallucinations?

No. Preference alignment can improve response behavior, but it cannot guarantee factual correctness. Hallucination reduction requires additional evaluation and, where appropriate, reliable retrieval or tool use.

Q10. Can an LLM be trained without human feedback?

Yes. Pretraining and SFT can be performed without direct human preference comparisons in the optimization loop. However, human feedback is often valuable for defining and evaluating desirable assistant behavior. Automated and synthetic preference data can also be used, with their own quality limitations.


Conclusion

A modern LLM is developed through a sequence of training and evaluation processes rather than a single training run.

Pretraining provides foundational language capabilities by learning statistical patterns from large datasets.

Supervised Fine-Tuning (SFT) teaches the model to follow instructions and generate responses in a desired format.

Preference Alignment, through approaches such as RLHF and DPO, helps optimize the model toward responses that evaluators consider more helpful, relevant, and appropriate.

These stages work together, but none guarantees perfect accuracy, reasoning, or safety. Data quality, evaluation, model architecture, deployment constraints, and continuous improvement remain essential.

The central idea is:

Pretraining teaches a model to generate language. Fine-tuning teaches it to follow instructions. Preference alignment teaches it to favor responses that better match defined human preferences.

Understanding this pipeline is essential for anyone working with LLMs, Generative AI, fine-tuning, and modern AI assistant development.