Foundation Models · M.Sc. AIS @ UniTN 2026
{name.surname}@unitn.it
University of Trento
Four loose ends from the Understanding lecture, and where this lecture picks each one up.
| In the Understanding lecture | What we did not explain | Here |
|---|---|---|
| LLaVA: GPT-4 wrote 158K conversations, and training on them gave a chat assistant. | Why does copying a teacher’s answers work, and where does it stop? | SFT, distillation (Section 1) |
| Qwen2.5-VL: the last training row read “SFT, then DPO”. | What is DPO, and why does it come after SFT? | Preferences (Section 3) |
| Hallucination: CHAIR and POPE count objects that are not there. | Can training punish an invented object? | RLHF for VLMs (Section 3) |
| Grounding is scored with IoU, VQA by exact match. | If a rule can score the answer, can it also train the model? | RLVR (Section 4) |
LLaVA-Bench: “85.1% of GPT-4”, and the judge was GPT-4.
Pretraining = the Understanding lecture: vision encoders (SSL, CLIP), then connector + LLM on image–text data. Everything here comes after.
Make it follow instructions → make it cheap to adapt → make it preferred → make it reason → make it act.
A pretrained model predicts likely tokens. It does not natively answer, follow instructions, or prefer good behaviour.
“Making language models bigger does not inherently make them better at following a user’s intent.” (Ouyang et al., 2022)
Alignment shapes it along three axes:
Two levers: supervised demonstrations, then preference-based optimisation.
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS.
Supervised fine-tuning passes three tests: (1) it starts from a pretrained model; (2) the target was written by someone (a human or a teacher model) as the desired answer; (3) the model is trained to generate it (next-token loss). Which of these are SFT?
| SFT? | Why | |
|---|---|---|
| 1, 3, 6 | yes | pretrained start, target written by someone (GPT-4, annotators), generated with next-token loss |
| 4 MAE | no | self-supervised: the target is the hidden part of the input, nobody wrote it; and it is pretraining |
| 2 CLIP | no | pretraining; the caption is only matched to the image, never generated |
| 5 | no | no target, only “A beats B”: a preference (Section 3) |
Fine-tune on (image, instruction, desired response) triples, with the usual next-token loss on the response tokens only.
Limits: it needs curated targets; it can overfit and cause catastrophic forgetting; full fine-tuning is expensive (Section 2).
Liu, H. et al. (2023). Visual instruction tuning. NeurIPS.
Bai, S. et al. (2025). Qwen2.5-VL technical report. arXiv.
Same loss, three sources of targets. Most open VLMs use the last two: cheap, but capped by the teacher, or by what the model already gets right.
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS.
Liu, H. et al. (2023). Visual instruction tuning. NeurIPS.
Chen, L. et al. (2024). ShareGPT4V: improving large multi-modal models with better captions. ECCV.
Xu, G. et al. (2025). LLaVA-CoT: let vision language models reason step-by-step. ICCV.
Bai, S. et al. (2025). Qwen2.5-VL technical report. arXiv.
DeepSeek-AI (2025). DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning. arXiv.
Question: does a better-written caption help, if we change nothing else? Distil detailed captions from GPT-4V and swap them into existing training sets.
Chen, L. et al. (2024). ShareGPT4V: improving large multi-modal models with better captions. ECCV.
Before: the existing description
Written by text-only GPT-4, without seeing the image, from 5 short human COCO captions and the object boxes.
Fluent, but it can only describe what the captions mention, and it adds plausible details that may not be there (“a sunny day”).
After: the ShareGPT4V caption
Written by GPT-4V, looking at the pixels.
Colours, positions, background, text in the image, details nobody captioned: ~940 characters per image.
Same number of samples, same task, same place in training: only who wrote the description changes.
Chen, L. et al. (2024). ShareGPT4V: improving large multi-modal models with better captions. ECCV. Sec. 3–4.
Liu, H. et al. (2023). Visual instruction tuning. NeurIPS.

LLaVA-7B: MME 807 → 1030. LLaVA-1.5-13B: +22 MME, +1.3 MMBench. Small swap, consistent gains: the quality of the targets drives SFT, and caps it.
How it’s measured. MME: yes/no questions on perception and cognition, summed into one score (higher is better). MMBench: ~3K multiple-choice questions over 20 abilities, accuracy (%).
Chen, L. et al. (2024). ShareGPT4V: improving large multi-modal models with better captions. ECCV. Fig. 2.
Full fine-tuning updates billions of weights per task, and stores a full copy of the model for each one. Parameter-efficient fine-tuning (PEFT) freezes the base model and trains a tiny add-on.
Both come from the language block. Here: the projector you already met in the Understanding lecture, then LoRA and prompt tuning on vision-language models.
Small bottleneck modules inserted between frozen layers. In VLMs, the projector (LLaVA’s \(W\)) that maps image features into the LLM is itself a lightweight adapter: in LLaVA’s stage 1 it is the only thing trained.
Houlsby, N. et al. (2019). Parameter-efficient transfer learning for NLP. ICML.
Liu, H. et al. (2023). Visual instruction tuning. NeurIPS. Redrawn from Fig. 1.
Question: if the update \(\Delta W\) also has a low rank, can we train only that, and add nothing at inference?
Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR.
Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. Redrawn from Fig. 1.
Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. Sec. 4.2, 7.1.
One attention projection of a 7B LLM: \(W_0\) is 4096 × 4096. LoRA with r = 16.
How many parameters does full fine-tuning train in this matrix? How many does LoRA train?
1 minute, individually.
Full: \(4096^2 \approx\) 16.8M. LoRA: \(2 \cdot 4096 \cdot 16 =\) 131K, i.e. 0.8%.

