Training, Alignment & Reasoning

Foundation Models · M.Sc. AIS @ UniTN 2026

Paolo Rota, Jacopo Staiano, Federico Bartsch

{name.surname}@unitn.it

University of Trento

After pretraining

Where we left off

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)

One warning we carry over

LLaVA-Bench: “85.1% of GPT-4”, and the judge was GPT-4.

  • A score is only as good as whoever computes it. A judge that likes long, confident answers will rate them high, right or wrong.
  • This lecture does more than measure models with scores: it trains them on scores. Keep one question in mind throughout: what exactly is being rewarded?

The plan: four stages after pretraining

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.

1. Make it follow instructions: SFT

Pretrained ≠ helpful

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:

  • Helpful: does what the user asks.
  • Honest: grounded, calibrated, admits uncertainty.
  • Harmless: refuses unsafe requests.

Two levers: supervised demonstrations, then preference-based optimisation.

Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS.

Activity: is it SFT?

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?

  1. LLaVA’s 158K GPT-4-written conversations
  2. CLIP’s 400M (image, caption) pairs with the contrastive loss
  3. (video, question, answer) triples
  4. MAE: reconstruct the masked patches
  5. Two answers, a human says which one is better
  6. Fine-tune a pretrained VLM to produce the COCO caption of each image
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)

SFT / visual instruction tuning

Fine-tune on (image, instruction, desired response) triples, with the usual next-token loss on the response tokens only.

  • LLaVA stage 2 is SFT: 158K generated conversations, CLIP frozen, projector + LLM trained.
  • Qwen2.5-VL post-training starts with SFT on ~2M samples, half of them text-only, so the model keeps its language skills.

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.

SFT: who writes the targets?

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.

ShareGPT4V — the question

  • VLMs “align the modalities in a sub-optimal manner, primarily due to the lack of sufficient high-quality image-text pairs”.
  • Web and COCO captions are short and name only the salient objects.

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.

ShareGPT4V — the recipe

  • Step 1: GPT-4V writes detailed captions for ~100K images from diverse sources, 942 characters on average.
  • Step 2: a captioner trained on those 100K (Share-Captioner) writes new captions for 1.2M images, in about 44 A100-days.
  • The swap: LLaVA-1.5’s SFT data (~665K samples) contains 23K “describe this image in detail” samples. Replace exactly those with 23K GPT-4V captions: 3.5% of the data. Nothing else changes.

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.

ShareGPT4V — the evidence

Four models on 9 benchmarks: blue = original SFT data, red = with the GPT-4V captions swapped in (“+ours”).

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.

2. Make it cheap: parameter-efficient fine-tuning

PEFT — why not fine-tune everything?

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.

  • LoRA / adapters: inject small trainable modules.
  • Prompt tuning: learn a few input vectors (a soft prompt); the weights stay frozen.

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.

Adapters & the projector

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.

LoRA — the question

  • For GPT-3 175B, deploying one fine-tuned copy per task “is prohibitively expensive”: 350 GB each.
  • Adapters add layers in sequence → extra latency at inference. Prefix tuning uses up part of the context window.
  • Hint from earlier work: pretrained models have a low “intrinsic dimension”: a few directions are enough to adapt them.

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.

LoRA — the idea

  • Freeze \(W_0\); learn \(\Delta W = BA\), with \(B \in \mathbb{R}^{d\times r}\), \(A \in \mathbb{R}^{r\times d}\), \(r \ll d\). The branch is scaled by \(\alpha/r\): \(\alpha\) is a fixed constant, so the update size does not depend on the rank.
  • Init: \(A\) random, \(B = 0\) → at step 0 the model is exactly the pretrained one.
  • Where: on the attention projections \(W_q, W_k, W_v, W_o\); in most experiments only \(W_q\) and \(W_v\), the best use of a fixed budget. Today often on every linear layer. (see next slide)
  • No latency: merge \(W = W_0 + BA\) before deployment; to switch task, subtract \(BA\) and add \(B'A'\).

Why fewer parameters, on a toy layer (d = 6, rank r = 1).

Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. Redrawn from Fig. 1.

LoRA — where it sits in a transformer

Hu, E. J. et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. Sec. 4.2, 7.1.

Activity: count the parameters

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%.

LoRA — the evidence

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.

Demo: LoRA on CLIP, locally

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 = 0

Prompt tuning — CoOp: the question

  • CLIP zero-shot depends on the prompt, and “a slight change in wording could have a huge impact on performance”.
  • Caltech101: “a photo of [CLASS].” 80.81 vs “a photo of a [CLASS].” 86.29. One word, +5 points.
  • Prompt engineering “requires domain expertise and is extremely time-consuming”.

