Parameter-Efficient Fine-Tuning and Reasoning in LLMs
local graph
Chapter 8 — Parameter-Efficient Fine-Tuning and Reasoning in LLMs
Section titled “Chapter 8 — Parameter-Efficient Fine-Tuning and Reasoning in LLMs”While LLMs are impressive generalists, their true value in production often comes from their ability to function as domain-specific experts. This chapter is about how to transform a foundation model into such a specialist without updating billions of parameters. It is also about alignment: how to ensure the adapted model not only produces fluent text but also behaves in ways users find helpful, safe, and grounded in sound reasoning.
We begin with parameter-efficient fine-tuning (PEFT), the family of methods that unlock efficient adaptation of very large models. You will learn how LoRA inserts low-rank adapters into key linear projections, and how QLoRA extends this idea by storing the frozen backbone in 4-bit precision while training adapters in fp16 or bf16. But adapting parameters is only part of the story. Models must also be aligned with what people actually want. We therefore connect LoRA and QLoRA to the three major preference-based alignment families. First, RLHF with PPO: training a reward model from human preferences and optimizing the policy while keeping it close to a fluent reference. Second, Direct Preference Optimization (DPO), which skips reinforcement learning entirely and instead fits policy logits directly to pairwise comparisons. Third, Group-Relative Policy Optimization (GRPO), a more recent variant that normalizes trajectories against one another within a prompt to stabilize optimization. Each of these objectives can be implemented efficiently with adapters alone, making them practical at scale.
Finally, we address reasoning itself. We will formalize reasoning as a probabilistic process over latent steps. By the end of this chapter, you will understand not only how to adapt large models, but also how to align and evaluate them so they can reason as specialists in your domain. We will bridge the gap between theoretical mechanics and practical engineering, preparing you to make the critical choices that define a production-ready system: which layers to adapt, what rank and scaling factors to choose, whether to merge or serve adapters separately, and how to set up A/B tests or versioning pipelines in the field.
In a nutshell, here are the main topics we’ll cover:
- Fine-tuning LLMs with LoRA and QLoRA
- Reinforcement learning with human feedback
- Advanced RLHF techniques for LLMs
- Reasoning in LLMs
Technical requirements
Section titled “Technical requirements”To follow along with the implementations and theory in this chapter, you should be comfortable with the following:
- Core architectures and math: A solid understanding of Transformers (specifically self-attention and MLP blocks), automatic differentiation, and basic PyTorch.
- The Hugging Face ecosystem: Familiarity with the Transformers and PEFT libraries, as well as bitsandbytes for quantized training, will be essential for reproducing our examples.
- Reinforcement Learning (RL) foundations: A basic grasp of concepts such as policy, reward, and PPO is useful. However, we will build the necessary intuition for these concepts carefully to ensure the chapter remains accessible.
Fine-tuning LLMs with LoRA and QLoRA
Section titled “Fine-tuning LLMs with LoRA and QLoRA”Building on our understanding of how large models process information, this section provides a guide to fine-tuning LLMs with LoRA and QLoRA. We focus on these specific techniques because they solve the primary bottleneck in modern AI development: the massive hardware requirement for full-parameter updates. You will learn how to steer a general-purpose model toward specialized tasks, such as drafting clinical notes or adopting a specific brand voice, without the need for industrial-scale compute clusters. By the end of this section, you will be able to configure adapter matrices and utilize 4-bit quantization to train specialized models on a single consumer-grade GPU, providing a practical blueprint for building efficient, high-performance domain experts.
Problem setup and notation
Section titled “Problem setup and notation”We begin by fixing notation for a pretrained causal language model. Let a pretrained causal LM have parameters and hidden size. For a tokenized sequence, the model defines. Supervised fine-tuning minimizes the negative log-likelihood:

Transformer layers interleave attention/MLP nonlinearities with linear submodules. For a linear submodule (e.g., or MLP ), let and for,.
Full fine-tuning updates all of. Parameter-Efficient Fine-Tuning (PEFT) holds most of fixed and introduces a small set of trainable parameters to adapt the model.
Low-Rank Adaptation (LoRA)
Section titled “Low-Rank Adaptation (LoRA)”LoRA instantiates this idea by freezing and learns a low-rank update:
Here, (“LoRA ”) controls update strength; using keeps the expected scale of roughly invariant as changes. For input,
A key detail is how the adapters are initialized. To preserve the pretrained function at step zero, LoRA initializes:
Then, and. This stabilizes optimization while allowing gradients to update immediately.
Benefits and complexity
Section titled “Benefits and complexity”LoRA’s primary advantage is parameter efficiency. Rather than updating the full matrix, LoRA trains only and, for a total of trainable parameters with. Only these adapters carry gradients and optimizer states, cutting memory substantially.
From a computational perspective, the base product still costs. The adapter adds at and at, that is, an extra when unmerged—small for.
After training, the adapters can be merged into the base weights by setting, removing this runtime overhead (re-quantize if serving quantized).
Typical hyperparameter choices are,, and an optional adapter dropout. Adapting attention projections (often and ) gives most of the benefit; some setups also adapt or selected MLP matrices.

A diagram of a flowchart AI-generated content may be incorrect.
Figure 8.1: Low-rank adaptation in LLMs
Gradients in LoRA
Section titled “Gradients in LoRA”Before we examine the specific mechanics of a LoRA-augmented layer, it is essential to revisit the role of gradients. In the context of neural networks, a gradient represents the direction and magnitude of the steepest increase in a loss function; by moving in the opposite direction, we “tune” the model’s weights to minimize error.
In traditional full fine-tuning, calculating and storing these gradients for billions of parameters is what creates the massive memory and compute overhead that makes LLM training so costly. LoRA changes this dynamic by freezing the original weights and only calculating gradients for the tiny, newly inserted adapter matrices. This allows the model to learn complex task-specific corrections with orders-of-magnitude fewer trainable parameters, effectively approximating the impact of a full update at a fraction of the cost.
With this conceptual foundation in place, let’s look at how these gradients flow through a LoRA-augmented linear submodule. Consider a LoRA-augmented linear submodule with a minibatch of inputs
(batch size ). The layer output is
where is the frozen base matrix,
and are the trainable adapters, and scales the update. Because, the adapter path adds a small, controlled low-rank perturbation.
Let

be the upstream gradient from the loss. As in a standard linear layer, the gradient with respect to the effective weight is

Using the chain rule to distribute this gradient to and gives compact, low-rank forms:

These can be implemented efficiently without ever forming the full matrix:
- Compute (cost )
- Then (cost )
- Then by first forming (cost ) and multiplying by (cost )
For completeness, the gradient with respect to the inputs is