| GPT-3 175B | trainable params | WikiSQL | MNLI-m | SAMSum (R1/R2/RL) |
|---|---|---|---|---|
| Full fine-tuning | 175,256M | 73.8 | 89.5 | 52.0 / 28.0 / 44.5 |
| LoRA | 4.7M | 73.4 | 91.7 | 53.8 / 29.8 / 45.9 |
10,000× fewer trainable parameters, 3× less GPU memory (1.2 TB → 350 GB), checkpoint 350 GB → 35 MB. Even \(r = 1\) is close to \(r = 8\).
How it’s measured. WikiSQL: question → SQL query, accuracy. MNLI-m: does sentence A entail, contradict or not concern sentence B? Accuracy. SAMSum: summarise a chat; ROUGE-1/2/L = overlap of words, word pairs, and longest common word sequence with a human summary.
Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. Fig. 2, Table 4.
import torch
from PIL import Image
from peft import LoraConfig, get_peft_model
from transformers import CLIPModel, CLIPProcessor
name = "openai/clip-vit-base-patch32" # the same CLIP as the zero-shot demo
model, proc = CLIPModel.from_pretrained(name), CLIPProcessor.from_pretrained(name)
labels = ["cat", "dog", "car"]
inputs = proc(text=[f"a photo of a {l}" for l in labels],
images=Image.open("pet.jpg"), return_tensors="pt", padding=True)
before = model(**inputs).logits_per_image.softmax(dim=-1) # zero-shot prediction, plain CLIP
# add a B·A branch (rank r = 16, scale alpha/r = 2) next to W_q and W_v of every attention layer;
# everything else is frozen
lora = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "v_proj"]))
lora.print_trainable_parameters() # only the A and B matrices count as trainable
after = lora(**inputs).logits_per_image.softmax(dim=-1) # same input, through the LoRA model
print("same output at init:", torch.allclose(before, after)) # B = 0 at init, so BA = 0Question: instead of writing the prompt, can we learn it from a few labelled images, keeping CLIP frozen?
Zhou, K. et al. (2022). Learning to prompt for vision-language models. IJCV. Fig. 1.
Zhou, K. et al. (2022). Learning to prompt for vision-language models. IJCV.

The catch: train on half of the classes, test on the other half.
| 11-dataset avg. | base | new |
|---|---|---|
| CLIP (hand-written) | 69.3 | 74.2 |
| CoOp | 82.7 | 63.2 |
The learned prompt overfits the training classes: on unseen classes it is 11 points worse than the hand-written one.
Zhou, K. et al. (2022). Learning to prompt for vision-language models. IJCV. Fig. 4.
Zhou, K. et al. (2022). Conditional prompt learning for vision-language models (CoCoOp). CVPR. Table 1.
No labels, no training set: adapt the prompt to each test image, then throw it away.
Shu, M. et al. (2022). Test-time prompt tuning for zero-shot generalization in vision-language models. NeurIPS.
| CLIP ViT-B/16, top-1 | ImageNet | -A | -V2 | -R | -Sketch | OOD avg. |
|---|---|---|---|---|---|---|
| CLIP (hand-written prompt) | 66.7 | 47.9 | 60.9 | 74.0 | 46.1 | 57.2 |
| CoOp (16 shots of ImageNet) | 59.3 | |||||
| TPT (zero shots) | 69.0 | 54.8 | 63.5 | 77.1 | 47.9 | 60.8 |
How it’s measured. Top-1 accuracy on ImageNet and four shifted versions: -V2 (new photos, same classes), -Sketch (drawings), -A (photos that fool ResNets), -R (art, cartoons, toys). OOD avg. = mean over the four.
Shu, M. et al. (2022). Test-time prompt tuning for zero-shot generalization in vision-language models. NeurIPS. Tables 1, 4.
SFT imitates demonstrations. But often we cannot write the right answer; we can only say which of two answers is better.
From “copy this answer” to “produce answers people prefer”.
Question: can a small amount of human feedback (demonstrations and rankings from 40 labelers) turn GPT-3 into a model people actually prefer?
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS.
InstructGPT: ~13K demonstrations (step 1), 33K ranked prompts with \(K = 4\) to \(9\) answers each (step 2), 31K unlabelled prompts for PPO (step 3).
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. Redrawn from Fig. 2.
\[ \mathcal{L}_{RM} = -\,\mathbb{E}_{(x,\,y^+,\,y^-)}\ \log \sigma\big(r_\phi(x, y^+) - r_\phi(x, y^-)\big) \]
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. Eq. 1.
\[ \max_{\pi_\theta}\ \mathbb{E}_{x,\ y\sim\pi_\theta}\Big[\, r_\phi(x,y)\ -\ \beta \log\frac{\pi_\theta(y|x)}{\pi_{ref}(y|x)} \Big] \]
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. Eq. 2.
Maximise reward without moving too far from the policy that collected the data:
\[ L^{CLIP}(\theta) = \mathbb{E}_t\Big[\min\big(\rho_t(\theta)\hat A_t,\ \text{clip}(\rho_t(\theta),1-\epsilon,1+\epsilon)\hat A_t\big)\Big],\qquad \rho_t = \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{old}}(a_t|s_t)} \]
Schulman, J. et al. (2017). Proximal policy optimization algorithms. arXiv.
Reward model: the judge
Trained before PPO (step 2, human rankings), then frozen.
Reads the finished answer → one score: how good is it?
Value model: the forecaster
Trained during PPO, next to the policy.
Reads the answer so far → what score should I expect from here?
One PPO iteration:
After training both are thrown away: only the policy is deployed.
Prompt \(q\): “What is 12 × 7?” Reward: 1 if the answer is 84, else 0. The value model predicts \(V(q) = 0.6\): “from here, the policy gets it right 60% of the time”.
| sample | answer | reward \(R\) | advantage \(\hat A = R - V\) | \(\pi_{old}\) | \(\pi_\theta\) | ratio \(\rho\) | \(\rho \hat A\) | \(\text{clip}(\rho)\,\hat A\) | \(\min\) |
|---|---|---|---|---|---|---|---|---|---|
| a | “84” | 1 | +0.4 | 0.50 | 0.65 | 1.3 | 0.52 | 0.48 | 0.48, clipped: no gradient |
| b | “19” | 0 | −0.6 | 0.20 | 0.18 | 0.9 | −0.54 | −0.54 | −0.54, gradient flows |
a · “84”, correct
\(\hat A = 1 - 0.6 = +0.4\) (better than expected)
\(\rho = 0.65 / 0.50 = 1.3\)
\(\min(1.3 \times 0.4,\ 1.2 \times 0.4) = \min(0.52, 0.48) = \mathbf{0.48}\)
Clipped: already +30%, no more push in this batch.
b · “19”, wrong
\(\hat A = 0 - 0.6 = -0.6\) (worse than expected)
\(\rho = 0.18 / 0.20 = 0.9\), inside \([0.8, 1.2]\)
\(\min(0.9 \times (-0.6),\ 0.9 \times (-0.6)) = \mathbf{-0.54}\)
Not clipped: the gradient keeps pushing “19” down.
Schulman, J. et al. (2017). Proximal policy optimization algorithms. arXiv.