Question: 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.

CoOp — the idea

  • \(M = 16\) context vectors of 512 dimensions (CLIP’s word-embedding size), shared by all classes, or one set per class for fine-grained datasets.
  • Cross-entropy on a few labelled shots; the gradient flows through the frozen text encoder into the vectors only.

Zhou, K. et al. (2022). Learning to prompt for vision-language models. IJCV.

CoOp — the evidence, and the catch

Gain over the hand-written prompt, 16 shots
  • 1–2 shots already beat the hand-written prompt; at 16 shots +15% on average over 11 datasets, up to +46 (EuroSAT).
  • A linear probe needs more than 4 shots just to match zero-shot CLIP.

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.

TPT — prompt tuning at test time

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.

TPT — the evidence

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
  • +3.6 on average under distribution shift, without a single labelled example, and above CoOp.
  • Confidence selection matters most on the hardest set: +3.0 on ImageNet-A (RN50).
  • The price: a backward pass and 64 forward passes per test image.

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.

3. Make it preferred: learning from preferences

Why preferences?

SFT imitates demonstrations. But often we cannot write the right answer; we can only say which of two answers is better.

  • Ranking is easier than writing, for humans and for models.
  • A preference can encode things that are hard to demonstrate: tone, concision, not inventing objects.
  • Optimising for it needs a different tool: reinforcement learning, or a loss that does the same job.

From “copy this answer” to “produce answers people prefer”.

InstructGPT — the question

  • GPT-3 is trained to predict the next token on web text, which is misaligned with “follow the user’s instructions helpfully and safely”.
  • It makes up facts, ignores instructions, produces toxic text.

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.

RLHF in three steps

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.

The reward model is a pairwise classifier

\[ \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.

The RL objective: reward, but stay close

\[ \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] \]

  • First term: produce answers the reward model scores high.
  • Second term: a KL penalty to the SFT model \(\pi_{ref}\) (\(\beta = 0.02\) in InstructGPT). Without it, the policy finds answers the reward model overrates: reward hacking.
  • Optimised with PPO.

Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS. Eq. 2.

PPO — conservative policy updates

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)} \]

  • \(\pi_{\theta_{old}}\): the policy as it was when it sampled this batch (a snapshot); \(\pi_\theta\): the policy being updated. \(\rho_t\) = how much more (or less) likely the token has become since then. State \(s_t\) = prompt + tokens so far; action \(a_t\) = the next token.
  • \(\hat A_t\) is the advantage: how much better this token was than expected.
  • Clipping (\(\epsilon = 0.2\)) ignores gains from moving the ratio beyond \([0.8, 1.2]\): a pessimistic bound.
  • The advantage needs a value model (a critic) as large as the policy. Heavy: four models in memory.

Schulman, J. et al. (2017). Proximal policy optimization algorithms. arXiv.

PPO — reward model vs value model

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:

  1. The policy writes an answer.
  2. The reward model scores it: \(R = 0.8\).
  3. The value model had predicted \(V = 0.6\).
  4. Advantage \(\hat A = R - V = +0.2\): better than expected, reinforce it.
  5. Update the policy (clipped loss) and the value model (towards 0.8, to predict better next time).

After training both are thrown away: only the policy is deployed.

PPO — a worked example

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.

InstructGPT — the evidence

Win rate vs the 175B SFT model. GPT = plain GPT-3 · GPT (prompted) = GPT-3 with an assistant prompt · SFT · PPO · PPO-ptx = InstructGPT.
  • Win rate against the 175B SFT model, judged by labelers.
  • 1.3B InstructGPT is preferred to 175B GPT-3: 100× fewer parameters.
  • 175B InstructGPT beats 175B GPT-3 85 ± 3% of the time.
  • Cost: 60 petaflop/s-days for PPO-ptx, vs 3,640 to pretrain GPT-3.

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.

Activity: be the reward model

“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.

Goodhart’s law

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:

  • LLaVA-RLHF: naive RLHF makes answers longer without making them more correct.
  • GLM-4.1V: one weak verifier makes all of training collapse.
  • LLM judges: biased towards long answers and the first answer shown.

Charles Goodhart (b. 1936), British economist. Bank of England adviser, then professor at the LSE.

Photo: Jamesfranklingresham, Wikimedia Commons, CC BY-SA 3.0 (2012 Long Finance conference).

