IFT (Instruction Fine-Tuning) and SFT (Supervised Fine-Tuning)
SFT: fine-tuning a pretrained model on labeled input-output pairs using standard supervised learning (cross-entropy loss on target tokens, conditioned on some input).
IFT: A specific kind of SFT where the training data is specifically instruction/response pairs, for instance:
prompt: “Summarize this text: …” → completion: An actual summary of the text
prompt: “Write a poem about X” → completion: A poem about X.
The goal of IFT is therefore to get the model to behave like a chatbot, i.e., to follow natural language instructions and conduct a conversation, rather than just continuing the input text
Intuition: Before IFT
Prompt: What is the most delicious Spanish appetizer?
Response: What is the most delicious Spanish appetizer? What is the most delicious Mexican appetizer? What is the most delicious Portuguese appetizer? These are the kinds of questions that get asked all the time, so we decided to put together a definitive ranking…
The raw model isn’t “answering” so much as continuing the statistical pattern (predicting the next token)
The text might resemble some blog text about appetizers, but it is not answering the user’s question directly
Intuition: After IFT
Prompt: What is the most delicious Spanish appetizer?
Response: A top pick is patatas bravas (fried potatoes with a spicy tomato sauce and aioli).
After instruction tuning, the model recognizes the input as a request directed at it
The model produces a direct answer instead of continuing a hypothetical document
Data source
OpenAI hired a team of about 40 freelance labelers
Our prompt dataset consists primarily of text prompts submitted to the OpenAI API
Customers using the Playground were informed that their data could be used to train further models v
We heuristically deduplicate prompts by checking for prompts that share a long common prefix, and we limit the number of prompts to 200 per user ID.
labelling methods
Open AI’s labelling interface for InstructGPT
For each output, labelers give a Likert score for overall quality on a 1-7 scale, and also provide various metadata labels.
After evaluating each output individually, labelers rank all the outputs for a given prompt.
The team generated
\(\sim\) 13,000 training prompts for SFT/IFT
\(\sim\) 33,000 training prompts for the reward model training
\(\sim\) 31,000 training prompts for reinforcement learning (PPO)
Each major LLM has a template structure that organizes the main components of the chat so the model can recognize them.
Unambiguous structure
Allow multiturn conversations
Enables use of APIs
chat templates are required to format data for training so the models recognize the components of the message (system, user, assistent, in some cases tools)
Example
messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Hi! How can I help you today?"}, {"role": "user", "content": "What's the weather?"},]
This example is taken from the Hugging Face LLM course
The format and keywords vary for some models
This is the style for OpenAI style and Qwen
im stands for instruction message (e.g., im_start refers to the start of the instruction message)
<|im_start|>systemYou are a helpful assistant.<|im_end|><|im_start|>userHello!<|im_end|><|im_start|>assistantHi! How can I help you today?<|im_end|><|im_start|>userWhat's the weather?<|im_start|>assistant
IFT Best Practices
High quality completions needed
Generally, modern LLMs train with on the order of 1 million prompts
Item
Pretraining
IFT
Data
enormous
ca. 1 million prompt completions
Batch size
256
1024-2048
Learning rate
\(1\times 10^{-5}\)
\(3\times 10^{-4}\)
Loss function
CE
CE
Question
The learning rate is typically \(3\times 10^{-4}\) in pretraining but only \(1\times 10^{-5}\) for IFT. Why is this?
Answer
A lower learning rate is used during instruction fine-tuning (IFT) than during pretraining
IFT uses a much smaller amoutn of training data and therefore has a narrower data distribution.
The lower learning rate is thought to help prevent overfitting on the IFT prompts
Question
During pretraining, the model learns to predict the next token. The entire input texts are used
Both pretraining and IFT use the same kind of cross-entropy (CE) loss
During IFT, the model is training on prompt-completion pairs. What part of this data is used for training?
Answer
Loss Masking: In IFT, cross-entropy (CE) loss is applied exclusively on the assistant tokens (i.e., the completions, not the prompts)
Prompt tokens: The prompt tokens are masked (removed) from the loss calculation
We want the model’s objective to be focussed on generating accurate, context-aware completions
The foundational language model has already learned grammar, syntax, and general world knowledge during pretraining, and so the IFT phase can focus just on generation of completions
architecture learns to distinguish between user inputs and assistant outputs.
Tokenization and sequence packing
Raw text is tokenized into IDs and concatenated
maximize GPU memory utilization and minimize wasted padding compute
Loss masking
CE loss computed only on the assistant completion tokens; prompt tokens assigned a loss weight of zero
gradients focus exclusively on generation quality
Optimizer and learning rate configuration
AdamW optimizer with reduced peak learning rate
Do not erase pre-trained representations
Parameter strategy selection
Full-parameter updates or Parameter-Efficient Fine-Tuning (PEFT) methods like LoRA or QLoRA
Target attention projections to adapt weights efficiently
RLHF, GPT, and ChatGPT
Reinforcement learning was a key idea to take early versions of GPT to the current versions of chat agents such as ChatGPT
In the following slides, we will present
A brief introduction to (traditional) reinforcement learning (RL)
An explanation of the differences between RL and RL with human feedback (RLHF), which is used for LLMs
Reward models
Reinforcement Learning (RL): Basics
An agent iteratively takes actions within an environment according to a policy.
The state at time (step) \(t\) is denote \(s_t\), and the action that is proposed at this step is denote \(a_t\)
The policy \(\pi_\theta\) can either be deterministic or stochastic
When using reinforcement learning for LLMs, the policy is stochastic.
The policy \(\pi_\theta\) outputs a distribution over the set of possible actions, and the probability of a specific action is \(\pi_\theta(a_t\mid s_t)\)
After an action is taken, the environment emits a reward representing the desirability of the resulting state. The reward \(r_t\) may be negative, zero, or positive
image source: Reinforcement Learning: An Introduction, Richard Sutton and Andrew G. Barto
Actions and Transitions
The policy outputs an action based on the current state. The probability of action \(a_t\) given that we are currently in state \(s_t\) is \[
\pi_\theta(a_t\mid s_t)
\tag{1}\]
After the policy outputs an action, the state of the environment will be updated according to the transition function1
\[
P(s_{t+1} | s_t, a_t)
\tag{2}\]
Reinforcement learning: Example
Agent: the mouse
State: (x,y)-position of the mouse
Action: move to another valid (x,y) position
Reward model:
Move to an empty cell: reward of 0
Move to a cell with cheese: Reward of 2
Move to cell with cheese and electric shock: Reward of -1
Move to cell with cat: Reward of -5
Policy: rules how the agent selects the action to perform given current state; \(a_t\sim \pi(\cdot\mid s_t)\)
Goal of RL is to select a policy that maximizes the expected reward when an agent acts according to the policy
image source: https://www.freecodecamp.org/
RL: Trajectories
Intuitively, we can conceptualize RL as a trial and error process. As our agent acts in its environment, the training process reinforces—either positively or negatively—observed behavior via the reward. Hence, the name “reinforcement” learning.
A trajectory is a sequence of states
We begin from an initial state \(s_0\)
The agent iteratively
Samples action \(a_t\) based on the current state \(s_t\)
Transitions to the next state \(s_{t+1}\)
Receives reward \(r_t\)
The trajectory continues until the final state \(s_T\) is reached (terminal state or because a maximum number of states was reached)
The trajectory \(\tau\)1 is represented as follows: \[
\tau = \left(\underbrace{s_0,a_0,r_0}_{t=0},
\underbrace{s_1,a_1,r_1}_{t=1}, \ldots,
\underbrace{s_{T-1},a_{T-1},r_{T-1}}_{t=T-1},
\underbrace{s_T}_{t=T}\right)
\]
RL: Recap
Reinforcement learning: in sum:
RL training repeatedly samples different trajectories
The agent thereby explores the space of possible states and actions
The goal of RL learning is to discover parameters \(\theta\) that maximize reward of the most probable trajectories.
A human annotator sees two responses to a prompt and picks the better one - this preference pair is the training data for the reward model
Prompt: Explain why bananas are curvy in one sentence
Completion (Response A): Bananas grow upwards toward the sun against gravity through a process called negative geotropism, which causes their shape to bend into a distinctive curve.
Prompt: Explain why bananas are curvy in one sentence
Completion (Response B): Bananas start out growing toward the ground, but then they turn and stretch upward toward the sun, which makes them bend into a funny curve.
Bradley-Terry Model of preferences
Given two responses, \(i\) and \(j\), the probability that a judge prefers i over j, is modelled as
\[
P(i>j) = \frac{p_i}{p_i+p_j}
\]
According to this model, each item has a latent strength \(p_i>0\) with \(\sum_i p_i = 1\).
Reparameterizing with \(p_i=e^(r_j)\) allows us to work with unbounded scores \(r_j\in \mathcal{R}\) (ranging from \(-\infty\) to \(+\infty\)), such as the output of a neural network: \[
P(i>j) = \frac{e^{r_i}}{e^r_i + e^r_j} = \sigma(r_i-r_j)
\]
Thus, only score differences matter
HOMEWORK Prove that \(\tfrac{e^{r_i}}{e^r_i + e^r_j} = \sigma(r_i-r_j)\)
Bradley-Terry Model for RLHF
We are given a prompt \(x\), a chosen completion \(y_c\), and a rejected completion \(y_r\).
We score both with a reward model \(r_\theta\)
A reward model in RLHF is a neural network trained to act as a computational proxy for human judgment.
The reward model prompt and a model-generated response (or pair of responses) as input and outputs a scalar score (or logit) representing how well the output aligns with human preferences, values, helpfulness, and safety criteria.
They are initialized from a pretrained or instruction-tuned language model, modified to output a single scalar value, and trained on preference datasets using ranking objectives (like the Bradley-Terry pairwise loss) where the model learns to assign higher scores to responses preferred by humans over rejected offensive
The reward model will be used in the actual reinforcement learning step (e.g. PPO), where we need to score millions of iterations - thus, it will act as a proxy for human judgement
The goal of reward model training is to find the \(\theta\) that maximiizes this probability (the probability that the model assigns a higher score to the preferrend answer)
Bradley-Terry Model for RLHF: Derive loss function
starting from
\[
\theta^{*} = \arg\max_\theta \dfrac{e^{r_\theta(y_c\mid x)}}{e^{r_\theta(y_c\mid x)} + e^{r_\theta(y_r\mid x)}}
\] - divide numerator and denominator by \(e^{r_\theta(y_c\mid x)}\) and using the \(\exp\) notation to unclutter
Bradley-Terry Model for RLHF: Derive loss function
Recalling that \(\sigma(z)=\tfrac{1}{1+e^{-z}}\), we obtain finally \[
\theta^{*} = \arg\max_\theta \sigma(r_\theta(y_c\mid x) - r_\theta(y_r\mid x) )
\]
It is easier to work in log space, and so recalling that log is monotonic we have that \[
\arg\max_\theta \sigma(r_\theta(y_c\mid x) - r_\theta(y_r\mid x) ) = \arg\max_\theta \log \sigma(r_\theta(y_c\mid x) - r_\theta(y_r\mid x) )
\]
Finally, multiply by minus 1 to transform into a loss function to be minimized \[
\mathcal{L}(\theta) = - \log \sigma(r_\theta(y_c\mid x) - r_\theta(y_r\mid x) )
\tag{4}\]
This will be the loss that we can minimize by gradient descent
This is a binary cross-entropy loss
Preferences and RL training
Training a preference reward model requires pairs of chosen and rejected completions.
We take the predicted reward at the end of each sequence (only one reward for each sequence)
Preferences and RL training
Loss derived from predicted difference in reward for each sequence (the models predict the reward at the EOS token)
At inference (RL), we can pass in only one completion to the model!
Training with RLHF: InstructGPT
The authors start with the IFT model as described
The final unembedding layer is removed
Using the Supervised Fine-Tuned (SFT) model as the starting point for the reward model ensures that both the policy and the reward model share identical tokenizer vocabularies and low-level feature representations.
The unembedding layer is used to project hidden states back to the output vocabulary
This layer is removed and replaced by a linear project layer that yields a single scalar value
Open AI used a smaller model (6.7 Billion parameters: the 6B model) for the reward model (trained separately from the largest policy model - the 175B Davinci model)
Intuitively, Using a 6B reward model provides the necessary linguistic comprehension to evaluate complex prompts while cutting down GPU memory and compute overhead required during the PPO reinforcement learning phase.
Each prompt had between \(K=4\) to \(K=9\) completions. Therefore, for each prompt, up to \({K\choose 2}\) comparisons can be made
See Appendix C.2 of Ouyang et al. (2022) for Details of RM training
Recall that our implementation replaces the previous unembedding head (which projects each position’s final hidden state to a distribution over the vocabulary) with a reward head: a linear layer that projects the hidden state at the EOS token position to a single scalar — the model’s learned rating of the completion.
import torch.nn as nnclass BradleyTerryRewardModel(nn.Module):def__init__(self, base_lm):super().__init__()self.lm = base_lmself.head = nn.Linear(self.lm.config.hidden_size, 1)def forward(self, input_ids, attention_mask, eos_positions):# see next slide
The argument base_lm refers to a pretrained, instruction-tuned model — its transformer body is reused, just with the unembedding head swapped out.
The head maps a hidden state of dimension \(h\) h to a scalar: nn.Linear(h, 1) stores its weight as a \((1,h)\) matrix internally and (by default) also learns a bias term, computing the reward as \(r=\mathbf{w}^T\mathbf{x}+b\).
To calculate the loss, we need to run the model separately for the chosen completions and the rejected completions (batch)
-logsigmoid(r_chosen - r_rejected) implements Equation 4, which we show again here: \[\mathcal{L}(\theta) = - \log \sigma(r_\theta(y_c\mid x) - r_\theta(y_r\mid x) )\]
mean() averages the per-example loss down to a single scalar
Backpropagation will start with this average loss for the batch
Outcome of reward Modelling
For the reward model training stage specifically: all parameters are trainable
Thus, weights of both the copied transformer body and the newly-initialized linear head get updated by the Bradley-Terry loss.
The result is an LLM that has been trained to reward completions.
Once RM training finishes, the weights of the reward model are fixed and the model is only used to score the policy’s outputs, producing the reward signal for PPO.
RLHF: Big picture
Image source: Lambert, Illustrating Reinforcement Learning from Human Feedback (RLHF), Hugging face blog
The second lecture on RL will present the KL divergence shift policy, various strategies for RLHF learning, and some new developments
Policy gradient optimization
To train an GPT-style LLM, our initial policy \(\pi_{\theta}\) is simply the decoder model
Our goal with RL is to modify the parameters \(\theta\) of the policy to maximize the expected return (Equation 5).
For a deep neural network, we change the parameters of the network to mimimize a loss function using stochastic gradient descent.
In the context of RLHF, the gradient \(\nabla_\theta J(\pi)\) is known as the policy gradient and the algorithms that optimize it are known as the policy gradient algorithms.
Problem: To optimize \(J(\pi) = \int_{\tau} P(\tau\mid\pi)\cdot R(\tau) = \mathbb{E}_{\tau\sim \pi}\left[R(\tau)\right]\), we would need to evaluate it over all possible trajectories, which is computationally intractable.
We will present Policy gradient optimization, showing how to modify the gradient to simplify the expression and reduce variance (which tends to improve convergence of training)
Terminology
It is important to keep the distinction between these three concepts clear!
Reward (denoted \(r_t\)): a scalar signal emitted by the environment at a single timestep, in response to one action taken from one state.
Return (denoted \(R(\tau)\) or ): the (typically discounted) sum of rewards over one specific trajectory
\(R(\tau)=\sum_{t=0}^T \gamma^t r_t\): rewards over the entire trajectory
\(G_t = \sum_{t=t'}^T \gamma^t r_{t'}\): reward-to-go, the rewards from a certain step onwards
Expected return: the expectation of return over the distribution of trajectories induced by a policy: \[
J(\pi)= \mathbb{E}_{\tau\sim\pi_\theta}\left[R(\tau)\right]
\tag{5}\]
The expected return is an average return over (in principle) infinitely many rollouts.
In reinforcement learning, we are trying to maximize the expected return
We will introduce \(V^\pi\) and \(Q^\pi\) below - these are expected returns conditioned on a certain current state (\(V^\pi\)) or current state-action pair (\(Q^\pi\)).
Understanding policy gradients
We want to choose parameters \(\theta\) to maximize the expected reward \[
J(\theta) = \mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_t R(\tau) \right]
\]
In practice we cannot calculate the expectation directly because it would mean integrating over all possible trajectories
Therefore, we estimate the expectation with a sample over rollouts (trajectories) \[
J(\theta) \approx \frac{1}{N}\sum_{i=1}^N R(\tau_i) \qquad \text{ with } \tau_i\sim \pi_\theta
\]
The meaning of \(\mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_t \gamma^t r(s_t,a_t)\right]\) is \[
\int_\tau p_\theta(\tau)R(\tau)\mathrm{d}\tau
\]
Understanding policy gradients
We define the policy gradient \(\Delta \theta\) as
In RLHF \(\gamma=1\), because we optimize entire completions rather than individual steps
Policy gradient optimization: Deriving the gradient
Written as an integral, the objective is \[
J(\theta) = \mathbb{E}_{\tau\sim\pi_\theta}\left[R(\tau\right]
= \int_\tau P_\theta(\tau)R(\tau)\mathrm{d}\tau\qquad \bullet\text{ by definition of expectation}
\] Take the gradient of the reward (scalar) with respect to the parameters (vector) \[
\nabla_\theta J(\theta) = \nabla_\theta \int_\tau P_\theta(\tau)R(\tau)\mathrm{d}\tau = \int_\tau \nabla_\theta P_\theta(\tau)R(\tau)\mathrm{d}\tau
\]
Although we can sample trajectories from \(P_\theta(\tau)\) we cannot from \(\nabla_\theta P_\theta(\tau)\)
This is why the log derivative trick is needed
Policy gradient optimization: Deriving the gradient
To understand the log derivative trick, consider that \(\tfrac{d}{dx}\log f(x) = \tfrac{1}{f(x)}\tfrac{d}{dx}f(x)\)
This implies \[
f(x)\tfrac{d}{dx}\log f(x) = \tfrac{d}{dx}f(x)
\]
In Python code, the rollout generation (creation of prompts/completions) handles the sampling
the loss code handles the calculation of \(\log P(\tau\mid\theta)\cdot R(\tau)\)
Policy gradient optimization: Deriving the gradient
Here, we focus on simplifying the term \(\nabla_{\theta} \log P(\tau\mid\theta)\)
Recalling the probability of a trajectory: \(P(\tau) = \rho(s_0)\prod_{t=o}^{T-1}P(s_{t+1}\mid s_t,a_t)\pi_{\theta}(a_t\mid s_t)\) (because it is a gradient of a probability and does not satisfy requirements for being a probability)
completion_mask: 1 for tokens that are part of the completion, 0 for tokens that were part of the prompt
.sum(dim=1)leaves seq_log_probs with dimension \((\mathrm{batch},)\), one scalar per sequence, equal to \(\sum_{t=0}^T \log \pi_\theta (a_t\mid s_t)\) but restricted to the completion tokens
advantages represent \(\Psi_t\)
loss.backward(): autograd calculation of the gradients
Policy gradient optimization: Deriving the gradient
We can now put everything together
\[
\begin{align}
\nabla_{\theta}J(\pi_{\theta}) &=\int_{\tau} P(\tau\mid\theta) \nabla_{\theta} \log P(\tau\mid\theta) R(\tau) &\\
&=\mathbb{E}_{\tau\sim \pi_{\theta}}\left[ \nabla_{\theta} \log P(\tau\mid\theta)R(\tau)\right] & \bullet\text{by definition of the expectation} \\
&=\mathbb{E}_{\tau\sim \pi_{\theta}}\left[ \sum_{t=0}^{T-1} \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t)\,R(\tau)\right] & \bullet\text{substituting from previous slide} \\
\end{align}
\] - So, we have an expression to calculate the gradient, but, we are still taking the expectation over all possible trajectories: \(\tau\sim \pi_{\theta}\) - If we have a trajectory of 100 tokens and a vocabulary of 100,000 tokens, there are \[
100^{100000}\quad\text{possible trajectories}
\]
Policy gradient optimization: Deriving the gradient
It is clearly not tractable to calculate all \(100^{100000}\) trajectories…
Instead, we generate a sample \(\mathcal{D}\) of trajectories and calculate the sample mean \[
\hat{g} = \frac{1}{|\mathcal{D}|} \sum_{\tau\in\mathcal{D}}\sum_{t=0}^{T-1} \nabla_{\theta} \log \pi_{\theta}(a_t\mid s_t)R(\tau)
\tag{7}\]
and then use this to update the parameters \[
\theta_{k+1} = \theta_k + \eta\hat{g}
\]
This is known as stochastic gradient ascent.
The gradient typically would be calculated using automatic differentiation by pytorch (autograd)
The so-called reinforce algorithm repeatedly performs rounds of stochastic gradient ascent, updates parameters, runs \(|\mathcal{D}|\) trajectories, etc.
REINFORCE
One of the original RL algorithms was entitled
REward INcrement = Nonnegative Factor times Offset Reinforcement times Characteristic Eligibility
The Kullback-Leibler (KL) divergence from a distribution q(x) to a reference p(x) is defined as \[
D_{KL}(q\Vert p) = \mathbb{E}_{x\sim q}\left[\frac{q(x)}{p(x)}\right]
\]
RLHF fine-tunes a policy \(\pi_\theta\) to produce responses \(y\) to prompts \(x\) that maximize a reward \(r(x, y)\) derived from human preferences.
Pure reward maximization may cause reward hacking and distribution drift from a trusted SFT policy.
To counteract this, RLHF adds a KL penalty loss that regularizes the policy toward a fixed reference \(\pi_{ref}\)\[
J(\pi) =
\mathbf{E}\left[ r_\theta (x,y) - \beta D_{KL}(\pi\Vert \pi_{ref})\right]
\]
A KL divergence term is used in the practical implementations of the algorithms discussed above.
Sources
Lectures and blogs
RLHF Book Together with accompanying online lectures, this is a truly excellent resource for learning about RL, RLHF, and many of the developments in the field