Alignment is cheap compared to pretraining, and worth more than scale.
Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. Fig. 1.

“Describe the image.”
(A) A brown-and-white spaniel runs across a sand dune toward the camera. A person in a blue jacket sits in the background.
(B) What a joyful moment! A Cavalier King Charles spaniel bounds along the beach, ears flying, chasing the red ball its owner just threw toward the waves. Behind it, a woman in a turquoise jacket relaxes on her beach towel, smiling at her playful companion.
Vote: which answer is better?
B: three invented details. A reward model trained on “B wins” learns: longer and more vivid = better. The policy will learn to give it exactly that.
What you just did as voters, a reward model does at scale: it rewards what looks good. RL then pushes the policy to produce exactly that.
Goodhart’s law: when a measure becomes a target, it ceases to be a good measure.
We will meet it again:

Photo: Jamesfranklingresham, Wikimedia Commons, CC BY-SA 3.0 (2012 Long Finance conference).
| 7B policy | LLaVA-Bench ↑ | MMHal ↑ |
|---|---|---|
| LLaVA (SFT only) | 81.0 | 1.55 |
| naive RLHF | 93.4 | 1.8 |
| Fact-RLHF | 94.1 | 2.1 |
RLHF rows: ablation with a 13B reward model.
LLaVA-Bench (helpfulness): GPT-4 rates the answer against GPT-4’s own reference answer; score in % of GPT-4.
MMHal (hallucination, 0–6): 96 trick questions on which LLaVA hallucinates; GPT-4 grades each answer against a human reference. Higher = fewer invented facts.
A reward model that can’t check the image rewards what sounds right. Give it an answer key, and it rewards what is right.
Sun, Z. et al. (2023). Aligning large multimodal models with factually augmented RLHF. arXiv. Tables 3, 5, 6.
Question: if we know the shape of the optimal policy, can we skip the reward model and the RL loop, and fit the policy to the preferences directly?
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS.
Invert the optimum: \(\ r(x,y) = \beta \log \frac{\pi^*(y|x)}{\pi_{ref}(y|x)} + \text{const}(x)\). Put it in the Bradley–Terry loss; the constant cancels in \(r^+ - r^-\):
\[ \mathcal{L}_{DPO} = -\,\mathbb{E}\ \log\sigma\Big(\beta \log\tfrac{\pi_\theta(y^+|x)}{\pi_{ref}(y^+|x)} - \beta \log\tfrac{\pi_\theta(y^-|x)}{\pi_{ref}(y^-|x)}\Big) \]
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS. Eq. 7.
\(\pi(y|x)\) = the probability that the model writes exactly the answer \(y\) after the prompt \(x\): the product of its next-token probabilities.
Prompt \(x\): “What is 12 × 7?” Preferred \(y^+\): “84” Rejected \(y^-\): “19”
| answer | tokens | \(\pi_{ref}\): frozen SFT model | \(\pi_\theta\): being trained |
|---|---|---|---|
| \(y^+\) “84” | “8”, “4” | \(p(8) \cdot p(4 \mid 8) = 0.40 \times 0.25 = \mathbf{0.10}\) | \(0.50 \times 0.30 = \mathbf{0.15}\) |
| \(y^-\) “19” | “1”, “9” | \(p(1) \cdot p(9 \mid 1) = 0.50 \times 0.40 = \mathbf{0.20}\) | \(0.40 \times 0.25 = \mathbf{0.10}\) |
Two copies of the same SFT model
\(\pi_{ref}\) is frozen: what the model did before DPO.
\(\pi_\theta\) starts identical and is trained.
What happened here
The reference preferred the wrong answer (0.20 vs 0.10).
A few steps of training have already started to flip that (0.15 vs 0.10).
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS.
Implicit reward = how much the policy moved away from the reference on that answer: \(\ \hat r = \beta \log \dfrac{\pi_\theta}{\pi_{ref}}\), here with \(\beta = 1\).
\(y^+\) · “84”, preferred
ratio \(= 0.15 / 0.10 = 1.5\)
\(\hat r^+ = \log 1.5 = \mathbf{+0.405}\)
The policy already likes it more than the reference does.
\(y^-\) · “19”, rejected
ratio \(= 0.10 / 0.20 = 0.5\)
\(\hat r^- = \log 0.5 = \mathbf{-0.693}\)
The policy already likes it less than the reference does.
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS.
\[ \mathcal{L}_{DPO} = -\log \sigma\big(\hat r^+ - \hat r^-\big), \qquad \hat r^+ = +0.405,\ \ \hat r^- = -0.693 \]
The loss
\(\hat r^+ - \hat r^- = 0.405 - (-0.693) = 1.099\)
\(\sigma(1.099) = 0.75\): the implicit reward already prefers \(y^+\), with 75%.
\(\mathcal{L} = -\log 0.75 = \mathbf{0.288}\): small, but not zero.
The push
Gradient weight \(= \sigma(-1.099) = 1 - 0.75 = \mathbf{0.25}\): the probability still given to the wrong order.
Raise \(\log \pi_\theta(y^+)\), lower \(\log \pi_\theta(y^-)\), scaled by \(\beta \times 0.25\).
At the start (\(\pi_\theta = \pi_{ref}\)): difference 0, loss 0.693, weight 0.5.
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS. Sec. 4.