Back to hallucination: LLaVA-RLHF

  • 10K human preferences ($3,000): “which answer has fewer hallucinations?”
  • Naive RLHF: the reward model is built from LLaVA itself and can’t check the image, so it scores how good an answer sounds. RL then makes answers longer, invented details included.
  • Fact-RLHF: the reward model also gets the image’s human-written captions as an answer key (the policy never sees them), plus correctness rewards on questions with known answers and a length penalty.
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.

DPO — the question

  • RLHF is “considerably more complex than supervised learning”: a reward model, a value model, sampling from the policy inside the training loop, and PPO’s many hyperparameters.
  • But the RL objective has a known optimum: \(\pi^*(y|x) \propto \pi_{ref}(y|x)\, e^{\,r(x,y)/\beta}\).
    • new model is like the old model times a reward exponentiated, normalised.

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.

DPO — the idea

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.

DPO — worked example (1/3): what is π?

\(\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.

DPO — worked example (2/3): implicit reward

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.

DPO — worked example (3/3): loss and push

\[ \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.

DPO — the evidence

Sentiment control (IMDb): reward vs KL

Summarisation (TL;DR): GPT-4 win rate
  • IMDb: for any KL budget, DPO reaches higher reward than PPO, even PPO with access to the true reward.
  • TL;DR: win rate ~61% vs ~57% for the best PPO, and much more robust to the sampling temperature. Humans prefer DPO to PPO 58% of the time.

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.

A DPO follow-up: RLHF-V

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.

Demo: DPO on a VLM (GPU node)

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()

4. The hinge: rewards you can check

When the answer can be checked

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}) \]

  • RLVR (reinforcement learning with verifiable rewards): the RLHF objective, with the reward model replaced by a verifier.
  • Tülu 3: math (GSM8K, MATH: exact match on the answer) and instruction constraints (IFEval: “answer in 3 bullet points”), after SFT and DPO.
  • A rule has nothing to hack: it cannot be flattered by length or style.

Lambert, N. et al. (2024). Tülu 3: pushing frontiers in open language model post-training. arXiv. Sec. 6.

GRPO — drop the critic, use the group

\[ \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.

RLVR with GRPO, step by step

GRPO — a worked example (1/2): the group

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.

GRPO — a worked example (2/2): clipping

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 vs GRPO vs DPO

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.

DeepSeek-R1-Zero — the question

  • Reasoning gains so far depended on human-written reasoning traces. They are expensive, biased, and cap the model at the level of the humans who wrote them.

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.

R1-Zero — the evidence

AIME 2024 accuracy during RL

Average response length during RL
  • AIME 2024 pass@1: 15.6% → 77.9%; 86.7% with majority voting over 16 samples, above the human participants.
  • Nobody asked for long answers: the length grows from hundreds to thousands of tokens, with reflection (“Wait, wait. Wait. That’s an aha moment…”).

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.

From R1-Zero to R1

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.

Does RL teach new skills, or sharpen old ones?

Accuracy vs number of samples K (GSM8K, MATH). Compare each metric with itself, before vs after RL: Maj@K-RL (orange) is above Maj@K-Instruct (purple); Pass@K-RL (blue) ≈ Pass@K-Instruct (green). Maj@K is always below Pass@K, by definition.

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.

Visual-RFT — RLVR for vision outputs

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.

When should we use RL?

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.

Recap: Qwen2.5-VL’s post-training

Real systems stack these stages. Qwen2.5-VL, from the Understanding lecture:

  1. Pretrain / align the vision encoder (captions, OCR), then the whole model, then long context.
  2. SFT on ~2M curated samples, half text-only (ViT frozen), with rejection sampling for reasoning data.
  3. DPO on preference data.

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.

A modern recipe: GLM-4.1V-Thinking

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

Each cell: gain over the SFT model on an evaluation domain (column) after RL on one training domain (row). Mix All = all domains together.

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.

One weak verifier is enough to break it

  • Top: training rewards keep rising. Bottom: benchmark scores collapse.
  • One domain (multi-image questions) had a weak verifier. The model learned to exploit it; after ~150 steps all domains collapsed.
  • “Any weakness in the reward signal for a single capability can derail the entire training.”

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.

5. Make it reason

Two capabilities

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.

Baseline — direct answer vs chain-of-thought

  • Direct: question → answer.
  • Chain-of-thought (CoT): the prompt starts with ~8 worked examples, each question → reasoning → answer. The model continues the pattern: it writes steps, then “The answer is …”. No training: only the prompt changes.
  • PaLM (Google’s 540B LLM, 2022) on GSM8K: 17.9 → 56.9.
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 answer

How 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.

Self-consistency — sample, then vote

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.

TTRV — reinforcement learning on the test set

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?

  • No labels at test time, so where is the reward? Use the model’s own agreement: sample \(N\) answers to a test question; reward each answer by how often it appears (a soft majority vote), plus a bonus for low entropy.
  • Run GRPO on these rewards, on unlabelled test samples: TPT’s idea, turned into RL.

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.

TTRV — the evidence

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.

LLaVA-CoT — the question

  • VLMs “often struggle to perform systematic and structured reasoning”.
  • They present “a conclusion prematurely and subsequently attempt to justify it”; with token-by-token generation, an early mistake propagates.
  • Free-form CoT prompting on a VLM drifts and hallucinates.

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.

LLaVA-CoT — the idea and an example

Four tagged stages, in one pass:

  1. <SUMMARY> the task
  2. <CAPTION> the relevant parts of the image
  3. <REASONING> step by step
  4. <CONCLUSION> the answer

Data: 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.

LLaVA-CoT — the evidence

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
  • The structure is worth +1.5 on its own: same data, with vs without tags (60.9 → 62.4).
  • At test time: several candidates per stage, a reward model picks one; if all are bad, retrace: go back and regenerate the previous stage.

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.

Thinking with images — the question

  • Long-CoT VLMs see the image once, then reason only in text. Small details lost in the first look stay lost.
  • OpenAI’s o3 (April 2025): “our models can think with images in their chain-of-thought, not just see them”, cropping and zooming as it reasons. The recipe was not disclosed.

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.

DeepEyes — the idea

Zheng, Z. et al. (2026). DeepEyes: incentivizing “thinking with images” via reinforcement learning. ICLR. Eq. 2.

DeepEyes — the evidence

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
  • High-resolution HR-Bench 4K / 8K: +6.3 / +7.3 over the base.
  • During training the model first zooms rarely, then too often, then learns to zoom less and better.

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.

6. Make it act

Baseline — a single tool call

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.

ReAct — think, act, observe

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.

VISPROG — the question

  • End-to-end VLMs need training for every new task, and give no insight into how they answered.
  • Neural module networks compose modules, but must learn the modules and the layout together.

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.

VISPROG — the idea

Gupta, T. & Kembhavi, A. (2023). Visual programming: compositional visual reasoning without training. CVPR. The example program is ours, in the paper’s syntax.

VISPROG — 20 modules

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.

VISPROG — the evidence

The visual rationale of an image-editing instruction: every program step with its intermediate output.
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.

Activity: be VISPROG

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.

  1. “Hide every face with a 😎.”
  2. “Tag the members of the Beatles in the photo.”

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)

