AI Run Lab

All chapters

Adapting an existing language model

An existing model already contains learned weights. You can train those weights further, add a small set of trainable weights, or supply new information with each question.

Open this chapter with experiments and audio

What kind of change are you trying to make?

Suppose a service team wants replies in a consistent structure and correct information about this month’s opening hours. These are separate goals. A training set of well-written replies can teach response behaviour. A current schedule in the prompt supplies the relevant facts for a particular answer. If hours change tomorrow, the document can be replaced immediately.

ApproachWhat the model seesWhat persists
Continued pretrainingMore domain text with next-token targetsUpdated weights
Supervised fine-tuningExample prompts and desired responsesUpdated weights or adapters
Retrieval in the promptRelevant excerpts with this questionExternal documents and index

How can two small matrices change a large one?

Full fine-tuning can adjust every parameter. LoRA leaves a chosen weight matrix W fixed and learns a change represented as the product of two smaller matrices. If W has shape output × input, a rank-r update uses B of shape output × r and A of shape r × input. Their product has the correct full shape. The learned values live in A and B, and a scaling factor can control their contribution.

effective weight = W + scale × (B × A)

For a 4,096 by 4,096 matrix, W contains 16,777,216 values. At rank 8, A and B together contain 65,536. The update has about 0.39% as many trainable numbers as this base matrix. That percentage is about one selected matrix. It cannot be used as a complete estimate of a model’s training memory. Activations and the frozen base still need resources.

Where do instruction and preference examples enter?

Instruction fine-tuning presents a prompt followed by a chosen response. Training commonly computes the loss on the response tokens while the prompt supplies context. Preference data instead compares candidate answers to the same prompt. RLHF can use these comparisons to fit a reward model and optimize the language model against that reward. DPO uses preference pairs directly in an objective comparing chosen and rejected responses with a reference policy.

QLoRA combines a quantized frozen base with trainable adapters. Distillation trains a student using signals produced by a teacher, such as generated answers or probability distributions. The training objective and the set of trainable parameters are separate design choices. For example, supervised instruction training can use LoRA.

How do you tell whether the change helped?

Keep test prompts separate before constructing the training set. Evaluate the original and adapted model using the same prompts, template and decoding settings. For the service assistant, score format compliance and factual accuracy separately. Also test earlier abilities that still matter. A model can improve its preferred format while giving less reliable answers on tasks missing from the fine-tuning data.

def lora_count(inputs, outputs, rank):
    return rank * (inputs + outputs)

base = 4096 ** 2
extra = lora_count(4096, 4096, 8)
print(base, extra, round(100 * extra / base, 3))
A schedule changes every day. What would you update first?

Update the retrieved schedule or use a lookup tool. Verify the answer cites the current version. Fine-tuning can help the assistant consistently use the supplied schedule when examples show that behaviour.

Source · Hu et al. · LoRA

Source · Rafailov et al. · Direct Preference Optimization

Supervised tuning marks exactly which tokens to imitate

A support team supplies a demonstration. A customer asks for their delivery date and the agent replies “Which order number?” The formatter serializes both roles into one token sequence. In a common supervised fine-tuning recipe, the user tokens remain visible as context, while only the assistant reply and its end marker contribute target losses. The mask determines which positions supply a direct teaching signal. Gradients from the answer can still flow through the processing of the user’s message.

Full fine-tuning can change all selected model weights. With LoRA, a selected weight matrix is frozen and a trainable low-rank correction is added. For a 100 × 100 matrix a rank-4 pair needs 100 × 4 + 4 × 100 = 800 trainable entries, versus 10,000 in the original matrix, ignoring biases and scaling. Restricting which parameters move and choosing the teaching signal are independent decisions. LoRA can be used with several objectives.

Change the low-rank correction and inspect the output →

Sources · Ouyang et al., 2022 · Hu et al., 2021

How a preference becomes a change in response probabilities

Two responses answer the same question. A human prefers A because it cites the relevant sentence. A reward model assigns a scalar score to each response. One training rule turns the difference A minus B into a predicted probability using a sigmoid. A gap of zero gives 50%. A gap of plus two gives about 88%. The loss is the negative log of the probability assigned to the observed preference. Increasing the gap reduces that loss for a label favoring A.

In the InstructGPT method, a separate policy step samples new answers and uses reward-model scores to update the generator with reinforcement learning. A penalty limits divergence from a reference policy. Direct Preference Optimization (DPO) instead trains the generator from preferred and rejected pairs using their log probabilities relative to a reference. A recorded human choice is evidence about that pair and the instructions given to the rater. A policy rewarded for sounding confident can learn confidence even on questions with no known answer.

Sources · Ouyang et al., 2022 · Rafailov et al., 2023

A checker changes both training and evaluation

For “What is 7 × 8?”, a generator produces candidate answers 54, 56 and 56. An exact integer checker gives rewards 0, 1 and 1. An illustrative baseline is their mean, 2/3. Subtracting it gives relative signals −2/3, +1/3 and +1/3. In a policy-gradient update, the sampled actions in above-baseline answers are encouraged. A full algorithm also decides how to normalize, clip and assign credit across many tokens.

A rule can verify an arithmetic result or run unit tests. A learned verifier can score examples where writing a complete rule is hard. Cobbe and colleagues trained verifiers to select among candidate math solutions. DeepSeek-R1 documents a training phase with verifiable rewards such as answer correctness. Training a generator against a checker, training a checker from labeled solutions, and using it only at inference are three different operations.

The answer passes, but does the explanation follow?

A final-answer checker would accept “7 × 8 = 56 because 7 + 8 = 56”. Testing the reasoning requires additional supervision or another check. Keep an independently designed evaluation set to reveal shortcuts that the training checker rewards.

Trace how a checker enters a service evaluation →

Sources · Cobbe et al., 2021 · DeepSeek-R1, 2025