How it’s measured. IMDb: write positive movie reviews; reward = a sentiment classifier’s score, plotted against KL from the reference. TL;DR: summarise Reddit posts; win rate = % of summaries GPT-4 prefers over the human-written one.
Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS. Fig. 2, Table 2.
Same DPO loss, aimed at hallucination. Two changes to standard DPO:
1 · The pairs: correct, don’t rank
Standard: a person ranks two long answers, each with its own errors.
RLHF-V: the model answers, a person rewrites only the hallucinated words. Original = \(y^-\), corrected = \(y^+\): the pair differs only where the model was wrong.
2 · The loss: dense DPO
Standard: every token of the answer counts the same.
RLHF-V: the corrected words get a larger weight (\(\gamma = 5\) in the paper), so the push lands on the hallucination and its fix; the text both answers share keeps weight 1.
Two phases: ① collected once, by people: 1.4K corrected answers → ② then offline DPO, no human: under 1 hour on 8 A100s.
Result: descriptions with an invented object: 50.5% → 12.2% (GPT-4V: 13.6%). 200 corrections ≈ 2.2K rankings.
How it’s measured. Object HalBench: 300 COCO images, “describe this image in detail”; the objects each description mentions are checked against COCO’s labels; % of descriptions with at least one invented object.
Yu, T. et al. (2024). RLHF-V: towards trustworthy MLLMs via behavior alignment from fine-grained correctional human feedback. CVPR. Table 1, Fig. 2.
TRL (Hugging Face’s Transformer Reinforcement Learning library) has one trainer per method of this lecture: SFTTrainer, RewardTrainer, DPOTrainer, PPOTrainer, GRPOTrainer. Same recipe for all: a model, a dataset in the method’s format, a config, then trainer.train(). Built on transformers and peft.
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForImageTextToText, AutoProcessor
from trl import DPOConfig, DPOTrainer
name = "Qwen/Qwen2.5-VL-3B-Instruct"
model = AutoModelForImageTextToText.from_pretrained(name, dtype="auto")
processor = AutoProcessor.from_pretrained(name)
# {images, prompt, chosen, rejected}: preferences on image descriptions (RLAIF-V)
ds = load_dataset("HuggingFaceH4/rlaif-v_formatted", split="train[:2%]")
trainer = DPOTrainer(
model=model, # no ref_model: with LoRA, the frozen base is the reference
args=DPOConfig(output_dir="dpo-vlm", beta=0.1, per_device_train_batch_size=2),
train_dataset=ds,
processing_class=processor,
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
)
trainer.train()For some tasks we do not need a learned reward model: a rule can check the answer.
\[ v(x, y) = \begin{cases} \alpha & \text{if } y \text{ is verifiably correct} \\ 0 & \text{otherwise} \end{cases} \qquad \max_{\pi_\theta}\ \mathbb{E}\big[v(x,y)\big] - \beta\,\text{KL}(\pi_\theta \,\|\, \pi_{ref}) \]
Lambert, N. et al. (2024). Tülu 3: pushing frontiers in open language model post-training. arXiv. Sec. 6.
\[ \hat A_i = \frac{r_i - \text{mean}(r_1,\dots,r_G)}{\text{std}(r_1,\dots,r_G)} \quad\text{for every token of answer } o_i \]
Shao, Z. et al. (2024). DeepSeekMath: pushing the limits of mathematical reasoning in open language models. arXiv. Redrawn from Fig. 4.
Prompt \(q\): “What is 12 × 7?” Verifier: reward 1 if the answer is 84, else 0. Group \(G = 3\).
| \(i\) | sampled answer \(o_i\) | reward \(r_i\) | advantage \(\hat A_i = (r_i - \mu)/\sigma\) |
|---|---|---|---|
| 1 | “84” | 1 | +0.71 |
| 2 | “80 + 28 = 108” | 0 | −1.41 |
| 3 | “12 × 7 = 84” | 1 | +0.71 |
Group statistics
\(\mu = (1 + 0 + 1) / 3 = 0.67\)
\(\sigma = \sqrt{\big[(1-0.67)^2 + (0-0.67)^2 + (1-0.67)^2\big] / 3} = 0.47\)
The baseline is the group itself: no value model.
Advantages
answers 1, 3: \((1 - 0.67) / 0.47 = \mathbf{+0.71}\)
answer 2: \((0 - 0.67) / 0.47 = \mathbf{-1.41}\)
The wrong answer is the exception, so it gets the larger push.
Shao, Z. et al. (2024). DeepSeekMath: pushing the limits of mathematical reasoning in open language models. arXiv.
One update step later, the policy has changed. Clip with \(\epsilon = 0.2\), i.e. ratios in \([0.8, 1.2]\):
| \(i\) | \(\pi_{old}\) | \(\pi_\theta\) | ratio \(\rho_i\) | \(\hat A_i\) | \(\rho_i \hat A_i\) | \(\text{clip}(\rho_i)\,\hat A_i\) | \(\min\) (what is optimised) |
|---|---|---|---|---|---|---|---|
| 1 | 0.10 | 0.11 | 1.1 | +0.71 | 0.78 | 0.78 | 0.78, gradient flows |
| 2 | 0.30 | 0.27 | 0.9 | −1.41 | −1.27 | −1.27 | −1.27, gradient flows |
| 3 | 0.05 | 0.07 | 1.4 | +0.71 | 0.99 | 0.85 | 0.85, clipped: no gradient |
1 · “84”
\(\rho = 0.11 / 0.10 = 1.1\), inside \([0.8, 1.2]\)
\(\min(1.1 \times 0.71,\ 1.1 \times 0.71) = \mathbf{0.78}\)
Not clipped: keep pushing up.
2 · “108”, wrong
\(\rho = 0.27 / 0.30 = 0.9\), inside \([0.8, 1.2]\)
\(\min(0.9 \times (-1.41),\ 0.9 \times (-1.41)) = \mathbf{-1.27}\)
Not clipped: keep pushing down.
3 · “12 × 7 = 84”
\(\rho = 0.07 / 0.05 = 1.4 \to\) clipped to 1.2
\(\min(1.4 \times 0.71,\ 1.2 \times 0.71) = \min(0.99, 0.85) = \mathbf{0.85}\)
Clipped: already +40%, no more push.
Shao, Z. et al. (2024). DeepSeekMath: pushing the limits of mathematical reasoning in open language models. arXiv. Eq. 3.
Schulman, J. et al. (2017). Proximal policy optimization algorithms. arXiv.
| PPO | GRPO | DPO | |
|---|---|---|---|
| Signal | scalar reward | reward, normalised in the group | pairwise preference |
| Value model | yes | no | no |
| Sampling during training | yes (online) | yes (online) | no (offline) |
| Reward model | yes | yes, or a verifier | not needed |
| Typical use | RLHF (InstructGPT) | reasoning with RLVR (R1) | preference alignment (Qwen2.5-VL) |
Online sampling matters for reasoning: the model must explore answers nobody wrote down.
The whole prompt: “…The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags…”. Reward = accuracy (a rule) + format. No neural reward model: it “may suffer from reward hacking”.
Question: can reasoning emerge from pure RL, with no SFT at all? Start from a base model, reward only the final answer (and the format), and let the model find its own way.
DeepSeek-AI (2025). DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning. arXiv. Table 1.