ViperGPT — code as the reasoning trace

  • Codex (GPT-3 fine-tuned on code) sees only the API specification (signatures and docstrings), never the image, and writes a Python function.
  • Perception from pretrained models (GLIP detection, X-VLM image–text matching, MiDaS depth, BLIP-2 VQA); logic (sort, if, math) from Python.
  • BLIP-2 answers “ski”; the program answers “hibernate”.
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.

GUI agents — the question

  • Earlier agents read the HTML or accessibility tree: verbose, platform-specific, often unavailable.
  • Screens are 720p and more; VLMs ran at 224–490 px, so small buttons and text were invisible.

Question: can a VLM operate a computer from pixels only, the way people do?

CogAgent — enough pixels to read the screen

  • CogVLM (224 × 224, 256 tokens) + a small high-resolution branch at 1120 × 1120 (6,400 tokens).
  • The high-resolution tokens enter every layer through cross-attention with a small hidden size, so the self-attention sequence stays short: Flamingo’s trick, used for resolution.
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.

UI-TARS — a native GUI agent

  • Qwen2-VL trained end-to-end: screenshot in, thought + action out; one action space across desktop, web, mobile.
  • Learns from its own runs: hundreds of virtual PCs; traces filtered, mistakes corrected by annotators, then SFT and DPO on (corrected, wrong) actions.
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.

Demo: a zoom-in agent on the lab vLLM

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); break

Next: from screens to robots

A 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.

7. Evaluation: how we measure alignment and reasoning

Task metrics

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

LLM-as-a-judge — and its biases

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.

Demo: a judge that checks both orders

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"

Agents: did the task actually get done?

  • 369 real computer tasks in virtual machines; each with its own evaluation script that checks the final state (a file, a setting, a cell). 134 different checkers.
  • At release (April 2024): humans 72.4%, best model 12.2%. UI-TARS (January 2025): 24.6%.

Xie, T. et al. (2024). OSWorld: benchmarking multimodal agents for open-ended tasks in real computer environments. NeurIPS. Fig. 1, Table 5.

Closing: what did each stage add?

Back to the plan

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.

Questions?