Behavior at initialization
Section titled “Behavior at initialization”With the paper’s recommended init,:
- (the pretrained function is preserved at step 0)
- is generally non-zero (since )
- at the very first step (because ), after which updates to make from step 1 onward.
- This staggered start helps keep the early optimization stable.
Complexity and memory
Section titled “Complexity and memory”LoRA trains only parameters instead of. In forward/backward passes:
- The base product still costs
- The adapter adds and with extra cost
- Only carry gradients and optimizer states, cutting memory substantially
- If you merge after training (), the adapter’s runtime overhead is removed
Dropout on the adapter path
Section titled “Dropout on the adapter path”While the core mechanics of LoRA focus on efficiency, the choice to include dropout is a strategic decision rather than a structural necessity. This technique is often categorized as optional because its value depends heavily on the size of your training data and the complexity of the task at hand. By introducing a dropout layer, you can steer the model toward better generalization, ensuring that the adapter matrices learn robust features instead of overfitting to the specific noise of a small dataset.
Some implementations apply dropout to the bottleneck activations: with mask. The gradients become

That is, the mask gates the signal flowing through the adapter; dropout is disabled at inference.
Takeaway
Constraining to the low-rank form concentrates learning into a small subspace. This yields the same simple gradient structure as a dense layer but with far fewer trainable parameters, lower memory, and modest extra compute—while retaining enough flexibility to adapt large models effectively.
Where to apply LoRA
Section titled “Where to apply LoRA”When deciding where to apply LoRA, the common practice is to insert the low-rank adapters into the projection matrices of the Transformer’s attention and, optionally, its feedforward layers. In a standard multi-head self-attention block, we have four key projection matrices:, each of shape
, where is the model’s hidden size. Applying LoRA to these matrices means that we learn small low-rank updates for each of them, while leaving the original weights frozen. This approach is effective because the attention projections control how information is distributed and mixed across tokens, so adapting them gives the model a strong ability to specialize to new tasks with very few additional parameters.
If the hidden size is, then each of these four projections contributes
parameters. The number of trainable parameters introduced by LoRA per layer is

where the sum is taken over the projections to which LoRA is applied, and are the input and output dimensions of each projection, and is the rank of the adapters. For square
matrices, this simplifies to
since each projection has, and there are four projections per layer. Across all layers of a Transformer, the total number of additional parameters is
This is typically less than 1% of the base model’s parameters for modest choices of,meaning we achieve a substantial reduction in parameter count without sacrificing the model’s ability to adapt. For some tasks, LoRA is also applied to the MLP (feedforward) projections inside the Transformer block, particularly when more expressive fine-tuning is needed, but the dominant practice remains focusing on the attention weights because they have the largest effect on model behavior for many tasks.
This placement strategy is what makes LoRA both parameter-efficient and task-effective: by targeting the weights most responsible for token interaction (attention projections), we get maximal representational flexibility with minimal overhead. This design choice also helps keep memory usage and compute cost low, enabling fine-tuning even LLMs on relatively modest hardware. Figure 8.2 shows the places that LoRA can be applied in a decoder-based transformer architecture:

A diagram of a decoder block AI-generated content may be incorrect.
Figure 8.2: Places that LoRA can be applied in a decoder-based transformer architecture
Merging for inference
Section titled “Merging for inference”After training, LoRA adapters can be merged into the base model weights to produce a single, self-contained set of parameters suitable for inference. Recall that LoRA introduces a low-rank update
where and are the learned adapter matrices and is the scaling factor. At inference time, we can fold this update directly into the frozen base weight matrix:
This operation produces a single weight matrix that combines the original pre-trained weights and the learned low-rank correction. Once this merge is done, the model behaves exactly as if LoRA adapters were still present, but there is no additional runtime overhead—we have effectively transformed the model back into a standard dense Transformer with updated weights.
Merging is particularly straightforward when the base model is stored in standard floating-point precision (e.g., FP16 or FP32): we simply add to and save the result. For quantized models such as those fine-tuned with QLoRA, merging requires a dequantization step: the base quantized weights must first be temporarily converted back to a higher-precision format (typically FP16 or FP32) so that the sum can be computed accurately. After the merge, the resulting weights can be re-quantized if desired, producing a single quantized checkpoint ready for efficient inference.
This merging procedure is highly useful in production environments because it removes the need to carry around separate adapter weights and apply them dynamically at runtime, leading to faster loading, lower memory usage, and simpler deployment pipelines.
Quantized LoRA (QLoRA)
Section titled “Quantized LoRA (QLoRA)”QLoRA extends the idea of LoRA to enable fine-tuning of LLMs on a single GPU. The core idea is to keep the base model frozen and stored in 4-bit quantized precision, while training the LoRA adapters in higher precision (such as bfloat16 or float16). This achieves two goals simultaneously:
- Drastically reducing memory requirements
- Allowing the adapters to both compensate for quantization error and adapt the model to downstream tasks
In this section, we will analyze how QLoRA compares to standard LoRA in practice, focusing on the trade-offs between memory reduction and model fidelity. We will specifically demonstrate how techniques such as NF4 (4-bit NormalFloat) and paged optimizers allow us to recover the quality of full fine-tuning while significantly lowering the barrier to entry for model adaptation.
Quantization preliminaries
Section titled “Quantization preliminaries”To understand QLoRA, let us first recall how quantization works. Suppose we have a real-valued weight. Uniform affine quantization maps into a low-precision integer code
using a scale factor
and a zero-point
:

where
lies in the integer range
, and
is the dequantized weight used in computation. Intuitively, we are compressing a continuous value into a small set of discrete bins indexed by integers, and then reconstructing it approximately as
.
QLoRA typically employs NF4 (NormalFloat 4-bit) quantization, which uses a non-uniform codebook designed specifically for weights that approximately follow a normal distribution. More generally, in codebook quantization, we define a codebook

where
is the bit width (e.g.,
), and quantization selects the index

so that dequantization is

QLoRA further introduces double quantization, in which even the per-group scales themselves are quantized (typically to 8 bits). This reduces memory overhead while still preserving accuracy. Figure 8.3 shows how quantization in QLoRA works. Please note that QLoRA applies dequantization on the fly during the compute process.

A diagram of different types of storage AI-generated content may be incorrect.
Figure 8.3. QLoRA’s storage and compute
During training, we treat the quantization/dequantization process as

where the base weights
are frozen and used only in quantized form, while the LoRA adapters are trainable.
Importantly, because the quantization operator is non-differentiable, training treats the base weights as frozen and backpropagation updates only the adapters. Gradients flow through the dequantized computation path to activations and adapter parameters, not to the int4 stored weights. Importantly, because the quantization operator is non-differentiable, training treats the base weights as frozen, and backpropagation updates only the adapters. Gradients flow through the dequantized computation path to the activations and adapter parameters, not to the int4 stored weights.
Forward computation with QLoRA
Section titled “Forward computation with QLoRA”Consider a standard linear layer with input. Under QLoRA, the forward pass becomes