How it’s measured. AIME 2024: 30 competition math problems with integer answers. pass@1: accuracy of a single sampled answer (averaged over samples). Majority voting over 16 (cons@16): sample 16 answers, keep the most frequent.
DeepSeek-AI (2025). DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning. arXiv (v2). Fig. 1.
RL finds the reasoning; SFT makes it readable. Rejection sampling (Section 1) links the two.
DeepSeek-AI (2025). DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning. arXiv. Sec. 2.3.

Sample K answers per question. Score = % of questions solved.
Pass@K: solved if any of the K is right. Can the model reach the answer?
Maj@K: solved if the most frequent answer is right. Does it reliably give it?
K = 8 samples for “What is 12 × 7?”
Before RL: 3 × “84”, 4 × “108”, 1 × “19” → Pass@8 ✓, Maj@8 ✗
After RL: 6 × “84”, 2 × “108” → Pass@8 ✓, Maj@8 ✓
Maj@K went up, Pass@K could not: the right answer was already there.
After RL, Maj@K improves and Pass@K does not: RL makes answers the model could already produce more likely.
Shao, Z. et al. (2024). DeepSeekMath: pushing the limits of mathematical reasoning in open language models. arXiv. Fig. 7.
So far every verifier checked a short text answer (“2”, “84”). Visual-RFT (Visual Reinforcement Fine-Tuning) lets the model answer with boxes, and scores where it looked: a geometric reward, the IoU from the Understanding lecture.
GRPO on Qwen2-VL-2B, a few labelled examples per class:
| base | SFT | RFT | |
|---|---|---|---|
| 1-shot classification | 56.0 | 51.7 | 80.3 |
| COCO 2-shot detection (mAP) | 19.6 | 21.0 | 41.5 |
mAP: a box counts if its IoU with the true box is high enough; averaged over classes.
With a handful of labels, scoring attempts beats copying the answer: SFT even makes classification worse.
Liu, Z. et al. (2025). Visual-RFT: visual reinforcement fine-tuning. arXiv. Sec. 3.2, Tables 2–3.
Not when we have big data, but when checking an answer is easier than writing the right one.
| What you have | Use | Seen in |
|---|---|---|
| Demonstrations: the answer you want, written out | SFT | LLaVA, ShareGPT4V |
| Only comparisons: “A is better than B” | Preferences: DPO (offline), RLHF (online) | InstructGPT, RLHF-V |
| A rule that checks the final answer | RLVR: GRPO or PPO with a verifier | DeepSeek-R1, Visual-RFT |
Why RL, beyond SFT
No single right answer, only better and worse ones.
Go beyond the teacher: explore and keep what scores well (R1-Zero, no human reasoning).
The goal is a whole outcome (correct, task done, nothing invented), judged once at the end.
What RL needs instead of big data
Few labels: one example per class (Visual-RFT), 1.4K corrections (RLHF-V).
A model that sometimes succeeds: all-zero rewards give no gradient, so SFT comes first.
A judge that can’t be gamed, and compute to sample many answers.
Real systems stack these stages. Qwen2.5-VL, from the Understanding lecture:

Early 2025: SFT + DPO. By mid-2025, open recipes add a large RL stage.
Bai, S. et al. (2025). Qwen2.5-VL technical report. arXiv.
Pretrain → long chain-of-thought SFT (format only: <think>…</think><answer>…</answer>) → RL on many domains at once, one verifier per domain:
| Domain | Verifier |
|---|---|
| Math, physics | symbolic match (sympy), tolerance |
| OCR | 1 − normalised edit distance |
| Grounding | share of boxes with IoU above a threshold |
| GUI agent | right action + IoU of the click |
| Long docs, open VQA | LLM judge |

Training on all domains helps every one; grounding alone gives +30 on grounding but −4.6 on OCR & charts.
GLM-V Team (2025). GLM-4.5V and GLM-4.1V-Thinking: towards versatile multimodal reasoning with scalable reinforcement learning. arXiv. Table 1, Fig. 6.

GLM-V Team (2025). GLM-4.5V and GLM-4.1V-Thinking: towards versatile multimodal reasoning with scalable reinforcement learning. arXiv. Fig. 5, Sec. 5.2.
Reasoning: decompose a hard question into intermediate steps before answering (counting, spatial logic, math-in-images).
Acting: call external tools (detector, OCR, calculator, code, a browser) and use their results.
Direct-response VLMs answer in one shot, and stumble on both.
| GSM8K | direct | CoT |
|---|---|---|
| PaLM 8B | 4.9 | 4.1 |
| PaLM 62B | 9.6 | 29.9 |
| PaLM 540B | 17.9 | 56.9 |
CoT only helps at scale (~100B): small models write “fluent but illogical chains of thought” and do worse.
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls.
How many tennis balls does he have now?
A: Roger started with 5 balls. 2 cans of 3 tennis balls each is 6 tennis balls. 5 + 6 = 11.
The answer is 11. <- one of ~8 worked examples
Q: <new question>
A: <- the model writes the reasoning, then the answerHow it’s measured. GSM8K: 8.5K grade-school math word problems; accuracy = exact match on the final number.
Wei, J. et al. (2022). Chain-of-thought prompting elicits reasoning in large language models. NeurIPS. Table 2.
Same prompt as CoT. One change: don’t trust one chain of thought, sample many and let the answers vote.
What changes vs CoT
Prompt: the same ~8 worked examples.
Decoding: sample with temperature instead of greedy (always the most likely token), so each run takes a different reasoning path.
Answer: read “The answer is …” in each path, take the majority.
No training, no verifier.
The paper’s example (Janet’s ducks)
Greedy CoT: one path → $14 ✗
Sampled paths → $18, $26, $18
Vote → $18 ✓
Wrong paths scatter over different wrong answers; right paths agree.
PaLM 540B, GSM8K: one greedy chain 56.5 → vote over 40 paths 74.4. The first form of test-time compute: more inference, better answer.
Wang, X. et al. (2023). Self-consistency improves chain of thought reasoning in language models. ICLR. Fig. 1, Table 2.
Self-consistency votes on the majority answer, every time. Instead of deciding on the majority, can we make it a reward, and train the model on it?
5 samples for one test image, no label
3 × “cat”, 1 × “dog”, 1 × “fox”
Frequency reward: cat \(3/5 = \mathbf{0.6}\), dog and fox \(1/5 = \mathbf{0.2}\)
GRPO advantages (mean 0.44, std 0.20)
cat: \((0.6 - 0.44)/0.20 = \mathbf{+0.82}\)
dog, fox: \((0.2 - 0.44)/0.20 = \mathbf{-1.22}\)
The model is pushed towards its own majority answer.
Singh, A. et al. (2026). TTRV: test-time reinforcement learning for vision language models. CVPR. Eq. 3–7.
| InternVL3-8B | before | after TTRV | GPT-4o |
|---|---|---|---|
| Recognition, 8 datasets (4-way multiple choice) | 66.7 | 95.7 | 93.4 |
| VQA, mean | 38.1 | 55.6 | 72.0 |
Only 20 unlabelled test samples per dataset. The authors argue it recovers abilities from pretraining rather than learning new ones; and it can hurt (Resisc45: 23.4 → 13.3 for InternVL2.5-4B).
How it’s measured. Recognition: image classification turned into 4-way multiple choice, accuracy averaged over 8 datasets. VQA: mean accuracy over several VQA benchmarks.
Singh, A. et al. (2026). TTRV: test-time reinforcement learning for vision language models. CVPR. Tables 1, 2.
Question: can we train a VLM to reason in fixed stages, first looking and then concluding, using SFT alone?
Xu, G. et al. (2025). LLaVA-CoT: let vision language models reason step-by-step. ICCV.
Four tagged stages, in one pass:
<SUMMARY> the task<CAPTION> the relevant parts of the image<REASONING> step by step<CONCLUSION> the answerData: 99K VQA samples, stage-by-stage answers written by GPT-4o (distillation again). Full SFT (all weights, no LoRA) of Llama-3.2-11B-Vision.

Xu, G. et al. (2025). LLaVA-CoT: let vision language models reason step-by-step. ICCV. Fig. 2.
| 6-benchmark avg. | |
|---|---|
| Llama-3.2-11B-Vision (base) | 56.6 |
| SFT on the original Q&A | 59.0 |
| SFT on the 100K, tags removed | 60.9 |
| LLaVA-CoT | 62.4 |
| + stage-wise search at test time | 65.5 |

How it’s measured. 6-benchmark avg.: mean score on MMStar, MMBench, MM-Vet, MathVista, AI2D, HallusionBench (general, math, diagram and hallucination questions).
Xu, G. et al. (2025). LLaVA-CoT: let vision language models reason step-by-step. ICCV. Tables 2, 4; Fig. 4.
Question: can an open VLM learn when and where to zoom, with RL alone and no zoom demonstrations?
Zheng, Z. et al. (2026). DeepEyes: incentivizing “thinking with images” via reinforcement learning. ICLR.
Zheng, Z. et al. (2026). DeepEyes: incentivizing “thinking with images” via reinforcement learning. ICLR. Eq. 2.

| V* (find small details) | |
|---|---|
| GPT-4o | 66.0 |
| Qwen2.5-VL-7B (base) | 71.2 |
| Qwen2.5-VL-32B | 87.9 |
| DeepEyes-7B | 90.1 |
| o3 | 95.7 |
How it’s measured. V*: questions about small objects in high-resolution images (attribute, relative position), accuracy. HR-Bench 4K / 8K: the same idea on 4K and 8K images.
Zheng, Z. et al. (2026). DeepEyes: incentivizing “thinking with images” via reinforcement learning. ICLR. Fig. 1(a), Table 1.
Wrap one tool (say, an object detector) around the model:
question → detect objects → answer from the list
Works for one fixed skill, but cannot compose tools or decide which to call. We need structure.
A frozen LLM, prompted with 1–2 example trajectories. A thought is an action that changes nothing outside: it only updates the context. ALFWorld success 71% (acting only: 45%); hallucination as failure mode on HotpotQA: 0% (CoT: 56%).
How it’s measured. ALFWorld: text-based household game (“put a clean mug in the coffee machine”), success = task completed. HotpotQA: questions that need two Wikipedia pages; hallucination % = share of failed runs caused by invented facts, judged by hand.
Yao, S. et al. (2023). ReAct: synergizing reasoning and acting in language models. ICLR. Tables 2, 3.
Question: can an LLM, shown a handful of examples, write a program that calls off-the-shelf vision models, and solve compositional tasks without any training?
Gupta, T. & Kembhavi, A. (2023). Visual programming: compositional visual reasoning without training. CVPR.
Gupta, T. & Kembhavi, A. (2023). Visual programming: compositional visual reasoning without training. CVPR. The example program is ours, in the paper’s syntax.
Red: neural models (OWL-ViT, CLIP, Stable Diffusion, GPT-3 …). Blue: Python and image-processing routines.
Gupta, T. & Kembhavi, A. (2023). Visual programming: compositional visual reasoning without training. CVPR. Fig. 2.

| Zero-shot, no training | GQA | NLVRv2 | Image editing |
|---|---|---|---|
| ViLT (VQA-trained) | 47.8 | ||
| VISPROG (5 programs, voted) | 50.5 | 62.4 | 59.8 → 66.4 after rephrasing |
How it’s measured. GQA: compositional questions on images, accuracy. NLVRv2: true/false statements about a pair of images, accuracy. Image editing: % of edits judged correct by hand.
Gupta, T. & Kembhavi, A. (2023). Visual programming: compositional visual reasoning without training. CVPR. Tables 1, 2, 4.
Modules: FACEDET(image) · LIST(query, max) · CLASSIFY(image, object, categories) · TAG(image, object) · EMOJI(image, object, emoji) · RESULT(var)
Write the program, one call per line. 3 minutes, in pairs. No photo: GPT-3 never sees the image either. The program must work on any photo; the modules look at it when it runs.
OBJ0 = FACEDET(image=IMAGE)
IMAGE0 = EMOJI(image=IMAGE, object=OBJ0, emoji=‘sunglasses’)
FINAL = RESULT(var=IMAGE0)
OBJ0 = FACEDET(image=IMAGE)
LIST0 = LIST(query=‘members of the Beatles’, max=4)
OBJ1 = CLASSIFY(image=IMAGE, object=OBJ0, categories=LIST0)
IMAGE0 = TAG(image=IMAGE, object=OBJ1)
FINAL = RESULT(var=IMAGE0)

| zero-shot | RefCOCO | GQA | OK-VQA |
|---|---|---|---|
| best end-to-end | 58.6 | 44.7 | 50.6 |
| ViperGPT | 72.0 | 48.1 | 51.9 |
How it’s measured. RefCOCO: find the object a phrase refers to (“pizza front”); score = overlap (IoU) with the true box. GQA: compositional VQA. OK-VQA: questions that need outside knowledge. Accuracy.
Surís, D., Menon, S. & Vondrick, C. (2023). ViperGPT: visual inference via Python execution for reasoning. ICCV. Fig. 5, Tables 1–3.
Question: can a VLM operate a computer from pixels only, the way people do?
| Mind2Web step success | input | overall |
|---|---|---|
| GPT-4, few-shot | HTML | 30.9 |
| LLaMA2-70B, fine-tuned | HTML | 54.4 |
| CogAgent 18B | screenshot | 58.2 |
How it’s measured. Mind2Web step success: on real websites, % of steps where the agent picks the right element and the right action (click, type, select).
Hong, W. et al. (2024). CogAgent: a visual language model for GUI agents. CVPR. Table 3.