where:
is the dequantized 4-bit base weight (frozen)- and are the LoRA adapters trained in higher precision (bf16/fp16)
- is the LoRA scaling factor
The key insight is that the expensive base matrix multiplication uses quantized storage but is dequantized to fp16/bf16 just-in-time for compute, while the adapters remain in higher precision for stability. Only the adapters and are updated during fine-tuning.
Memory and compute requirements
Section titled “Memory and compute requirements”Let
denote the total number of parameters in the base model. Storing them in 4-bit precision requires approximately
bytes. There is an additional overhead for scales and metadata, often modeled as
, where
–0.1 depending on group size and whether double quantization is applied.
On top of this, the LoRA adapters introduce
parameters, stored in bf16/fp16, along with their optimizer states. A rough working memory estimate during training is:

where
is typically in the range of 6–8 bytes per parameter for mixed-precision optimizers such as Adam.
In terms of compute, the cost is dominated by two operations:
- Multiplication with the dequantized
(expensive but efficient since it uses fp16/bf16 GEMM on the GPU). - The adapter path
, which adds only operations per projection—negligible when.
Thus, QLoRA achieves fine-tuning with only a small overhead compared to inference with the base quantized model.
Training objective with QLoRA
Section titled “Training objective with QLoRA”The training objective remains the same as in standard LoRA. Given a minibatch, the outputs are

and gradients flow only to and. The quantized base weights
are frozen, so there are no gradients with respect to the 4-bit storage. This makes QLoRA both memory-efficient and stable, since the quantized backbone is left untouched and only lightweight adapters are trained.
Practical training flow for LoRA and QLoRA
Section titled “Practical training flow for LoRA and QLoRA”Fine-tuning LLMs with LoRA and QLoRA follows a structured pipeline. The aim is to adapt massive pretrained models efficiently, both in terms of memory usage and compute cost, while maintaining high stability during training. In this section, we will describe the process step by step—from data preparation to optimization—and illustrate both the mathematical details and the practical engineering choices. Beyond the high-level workflow, these choices require balancing model capacity against hardware constraints—specifically selecting which layers to target and determining the optimal rank. You will also navigate trade-offs in efficiency and stability by configuring 4-bit NF4 quantization, paged optimizers, and adapter dropout for regularization. Ultimately, these engineering decisions culminate in how you deploy, choosing between the low-latency benefits of merging adapters or the modular flexibility of maintaining independent versioning pipelines.
Data and objective
Section titled “Data and objective”The choice of training data depends on the downstream task. For instruction-tuning, we prepare input-output pairs (prompt → response), whereas for general language modeling, we simply use next-token prediction data.
The objective function is typically the causal language modeling loss:

where the model predicts each token
given its context.
However, when the dataset is small or domain-specific, there is a risk that the adapters overfit and drift too far from the base model’s general distribution. To counter this, a regularization term is often added in the form of a KL divergence between the adapted model’s predictions
and the base model’s frozen predictions
:

where controls how strongly the fine-tuned model is encouraged to stay close to the base model. This stabilizes training, especially in low-resource regimes.
Targeted modules
Section titled “Targeted modules”One of LoRA’s key strengths is that it does not need to be applied everywhere. Instead, it targets a small set of weight matrices where adaptation has the greatest impact. In transformer architectures, these are typically:
- Attention projections ()
- Feed-forward (MLP) projections ()
For decoder-only LLMs in particular:
- Applying LoRA to Q, V, O is often sufficient, giving excellent trade-offs
- Adding LoRA to MLPs provides extra expressivity but increases adapter size
This selective targeting explains why LoRA is so parameter-efficient—we adapt only the “bottleneck” weights that control token interactions.
Initialization and stability
Section titled “Initialization and stability”The earliest steps of training are often the most fragile, so careful initialization matters. To ensure the fine-tuned model begins nearly identical to the base model, LoRA adapters are initialized as:
,
which ensures that, at initialization,
A scaling factor is also applied:

where is the rank of the adapter and is a hyperparameter controlling its effective strength.
In practice:
- Layer norms and biases remain frozen
- Sometimes the output embedding is unfrozen for domain adaptation.
Together, these choices ensure that LoRA begins as a “small nudge” on top of the pretrained weights. This reduces the risk of catastrophic forgetting in the first few training steps. Because the adapter path is
, and is initialized to zero, the initial output of the adapter branch is zero. This is why the model starts out identical to the base model—it’s a mathematical “pass-through” until training begins.
Optimization strategy
Section titled “Optimization strategy”Once the adapters are in place and initialized, training proceeds much like standard fine-tuning, but with a lighter optimization footprint. Because only a small number of parameters are updated, LoRA and QLoRA can use more aggressive settings while remaining stable.
Selecting the right configuration is a balancing act between model capacity and computational efficiency. While the default values provide a strong baseline, fine-tuning these hyperparameters allows you to tailor the adapter’s influence to the complexity of your specific dataset. By carefully adjusting the following settings, you can optimize the learning signal while maintaining the stability required for large-scale model adaptation.
- Optimizer: AdamW
- Precision: mixed precision (bfloat16 is common)
- Learning rates: higher than full fine-tuning (since adapter capacity is small), typically

- Schedules: linear warmup (1–3% of steps) followed by cosine decay
- Gradient clipping:
, especially important in QLoRA due to quantization noise
Memory management and long contexts
Section titled “Memory management and long contexts”As context lengths grow, training quickly becomes memory-bound. In practice, most VRAM is consumed by activations rather than model parameters. To reduce memory load, do the following:
- Use gradient checkpointing to trade compute for memory
- Employ FlashAttention kernels to reduce attention memory usage
- In QLoRA, use paged optimizers (such as 8-bit Adam or Lion) to avoid CPU/GPU memory spikes
These techniques make it possible to fine-tune models with billions of parameters on a single GPU.
Hyperparameter choices
Section titled “Hyperparameter choices”LoRA introduces a small but important set of additional hyperparameters. While optimal values are task-dependent, the following rules of thumb work well in practice:
- Rank : 4–32. Small is sufficient for small tasks; larger for domain shifts
- Scaling : usually 8–64, giving an effective scale
- LoRA dropout: 0–0.1 for small datasets (adds robustness)
- Target modules: start with
, add and MLP for higher accuracy - Batch size: as large as VRAM allows
LoRA vs QLoRA
Section titled “LoRA vs QLoRA”The choice between LoRA and QLoRA is largely driven by memory constraints and deployment requirements:
- LoRA: Use when the base model can fit in fp16/bf16. Simple, efficient, supports merging adapters back into weights.
- QLoRA: Use when VRAM is limited. Stores the base model in 4-bit precision, dequantizes on-the-fly, and trains adapters in higher precision. Adapters recover performance close to full fine-tuning.
At inference time, you can do one of the following:
- Keep the base quantized and add adapters
- Dequantize the base and merge adapters into final weights
Use case: query projection
Section titled “Use case: query projection”The previous sections described the LoRA and QLoRA training pipeline at a high level. It’s now time to walk through a simple end-to-end example, focusing on how LoRA modifies a single attention projection and how gradients flow during training.
Consider a query projection with input
.
In the pretrained model, the query vector is computed as:

With LoRA or QLoRA applied, the projection becomes:

Here,
is either frozen fp16 (LoRA) or dequantized from int4 (QLoRA).
Gradient flow
Section titled “Gradient flow”Let
denote the gradient of the loss with respect to the adapted query vector. The gradients with respect to the LoRA parameters are:

These gradients are accumulated across all tokens and heads, and Adam updates only
.
Parameter efficiency
Section titled “Parameter efficiency”The impact of this design becomes clear when counting parameters. If each transformer block contains four attention projections and two MLP projections, each of size
, the total number of adapter parameters add to about:

where is the number of layers.
For example, with
,
,
:

which is < 0.2% of a 7B model. This tiny footprint explains why LoRA scales so well.
Avoiding forgetting
Section titled “Avoiding forgetting”Because LoRA adapters have limited capacity, they can still overfit or drift if training is poorly controlled. Common mitigation strategies include the following:
- Smaller adapter ranks
- Weight decay on
- Early stopping by validation perplexity
- Mixing logits during warmup:

- KL penalties, as described earlier
These keep the adapted model “anchored” to the pretrained distribution while learning task-specific refinements.
Training flow
Section titled “Training flow”Figure 8.4 shows the LoRA training flow. Figure 8.5 shows the QLoRA training flow. Figure 8.4 shows the LoRA training process, where the base model remains in full precision and only the adapters are trained:

A diagram of a training flow AI-generated content may be incorrect.
Figure 8.4: The flow chart of training LoRA
Figure 8.5 shows the QLoRA pipeline, highlighting quantization, on-the-fly dequantization, and adapter updates:

A diagram of a training flow AI-generated content may be incorrect.
Figure 8.5: The QLoRA training process
After fine-tuning, the adapted model should be evaluated on both language modeling quality and task-specific metrics.
Evaluation and merging for deployment
Section titled “Evaluation and merging for deployment”After fine-tuning, first evaluate the adapted model on both language modeling quality and task metrics. For generative LMs, report perplexity (or validation NLL). For instruction/SFT tasks, also report downstream metrics such as Exact Match, F1, BLEU/ROUGE, or accuracy, depending on the benchmark.
Once quality is acceptable, decide how to serve the model:
If the base model is in full precision (fp16/bf16/fp32) and latency matters, fold the adapters into the base weights to remove runtime branches:
Replace
and discard. This yields a single dense checkpoint with no LoRA runtime overhead (just a standard GEMM).
If the base model is quantized, as in QLoRA, there are two common deployment options:
- Two-branch inference (no merge):
where
is the dequantized 4-bit weight used for compute. Pros: simple, avoids re-quantization, preserves 4-bit storage. Cons: an extra low-rank path adds a tiny compute/latency overhead.
- Merged higher-precision checkpoint: Temporarily dequantize (e.g., to fp16/bf16), compute, and (optionally) re-quantize to the format your serving stack supports. Pros: single branch at inference. Cons: requires a merging step and a format that can represent without undue error.
In both cases, the numerical behavior matches training: merging simply bakes the learned low-rank correction
into the base weight tensor.
Let’s summarize the full workflow:
- Target modules and rank : Choose attention (Q,V or Q,V,O) first; add MLPs if needed. Pick based on VRAM and task difficulty
- LoRA path: Keep base in bf16/fp16, train, then merge
for the fastest serving - QLoRA path: Quantize the base to 4-bit (e.g., NF4 with per-group scales, double-quantized scales), freeze the base, train in bf16; at inference, do either of the following:
- keep two-branch (
)
- dequantize & merge to produce a single checkpoint (then optionally re-quantize)
- keep two-branch (
- Monitoring: Track validation loss/perplexity and task metrics; if under- or overfitting, retune
(with ), LR, dropout, and targeted modules - Deployment hygiene: Record quantization/scale metadata, adapter rank and scaling, and any tokenizer/versioning so checkpoints are reproducible
So far, we have explored parameter-efficient fine-tuning methods such as LoRA and QLoRA, which allow LLMs to be adapted efficiently to new tasks while keeping memory and compute costs manageable. These methods emphasize structural efficiency: instead of modifying all of a model’s billions of parameters, we introduce lightweight adapters or quantization strategies that retain most of the pretrained knowledge while enabling targeted adaptation. However, while these techniques are powerful for supervised fine-tuning and domain adaptation, they are fundamentally limited by the quality of the training data. Instruction-tuned models, even when efficiently adapted, can only reproduce patterns and preferences directly encoded in their datasets. To align models more closely with human values, preferences, and nuanced goals, we need approaches that go beyond standard supervised objectives.
This is where Reinforcement Learning from Human Feedback (RLHF) provides a way to train models not only on static labeled data but also on interactive, preference-driven signals that reflect what humans actually want from the system. The next part of this chapter will explore advanced RLHF techniques for LLMs, including reward modeling, preference optimization, and newer methods that extend or refine the standard RLHF pipeline. These approaches represent the natural next step: moving from efficient adaptation of parameters (LoRA/QLoRA) to efficient adaptation of behavior through human feedback and reinforcement learning.
Reinforcement learning with human feedback
Section titled “Reinforcement learning with human feedback”RLHF is a training framework that helps align LLMs more closely with human expectations. Instead of relying only on supervised datasets, RLHF introduces a feedback loop in which human judgments guide the optimization of model behavior. This makes the model’s responses not only plausible in terms of language, but also more useful and safe in terms of what people actually want.
The process begins with supervised fine-tuning, where the model is trained on carefully curated prompt–response examples. These examples, often written or verified by humans, provide the model with an initial sense of how to respond in a helpful and coherent way. But supervised fine-tuning alone has limitations, because it cannot cover the vast diversity of prompts a user might ask, and it tends to make the model mimic the style of the examples without deeper alignment to preferences. To address this, RLHF introduces a reward model. Human annotators are asked to compare and rank outputs from the language model for the same prompt. By indicating which response is better—perhaps more accurate, more polite, or less harmful—they create training data that allows a reward model to learn to predict human preferences. This reward model then becomes the scoring mechanism that tells the system whether a new output is “good” or “bad.”
The final stage applies reinforcement learning, usually with an algorithm such as Proximal Policy Optimization (PPO). Here, the original model is treated as a policy that generates text given a prompt. Instead of optimizing for next-token prediction as in pretraining, the policy is now optimized to maximize the score from the reward model. In practice, this means the language model gradually learns to produce responses that humans are more likely to prefer, while avoiding those that people tend to reject.
This approach is especially important for LLMs because raw pretrained models, although powerful, often produce outputs that are unhelpful, irrelevant, or even unsafe. They may generate biased language, confidently state incorrect information, or fail to follow instructions. RLHF helps correct these issues by shifting the training signal from purely statistical likelihoods to values informed by human judgment. The benefits are that models become more aligned with user intent, safer to deploy, and more engaging to interact with. They are better able to strike the right balance between accuracy and politeness, which leads to improved reliability in real-world applications. In a broader sense, RLHF transforms an LLM from a system that simply imitates the patterns of its training data into one that adapts to human values and goals. It is the reason modern conversational models such as ChatGPT feel more cooperative and aligned with the way people expect an assistant to behave.
While the standard RLHF pipeline has proven remarkably effective, it is not without its challenges. Training a separate reward model, collecting high-quality human preference data, and running reinforcement learning at scale are all resource-intensive steps. Moreover, RLHF can sometimes introduce instability, reward hacking, or overly cautious model behavior. These limitations have motivated researchers to explore advanced extensions and alternatives to the classic pipeline.
It’s time now to examine more advanced RLHF techniques. Topics such as reward shaping, direct preference optimization, and hybrid approaches that combine supervised signals with reinforcement learning have emerged as promising ways to improve both efficiency and stability. Together, these methods represent the ongoing evolution of alignment strategies, moving beyond the basic RLHF recipe toward more refined techniques that bring LLMs even closer to human intent.
Advanced RLHF techniques for LLMs
Section titled “Advanced RLHF techniques for LLMs”The standard RLHF pipeline, consisting of supervised fine-tuning, reward modeling, and reinforcement learning with PPO, has proven to be one of the most effective frameworks for aligning LLMs with human intent. In its simplest form, the model learns a policy
that generates outputs for prompts
, while a reward model
provides a scalar signal estimating human preference. The objective of reinforcement learning is then to maximize the expected reward:

often with an added KL penalty to keep the fine-tuned model close to the original pretrained distribution
:

This baseline approach is powerful but comes with well-known challenges. Reward models are imperfect proxies for human judgment, reinforcement learning introduces instability, and the need for large volumes of human preference data can be prohibitively expensive. These limitations have motivated the development of more advanced techniques that either refine the reward signal, simplify the optimization procedure, or combine multiple alignment signals into a more robust training objective.
Among these refinements, we focus on three complementary directions. First, we examine Direct Preference Optimization (DPO), which removes the explicit reinforcement learning loop and instead aligns models directly from preference data using a contrastive objective. Second, we introduce Group Relative Policy Optimization (GRPO), a scalable reinforcement learning variant that stabilizes policy updates by normalizing rewards across groups of candidate responses. Then, in the next and final section of this chapter, we broaden the discussion beyond alignment objectives to consider reasoning in LLMs, introducing a formal framework for modeling and training intermediate reasoning steps under supervised, latent, and preference-based regimes.
Direct Preference Optimization (DPO)
Section titled “Direct Preference Optimization (DPO)”While traditional RLHF relies on reinforcement learning with a learned reward model and a policy optimization algorithm such as PPO, Direct Preference Optimization (DPO) simplifies the pipeline by eliminating the explicit reinforcement learning step. Instead, it directly optimizes the model’s likelihood to match human preferences using a contrastive objective derived from preference data. This makes DPO both simpler to implement and more stable in practice.
To see how this works, it helps to start from the kind of data we actually collect in alignment settings. Suppose we have a dataset of preference pairs: for each prompt
, humans rank two candidate responses
, where
is preferred over
. In the standard RLHF pipeline, this data would be used to train a reward model
. DPO, by contrast, avoids training a separate reward model and instead directly adjusts the policy
.
The key assumption is that there exists a latent reward function such that the probability of preferring
over
follows a logistic model:

where
is the sigmoid function.
The crucial insight is that this reward does not need to be modeled explicitly. Instead of learning explicitly, DPO shows that we can express this preference probability in terms of the ratio between the fine-tuned policy
and the reference (pretrained) policy
:

This connection allows us to directly optimize the model toward preferred responses without an intermediate reward model.
Once preferences are expressed this way, defining the training objective becomes straightforward. Given a preference pair
, the DPO objective encourages the policy to assign a higher relative likelihood to
compared to
, relative to the reference model. The loss is:

where is a temperature-like parameter that controls how strongly the policy is updated relative to the reference. Figure 8.6 shows how DPO works:

A diagram of a program AI-generated content may be incorrect.
Figure 8.6: The training process of DPO
At an intuitive level, this objective behaves in a very familiar way:
- The reference model
anchors the fine-tuned model, ensuring it does not drift too far from the pretrained distribution (similar to the KL penalty in RLHF) - The policy
is optimized so that preferred responses
get a higher likelihood relative to the baseline than the dispreferred ones 
- Unlike PPO-based RLHF, there is no explicit reinforcement learning loop, no learned reward model, and no need for rollouts; optimization reduces to standard gradient descent on a classification-like loss
What makes DPO particularly appealing is the set of components it deliberately omits. DPO eliminates the need for an explicit reinforcement learning loop, a separately trained reward model, and the generation of rollouts. Instead, optimization reduces to standard gradient descent on a classification-style objective defined over preference pairs. Conceptually, DPO is substantially closer to supervised fine-tuning than to policy-gradient–based reinforcement learning.
This simplification confers several practical advantages. By removing the reward model, DPO avoids the additional training overhead and the instability commonly associated with PPO-style updates. Because the objective operates directly on log-likelihood ratios, training is typically more stable and easier to diagnose. From a computational perspective, the training loop closely resembles supervised fine-tuning, with preference pairs replacing single target outputs. Despite its simplicity, DPO demonstrates strong alignment with human preferences and, across many benchmarks, matches or exceeds the performance of traditional RLHF methods.
Group Relative Policy Optimization (GRPO)
Section titled “Group Relative Policy Optimization (GRPO)”If DPO represents a simplification of RLHF by removing the explicit reinforcement learning loop, GRPO tackles a different pain point: the cost and instability of policy-gradient methods at a large scale. GRPO is a reinforcement learning method proposed in DeepSeek-V3 as a scalable alternative to Proximal Policy Optimization (PPO). It was designed to improve sample efficiency, training stability, and computational cost when fine-tuning LLMs with reinforcement signals.
Instead of computing rewards for single samples independently (as in PPO), GRPO introduces group-based normalization: responses are sampled in groups, and their rewards are normalized relative to each other. This reduces variance in gradient estimates and avoids the need for a separate learned value function (critic), which is typically required in PPO.
In standard PPO, the objective is to maximize the expected reward with a KL penalty to keep the new policy
close to the old policy
. The clipped objective is:

where

is the likelihood ratio, and
is the advantage function, usually estimated by a separate critic network.
While effective, this setup is expensive and operationally complex. PPO requires training and maintaining both a policy model and a value model, along with careful tuning of clipping thresholds, advantage estimation, normalization, and rollout collection. As model sizes grow, these costs quickly dominate training.
GRPO simplifies this picture by changing how advantages are computed. It eliminates the need for a critic by normalizing rewards within a group of responses to the same prompt.
- For each prompt
, sample a group of responses
from the current policy
. - Compute their scalar rewards
(from human feedback, automated metrics, or preference models). - Normalize these rewards within the group:

where
and
are the mean and standard deviation of rewards across the group.
- The GRPO objective is then deceptively simple:

with

This resembles policy-gradient optimization, but with group-relative advantages instead of critic-based ones.
This small shift has several important consequences:
- No value function needed: Unlike PPO, GRPO doesn’t train a critic model. Advantages are computed by normalizing rewards across sampled responses.
- Lower variance: Group normalization stabilizes updates, since the relative quality of responses is more consistent than absolute reward values.
- Scalable to LLMs: Sampling multiple responses per prompt is natural in large-batch distributed training.
- Better sample efficiency: Each prompt provides multiple useful gradient signals, not just one.
The intuition behind GRPO is simple. Instead of asking: “Is this single response good in absolute terms?”
GRPO asks: “Within this group of responses to the same prompt, which ones are better and by how much?”
This makes optimization more robust, since models often care about relative preference (choosing the best answer among candidates) rather than absolute reward magnitudes.
At this point, we have seen several complementary ways of aligning model behavior. Across PPO-based RLHF, DPO, and GRPO, the common goal is the same: when faced with many plausible continuations, the model should consistently favor the ones humans prefer. These methods differ mainly in how they trade off stability, complexity, and scalability.
Alignment alone, however, is not the full story. A model that prefers the right answers does not automatically know how to arrive at them. Many tasks, including mathematics, coding, planning, and data analysis, benefit when the model reasons through intermediate steps before producing a final response. The next section turns to this problem directly. It formalizes the notion of reasoning and shows how to train it, both when step-by-step solutions are available and when only final answers are labeled. These objectives pair naturally with the LoRA or QLoRA adapters trained earlier, or with the aligned policies produced by the methods discussed here.
Reasoning in LLMs
Section titled “Reasoning in LLMs”To study reasoning in LLM, we need a formal framework that makes explicit what the model observes, what it constructs internally as intermediate reasoning, and how this reasoning leads to a final answer. By grounding reasoning in equations and notation, we can analyze training objectives that directly supervise reasoning, indirectly encourage it, or align it through preferences.
Inputs, reasoning, and outputs
Section titled “Inputs, reasoning, and outputs”Let the input prompt or problem be denoted by
This input could be a natural language question, a conversational history, or a structured query. The role of the model is to transform this input into a reasoning process and, ultimately, an answer.
Rather than producing an answer in a single step, reasoning unfolds as a sequence of intermediate states or “tokens of thought.” We denote these by

Here,
is the length of the reasoning process, and each can represent a natural language token, a symbolic operation, or an action in a latent reasoning space.
If the model is performing chain-of-thought reasoning, each corresponds to one token in the reasoning chain. If the model is executing program-like reasoning, may instead represent function calls or logical steps.
After completing the reasoning process, the model produces a final answer:

This is the explicit response to the user’s query (e.g., “Paris” as the capital of France). While task success is usually judged by the correctness or usefulness of, the intermediate sequence provides insight into how the model arrived at that answer.
In practice, what an LLM actually emits is a single trajectory string composed of the reasoning steps followed by the final answer. We define this trajectory as:

If contains
reasoning tokens and contains
tokens of the final answer, then the total trajectory length is

The trajectory is therefore the observable sequence generated by the model.
Use case: reasoning as an explicit latent process
Section titled “Use case: reasoning as an explicit latent process”Consider a simple arithmetic reasoning task. Let the input space consist of natural-language problem descriptions, and let the input be

Rather than mapping the input directly to an answer, the model constructs an internal reasoning process represented as a sequence of intermediate reasoning tokens

For this example, the reasoning sequence may be


Here, each corresponds to a discrete step in a chain-of-thought decomposition. More generally, the elements of
may represent natural-language statements, symbolic operations, or actions in a latent reasoning space (e.g., function calls such as
).
After completing the reasoning process, the model produces a final answer

which constitutes the explicit response to the input query.
In practice, the language model emits a single observable trajectory that concatenates the reasoning sequence and the final answer. We define this trajectory as

If the reasoning process contains
reasoning tokens and the final answer consists of
token, then the total length of the emitted sequence is

This example illustrates how reasoning can be formalized as a latent variable mediating between the input
and the output. While task success is typically evaluated based on the correctness of, explicit access to provides insight into the model’s problem-solving process. Such a formulation enables the systematic study of training objectives that (i) directly supervise intermediate reasoning, (ii) encourage reasoning implicitly through likelihood-based learning, or (iii) align reasoning trajectories via preference-based methods.
Probabilistic modeling
Section titled “Probabilistic modeling”An LLM is fundamentally a probabilistic generative model. Its behavior is determined by a high-dimensional set of parameters, which we denote by

These parameters encompass all of the model’s neural weights (e.g., the matrices within attention layers, feed-forward layers, and embedding layers). Collectively, they encode the statistical knowledge acquired during pretraining.
Formally, given an input prompt
, the model defines a conditional distribution over possible output trajectories:

Here:
is a trajectory consisting of reasoning tokens and a final answer.- Each token
is drawn sequentially, conditioned on the prompt
and all preceding tokens.
The autoregressive factorization makes this explicit:

where
. This factorization underlies the model’s ability to generate coherent sequences one token at a time while still defining a valid probability distribution over complete trajectories.
In practice, especially in alignment settings, we do not optimize the model distribution
in isolation. Instead, we compare it to a reference policy
. The reference policy is typically a pretrained model before alignment or fine-tuning, such as the base LLaMA, GPT, or Falcon checkpoint. Its purpose is to serve as an anchor.
The reference policy plays several distinct roles:
- Language fluency anchor: The reference policy ensures that the model retains general language competence and does not diverge toward unnatural or incoherent outputs during alignment.
- Regularization role: Alignment objectives often involve explicit or implicit KL-divergence penalties that keep the aligned policy
close to
:

This acts as a safeguard against mode collapse, distribution drift, or over-optimization toward narrow objectives.
- Baseline for preference models: In preference-based alignment (e.g., RLHF or DPO), the reference policy provides the baseline logits that are adjusted based on human or synthetic feedback.
Latent-step factorization
Section titled “Latent-step factorization”While the autoregressive formulation describes how trajectories are generated, it does not explicitly distinguish between intermediate reasoning steps and the final answer. To model reasoning more explicitly, we introduce a latent-variable perspective.
Let
represent the sequence of intermediate reasoning tokens, and let be the final answer. Then the joint distribution can be written as:

This decomposition reflects the idea that reasoning trajectories are causal mediators between the input
and the final prediction. The model first samples a rationale conditioned on the problem, and then produces an answer conditioned on both the rationale and the input.
Training regimes
Section titled “Training regimes”Given this probabilistic formulation, reasoning can be trained under several distinct regimes, depending on what supervision signals are available. In some settings, intermediate reasoning steps are explicitly labeled, allowing the model to learn directly from human-provided rationales. In others, only final answers are observed, requiring the model to infer and marginalize over latent reasoning processes. Finally, when neither steps nor answers are fully specified, preference-based signals can be used to shape entire reasoning-and-answer trajectories. The following sections examine these regimes in turn.
Regime 1: Supervised reasoning with ground-truth steps
Section titled “Regime 1: Supervised reasoning with ground-truth steps”In many reasoning datasets, the intermediate steps are explicitly annotated. This is often referred to as chain-of-thought supervision, where annotators provide not only the correct final answer but also a detailed sequence of reasoning steps. Such data gives us direct access to the latent reasoning variables introduced in the previous section, turning them from hidden to observed quantities.
Formally, for each training example, we are given the following:
- A problem or prompt:

- A sequence of ground-truth reasoning steps:

- A ground-truth final answer:

The combined trajectory is then

Because the reasoning steps are observed, marginalization over
is no longer required. The training objective reduces to maximizing the likelihood of the observed trajectory. Recall the latent-step factorization:

When reasoning steps are unobserved, the model must marginalize over all possible rationales. This is intractable in practice. However, when reasoning steps are annotated (
), the marginal collapses to a single joint term:

The supervised objective then becomes the negative log-likelihood of the observed trajectory:

Since the LLM is autoregressive, the joint likelihood in equation (A) can be factorized token by token. Writing the trajectory string
, we have:

where
denotes all tokens before step
.
Plugging this into equation (B) yields the familiar teacher-forced likelihood:

This is the standard supervised fine-tuning (SFT) loss applied to trajectories that include explicit reasoning.
Training on annotated reasoning has several important effects:
- Lower-entropy predictions: Each reasoning token
conditions the next, making the conditional distributions narrower than predicting directly - Better generalization: The model learns reusable inference patterns, not just direct input–output mappings
- Interpretability: Because the model is trained to emit reasoning steps, its predictions provide natural explanations
In short, the model learns not only what to answer but also how to arrive at the answer.
Practical implementation
Section titled “Practical implementation”Supervised reasoning with explicit rationales is powerful but computationally intensive, since trajectories are longer than single-shot answers. In practice, the following techniques make training feasible:
- LoRA / QLoRA adapters: Instead of tuning all weights, insert low-rank adapters into key matrices (e.g.,
). Update only the adapter parameters
. With QLoRA, the base is quantized to 4-bit for further memory savings. - Gradient checkpointing: Recompute intermediate activations during backpropagation to reduce memory consumption for long rationales.
- Mixed-precision training: Training with fp16 or bf16 precision improves efficiency without compromising stability.
- Micro-batching: Split long sequences into smaller sub-batches, accumulate gradients, and update jointly.
This supervised setting illustrates the most straightforward use of the latent-step framework. When reasoning steps are latent, we must marginalize over them (Equation 1). When they are observed, we can directly condition on them, yielding the preceding simple negative log-likelihood objective. Supervised chain-of-thought training can therefore be viewed as the observed-variable special case of the general probabilistic reasoning model, anchoring the model’s internal reasoning distribution to human-provided rationales and making optimization both easier and more interpretable.
Regime 2: Supervised reasoning with answers only (latent steps)
Section titled “Regime 2: Supervised reasoning with answers only (latent steps)”Fully annotated reasoning data is rare. In most practical settings, datasets provide only final answers, while the reasoning process remains latent. This is the setting of supervised reasoning with latent steps: the reasoning variables are not observed, but we still want the model to learn a distribution over them that supports accurate prediction.
Given a prompt
and a labeled final answer
, the ideal training objective would be to maximize the log-likelihood of the answer:

Here, the sum runs over all possible reasoning trajectories. Intuitively, the model is asked to assign high probability to the correct answer regardless of which reasoning path supports it.
However, in practice, this marginalization is intractable: the space of possible rationales
is exponentially large, and summing over them directly is computationally infeasible. To address this challenge, we introduce an auxiliary inference model (sometimes called a teacher or guide), denoted by

This model proposes candidate reasoning trajectories conditioned on both the input and the correct answer. For example:
could be a stronger teacher LLM that generates rationales- It could be a self-trained sampler, producing candidate chains filtered by a verifier
- Or, it could be a program generator if the reasoning steps are executable instructions
Using the inference model, we apply variational inference. Starting from the ideal objective:

Jensen’s inequality gives us a tractable lower bound, known as the Evidence Lower Bound (ELBO):

Expanding the joint likelihood inside the expectation yields the ELBO objective:

This formulation has a clear interpretation:
- The answer likelihood term encourages the model to make use of reasoning steps to predict the correct answer

- The reasoning prior term encourages the model to favor plausible reasoning paths that are consistent with the input distribution

- The inference regularizer prevents the inference model from collapsing to degenerate solutions by regularizing its posterior distribution

Several practical designs exist for
. One option is rationale distillation, where a stronger teacher LLM generates reasoning traces that are transferred to the student model. Another approach is self-sampled rationales, in which the model proposes candidate reasoning paths that are filtered using a verifier for correctness or consistency. When reasoning steps are naturally executable, such as in mathematical derivations or code, a program generator can be used to provide structured reasoning trajectories.
When neither explicit reasoning steps nor gold answers are available, this supervised framework gives way to preference-based objectives, where training proceeds using preferences over complete reasoning-and-answer trajectories. This setting is explored in the next regime.
Practical implementation
Section titled “Practical implementation”Although the ELBO formulation makes explicit the probabilistic structure underlying reasoning, its practical realization requires a concrete data representation that can be consumed by a training pipeline. In particular, variational reasoning assumes access to triplets
, where
denotes the input prompt, denotes a candidate reasoning trajectory, and
denotes the target answer. In practice, these quantities are serialized and stored in a structured format, most commonly as JSON Lines (JSONL), with one record per training instance.
Each record encodes the input
as a text prompt, the reasoning process
as an ordered sequence of intermediate steps, and the final answer
as a text completion. A representative example is shown here.
{ “input”: “If Alice has 3 apples and buys 2 more, how many apples does she have?”, “reasoning”: [ “Alice starts with 3 apples.”, “Buying 2 more increases the total by 2.” ], “answer”: “5 apples”}This representation aligns directly with the ELBO objective. The answer likelihood term
is optimized by conditioning the generative model on the concatenation of the input and the reasoning sequence and maximizing the likelihood of the final answer. The reasoning prior term
is implemented by training the model to assign high probability to plausible reasoning trajectories given the input alone. The inference regularization term
is computed by an inference model that scores the same reasoning sequence when conditioned jointly on the input and the target answer.
Under this formulation, each serialized training example provides all components necessary to evaluate and optimize the ELBO. As a result, variational reasoning can be implemented using standard sequence-to-sequence training infrastructure, with the distinction between the generative model and the inference model realized through different conditioning contexts rather than specialized data structures. This grounding of abstract probabilistic objectives in an explicit data format closes the gap between theoretical analysis and practical implementation.
Regime 3: Preference-based reasoning objectives
Section titled “Regime 3: Preference-based reasoning objectives”In the previous sections, we studied supervised reasoning in two regimes: when reasoning steps are explicitly annotated, and when only final answers are available. However, in many practical alignment scenarios, neither explicit rationales nor even large numbers of gold answers are available. Instead, we may only have preferences between candidate trajectories.
That is, for a given prompt
, we may observe that a trajectory

is judged preferable to another trajectory

These preferences could be collected from human annotators or derived from automated heuristics (e.g., safety filters, correctness checks, or user engagement signals). Preference data tells us which reasoning-and- answer combination is better, without requiring explicit labels for the reasoning steps.
The standard framework for learning from preferences is RLHF. In this approach, a reward model
is first trained from pairwise preference data using a probabilistic ranking model, commonly the Bradley–Terry formulation:

This allows us to estimate a scalar reward for each trajectory.
The language model policy
is then optimized using Proximal Policy Optimization (PPO), with KL regularization against a reference policy
:

Here:
is the importance ratio.
is the advantage estimate.
The KL penalty ensures that the aligned model remains close to the pretrained reference, preventing reward hacking or degeneration of fluency. Overall, PPO pushes the model toward trajectories that receive higher learned reward while maintaining stability through KL control.
While PPO requires explicit reinforcement learning, DPO bypasses RL entirely. Instead, it directly optimizes the policy to respect preferences. The DPO objective takes the form:

Here, the difference between log-probabilities of preferred and rejected trajectories forms the central signal, and the reference model provides implicit KL regularization. DPO aligns the policy directly with preferences without requiring a separate reward model or explicit policy-gradient updates. Since trajectories include both reasoning and answers, DPO implicitly aligns reasoning styles (e.g., clarity, truthfulness, safety) in addition to correctness.
Another approach is GRPO, which compares multiple candidate trajectories for the same prompt.
For a given prompt
, sample trajectories 
Each trajectory’s reward is normalized relative to the group mean:

Policy updates are then performed using these group-relative advantages. By focusing on relative quality within a set of candidates for the same prompt, GRPO reduces variance and improves stability. This is particularly important for reasoning tasks, where absolute reward magnitudes may vary substantially with problem difficulty or rationale length.
Practical implementation
Section titled “Practical implementation”All preference-based objectives (PPO, DPO, and GRPO) can be implemented efficiently using LoRA/QLoRA adapters. In these setups, only the low-rank adapter matrices
are updated, while the base model remains frozen and is often quantized to 4-bit precision in the QLoRA case. This allows preference-based alignment to scale to very large language models without prohibitive memory or compute costs.
Summary
Section titled “Summary”This chapter showed how to turn a broad, pretrained language model into a reliable specialist without touching most of its billions of weights. We began with parameter-efficient fine-tuning, introducing LoRA as a low-rank update
inserted into selected linear modules so the base model stays frozen while a tiny set of adapter parameters learns the task. With the paper-standard initialization
, the update is zero at step zero, preserving the pretrained function and stabilizing optimization. QLoRA then pushed efficiency further by storing the frozen base in 4-bit quantization (e.g., NF4 with double-quantized scales) and training the same adapters in bf16/fp16; dequantization happens just-in-time for compute, so very large models can be adapted on a single modern GPU. We closed the loop operationally: where to place adapters (typically
, and optionally
and MLP), how to choose ranks and scales, and when to merge adapters into the base for lowest-latency inference versus serving them as a separate branch for flexibility.
On top of adaptation, we treated alignment as the art of shaping model behavior toward human preferences while remaining anchored to a fluent reference policy. RLHF framed alignment as reward-guided policy optimization with PPO under a KL constraint to the reference; DPO replaced explicit RL with a direct, reference-anchored preference objective; and GRPO stabilized learning by comparing candidates within the same prompt using group-relative advantages. Because each of these methods updates only adapter parameters, they pair naturally with LoRA/QLoRA, giving you practical knobs to trade data, stability, and compute.
Finally, we formalized reasoning itself. A trajectory
comprises latent steps and an answer, generated autoregressively
Viewing as a mediator yields
. When steps are annotated, supervised fine-tuning reduces to teacher-forced likelihood over
, typically lowering entropy and improving generalization. When only answers are labeled, a variational treatment introduces an inference model
and optimizes an ELBO that balances using steps to predict answers, preferring plausible steps, and regularizing the posterior. When neither steps nor gold answers are plentiful, preference learning over whole trajectories aligns both the answer and the style of reasoning.
The next chapter turns from shaping parameters and behavior to shaping context. Retrieval-Augmented Generation (RAG) equips your aligned, adapter-tuned model with fresh, verifiable evidence at inference time. We will also introduce the Model Context Protocol (MCP), a standard way for models to discover and call tools and data sources.
References
Section titled “References”- Dettmers, Tim, Artidoro Pagnoni, Ari Holtzman, and Luke Zettlemoyer. “QLoRA: Efficient Finetuning of Quantized LLMs.” In Advances in Neural Information Processing Systems 36 (NeurIPS 2023): 10088–10115, 2023.
- Hu, Edward J., Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, et al. “LoRA: Low-Rank Adaptation of Large Language Models.” In International Conference on Learning Representations (ICLR), 2022.
- Ouyang, Long, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, et al. “Training Language Models to Follow Instructions with Human Feedback.” In Advances in Neural Information Processing Systems 35 (NeurIPS 2022): 27730–27744, 2022.
- Rafailov, Rafael, Archit Sharma, Eric Mitchell, Christopher D. Manning, Stefano Ermon, and Chelsea Finn. “Direct Preference Optimization: Your Language Model Is Secretly a Reward Model.” In Advances in Neural Information Processing Systems 36 (NeurIPS 2023): 53728–53741, 2023.
- Schulman, John, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. “Proximal Policy Optimization Algorithms.” arXiv, July 2017. https://arxiv.org/abs/1707.06347.
- Shao, Zhihong, Peiyi Wang, Qi Zhu, Runxin Xu, Junxiao Song, Xuecheng Bi, et al. “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.” arXiv, February 2024. https://arxiv.org/abs/2402.03300.
- Wei, Jason, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, et al. “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.” In Advances in Neural Information Processing Systems 35 (NeurIPS 2022): 24824–24837, 2022.
- Ziegler, Daniel M., Nisan Stiennon, Jeffrey Wu, Tom B. Brown, Alec Radford, Dario Amodei, et al. “Fine-Tuning Language Models from Human Preferences.” arXiv, September 2019. https://arxiv.org/abs/1909.08593.