| OSWorld (screenshot only) | 15 steps | 50 steps |
|---|---|---|
| GPT-4o | 5.0 | |
| Claude Computer Use | 14.9 | 22.0 |
| UI-TARS-72B-DPO | 22.7 | 24.6 |
How it’s measured. OSWorld: 369 real computer tasks in virtual machines, each checked by a script on the final state (Section 7). 15 / 50 steps: the step budget per task.
Qin, Y. et al. (2025). UI-TARS: pioneering automated GUI interaction with native agents. arXiv. Fig. 4, Table 9.
import base64, io, json, os
from PIL import Image
from openai import OpenAI
client = OpenAI(base_url=os.environ.get("VLLM_BASE_URL", "http://LAB-HOST:8000/v1"),
api_key=os.environ.get("VLLM_API_KEY", "EMPTY"))
MODEL = "Qwen/Qwen2.5-VL-7B-Instruct"
def as_part(im):
buf = io.BytesIO(); im.convert("RGB").save(buf, "JPEG")
return {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()}}
image = Image.open("scene.jpg")
msgs = [{"role": "system", "content": 'Think step by step. To look closer, reply only with JSON {"crop": [x1, y1, x2, y2]} '
'in pixel coordinates. When sure, reply "ANSWER: ..."'},
{"role": "user", "content": [as_part(image), {"type": "text", "text": "What time does the clock show?"}]}]
for step in range(4): # a bounded ReAct loop
out = client.chat.completions.create(model=MODEL, messages=msgs, max_tokens=300).choices[0].message.content
msgs.append({"role": "assistant", "content": out})
if out.strip().startswith("{"): # action: crop, observation: the crop
crop = image.crop(json.loads(out)["crop"])
msgs.append({"role": "user", "content": [as_part(crop), {"type": "text", "text": "Here is the crop."}]})
else:
print(out); breakA GUI agent sees a screenshot and outputs click and type.
Replace the screenshot with camera frames and the clicks with motor commands, and the same VLM recipe controls a robot.
Vision-language-action (VLA) models: later in the course.
| What | Metric: what it measures | Typical benchmarks | |
|---|---|---|---|
| Broad understanding | accuracy on multiple choice | MMMU, MMBench, MMStar | ✓ seen, Understanding |
| Hallucination | invented objects | CHAIR, POPE | ✓ seen, Understanding |
| Alignment | win rate vs a reference, judged by humans or an LLM | MT-Bench, LLaVA-Bench, MMHal | → coming up |
| Reward model | preference accuracy: is \(y^+\) scored above \(y^-\)? | held-out preference pairs | |
| Reasoning | accuracy, pass@1, maj@K | MathVista, MMMU-Pro, MathVision | |
| Agents | task success rate checked on the final state | OSWorld, WebArena, AndroidWorld | → coming up |
GPT-4 as judge agrees with human experts 85% of the time on pairwise comparisons: humans agree with each other 81%. Good enough to use, with known biases:
| Bias | Test | Result |
|---|---|---|
| Position | swap the two answers | GPT-4 is consistent 65% of the time; Claude-v1 24% (favours the first) |
| Verbosity | repeat a list in new words, no new content | Claude-v1 and GPT-3.5 fooled 91%; GPT-4 9% |
| Self-preference | judge its own answers | GPT-4 ~10% higher win rate for itself (not conclusive) |
| Math | grade a wrong solution | fails 14/20; 3/20 if given the reference answer |
How it’s measured. Agreement: % of answer pairs where the judge picks the same winner as human experts (ties excluded). Consistency: % of pairs where the verdict stays the same after swapping the two answers.
Zheng, L. et al. (2023). Judging LLM-as-a-judge with MT-Bench and Chatbot Arena. NeurIPS Datasets & Benchmarks. Tables 2–5.
import os
from openai import OpenAI
client = OpenAI(base_url=os.environ.get("VLLM_BASE_URL", "http://LAB-HOST:8000/v1"),
api_key=os.environ.get("VLLM_API_KEY", "EMPTY"))
MODEL = "Qwen/Qwen2.5-VL-7B-Instruct"
def judge(q, a, b):
prompt = f"Question: {q}\n\nAnswer A: {a}\n\nAnswer B: {b}\n\nWhich answer is better? Reply with A or B only."
out = client.chat.completions.create(model=MODEL, max_tokens=5, temperature=0,
messages=[{"role": "user", "content": prompt}])
return out.choices[0].message.content.strip()[:1]
def compare(q, x, y):
v1, v2 = judge(q, x, y), judge(q, y, x) # same pair, both orders
if (v1, v2) == ("A", "B"): return "x wins"
if (v1, v2) == ("B", "A"): return "y wins"
return f"inconsistent ({v1}, {v2}): position bias, count as a tie"
Xie, T. et al. (2024). OSWorld: benchmarking multimodal agents for open-ended tasks in real computer environments. NeurIPS. Fig. 1, Table 5.
| Stage | What it adds | What it cannot do alone |
|---|---|---|
| SFT | follows instructions; copies a teacher’s style | exceed the teacher; learn from bad answers |
| PEFT | makes every stage affordable (<1% of the weights) | — |
| Preferences (RLHF, DPO) | answers people prefer; fewer hallucinations | resist a reward model that can be fooled |
| RLVR | multi-step reasoning, learned not prompted | tasks without a checkable answer |
| Tools | acts: zooms, runs code, clicks | know when its own perception failed |
Every stage optimises a signal. The quality of the model is bounded by the quality of the signal.
M.Sc. AIS · Foundation Models · Fall 2026