Coding tutorial · Build it from scratch

Post-Train a VLM

We take a real 256M vision-language model and align it by hand: preference pairs with exact truth, image-conditioned DPO, a check that it used the image, visual GRPO, and a reward we hack on purpose.

Multimodal RLHallucinationDPO and GRPO

A post-training system for a real pretrained VLM: exact synthetic scenes, five kinds of hallucination negatives, image-conditioned DPO written by hand, a blind-preference check, tested visual rewards, visual GRPO, a freeze ablation, and a reward we hack on purpose.

Time
About an hour to read and run the tests. Running every script took about three hours of wall time on 8 CPU threads, plus about four minutes of H100 training for two counting runs (see results/run_all.log).
Hardware
Two machines, and every result names which one. CPU is an AMD EPYC 7R13 with 8 threads. H100 is an NVIDIA H100 80GB HBM3 with torch 2.15.0 and CUDA 13.2. Nothing here requires a GPU.
You need
Python 3.10+, PyTorch, transformers 5, Pillow, pytest. It helps to have read C6 for LoRA and text DPO, and C7 for the VLM forward pass.
Package
vlmalign
Final repo tree c09-vlm-post-training/
c09-vlm-post-training/
├── README.md                 # how to run everything, results table
├── conftest.py
├── vlmalign/
│   ├── scenes.py             # synthetic images with exact facts
│   ├── tasks.py              # questions and sentence templates
│   ├── preference.py         # hallucination negatives, balanced and biased
│   ├── model.py              # SmolVLM loading, prompts, answers
│   ├── logprobs.py           # batches, encode-once path, sequence log-probs
│   ├── dpo.py                # image-conditioned DPO loss and pair batches
│   ├── blind.py              # text-only preference probe
│   ├── rewards.py            # exact match, IoU, Dice, CER, ANLS, field accuracy
│   ├── rl_tasks.py           # RL tasks and reward registry
│   ├── grpo.py               # rollouts, relative advantages, clipped loss
│   ├── lora.py               # a minimal LoRA
│   ├── freeze.py             # the three freeze modes
│   ├── evaluate.py           # VQA and preference accuracy, real or grey image
│   ├── tiny.py               # tiny random Idefics3 for offline tests
│   └── device.py
├── scripts/
│   ├── show_pairs.py         # pairs and one batch, tensor by tensor
│   ├── blind_probe.py        # the text-only check
│   ├── reward_audit.py       # hand-written answers against every reward
│   ├── show_rollouts.py      # one GRPO group printed
│   ├── train_dpo.py
│   ├── train_grpo.py         # freeze ablation and reward hacking
│   ├── perception_probe.py   # did image features change?
│   └── run_all.sh
├── benchmarks/
│   └── bench_encode_once.py
├── results/                  # real logs and JSON
└── tests/
    ├── test_rewards.py
    ├── test_data.py
    ├── test_logprobs_dpo.py
    ├── test_lora_freeze.py
    ├── test_grpo.py
    └── test_smolvlm_network.py

The plan

When a vision-language model starts to prefer the true answer after post-training, did it look at the image, or did it learn which words tend to win?

Most of this tutorial exists to answer that question with numbers. A VLM can lower a preference loss without using a single pixel. It can also raise a visual reward by gaming the reward. Both failures look like progress on a training curve.

So we build the alignment stack on images where we know every fact exactly. We draw the image ourselves, so we know the true colour, count, position and text. That makes every preference label and every reward exact, and it lets us run controls that real datasets cannot.

We post-train a real pretrained model, HuggingFaceTB/SmolVLM-256M-Instruct. The tiny VLM from C7 and C8 is not capable enough for this. Preference learning and RL refine a model that can already do the task sometimes. A model that cannot read a colour gives DPO and GRPO nothing to refine.

Clone the repo once. Every command below runs from its root, using this virtual environment.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
Step 01

Draw scenes where the truth is exact

Goal A seeded image generator, and questions whose answers we compute instead of annotate.

A scene is a few coloured shapes and one printed word on a white canvas. Objects live in distinct cells of a 3 by 3 grid, so they never overlap. Each pair of colour and shape appears at most once, which keeps every question unambiguous.

def sample_scene(seed: int, min_objects: int = 2, max_objects: int = 6, with_word: bool = True) -> Scene:
    """Place objects in distinct grid cells; each (colour, shape) pair is unique."""
    rng = random.Random(seed)
    cell = CANVAS // GRID
    cells = [(r, c) for r in range(GRID) for c in range(GRID)]
    rng.shuffle(cells)
    word, word_box = None, None
    if with_word:
        r, c = cells.pop()
        word = rng.choice(WORDS)
        word_box = (c * cell + 12, r * cell + 45, (c + 1) * cell - 12, (r + 1) * cell - 45)
    n = rng.randint(min_objects, min(max_objects, len(cells)))
    identities = [(s, k) for s in SHAPES for k in PALETTE]
    rng.shuffle(identities)
    objects = []
    for (r, c), (shape, color) in zip(cells[:n], identities[:n]):
        side = rng.randint(80, 120)
        x0 = c * cell + rng.randint(8, cell - side - 8)
        y0 = r * cell + rng.randint(8, cell - side - 8)
        objects.append(Obj(shape, color, (x0, y0, x0 + side, y0 + side)))
    return Scene(objects=objects, word=word, word_box=word_box, seed=seed)
Listing 1One seed gives one scene. Drawing at 512 pixels matches the size SmolVLM uses, so we avoid a resample.

Questions come with a sentence template that has one slot. This is what makes hallucination negatives cheap later: a rejected answer is the same sentence with one slot changed.

def ask(scene: Scene, kind: str, rng: random.Random) -> Question | None:
    """Return one question of `kind` about `scene`, or None if the scene cannot support it."""
    if kind == "color":
        unique = [o for o in scene.objects if scene.count(o.shape) == 1]
        if not unique:
            return None
        o = rng.choice(unique)
        return Question(kind, f"What color is the {o.shape}?", o.color, f"The {o.shape} is {{}}.", "color")
    if kind == "count":
        shape = rng.choice(sorted({o.shape for o in scene.objects}))
        n = scene.count(shape)
        return Question(kind, f"How many {shape}s are there?", str(n), f"The number of {shape}s is {{}}.", "count")
    if kind == "object":
        unique = [o for o in scene.objects if len(scene.with_color(o.color)) == 1]
        if not unique:
            return None
        o = rng.choice(unique)
        return Question(kind, f"What shape is the {o.color} object?", o.shape, f"The {o.color} object is a {{}}.", "shape")
    if kind == "ocr":
        if not scene.word:
            return None
        return Question(kind, "What word is written in the image?", scene.word, "The word is {}.", "word")
    if kind == "spatial":
        pairs = [(a, b) for a in scene.objects for b in scene.objects
                 if a is not b and abs(a.center[0] - b.center[0]) > 60]
        if not pairs:
Listing 2Four of the five question kinds, and the start of the fifth. The answer is computed from the scene, and the template holds one slot.

Next, load the model. SmolVLM normally splits a large image into tiles. Our scenes do not need that, so we switch it off. One 512 by 512 tile gives 64 image tokens instead of 1,088, which makes every later step faster.

def load_processor(model_id: str = MODEL_ID):
    # One 512x512 tile instead of 16 tiles + a global view: 64 image tokens, not 1,088.
    # Our synthetic scenes are 512x512 with large objects, so tiling buys nothing.
    proc = AutoProcessor.from_pretrained(model_id)
    proc.image_processor.do_image_splitting = False
    return proc
Listing 3Turning off tiling. The first run of this tutorial had 1,141 tokens per prompt. This line brings it to 81.
What goes into SmolVLM-256M for one image
TensorShapeMeaning
pixel_values(1, 1, 3, 512, 512)Batch, images per row, channels, height, width.
Vision output(1, 1024, 768)32 × 32 patches of 16 pixels, from a SigLIP encoder.
Connector output(1, 64, 576)Pixel shuffle by 4 merges 16 patches into one token, then a linear projection.
input_ids(1, 81)17 text tokens around 64 <image> placeholders, for a short question.
logits(1, 81, 49280)One distribution over the vocabulary per position.

Run the scene and question tests before going further. They need no model, so they take seconds.

$ .venv/bin/python -m pytest c09-vlm-post-training/tests/test_data.py
7 passed in 3.02s

Before we train anything, measure what the pretrained model can do. Greedy short answers, 30 questions per kind, on the fixed evaluation set that train_dpo.py prints first.

Pretrained SmolVLM-256M, greedy short answers, 30 questions per kind. AMD EPYC 7R13, 8 threads, one seed. Computed from results/dpo_balanced.json (the before entry).
SkillExact-match accuracy
color67%
count7%
object77%
ocr97%
spatial47%
mean59%

Counting is the weak skill at 7%, and spatial is next at 47%. The training runs in steps 5, 9 and 10 report against this table. Step 9 uses a different set of 100 counting questions, on which the pretrained model scores 8% and on which 55 of the 100 answers are 1. Both sets are small, so treat 7% and 8% as the same number.

Checkpoint

  • The same seed produces the same pixels.
  • test_render_draws_the_object_colour_at_its_centre and test_answers_match_the_scene pass.
Step 02

Generate hallucination negatives

Goal Turn every question into a preference pair, in two versions: one that needs the image, and one that does not.

A multimodal preference example has four fields: image, prompt, chosen, rejected. The chosen answer states the true fact. The rejected answer is a hallucination we manufacture, and it comes in five kinds: wrong colour, wrong count, wrong object, false OCR and wrong spatial relation.

How we draw the wrong value matters more than anything else in this step. So we write two samplers that share everything else.

def wrong_value(q: Question, rng: random.Random, mode: str = "balanced") -> str:
    """A value for the slot that is false for this image."""
    if q.kind == "spatial":
        return _OTHER_SIDE[q.answer]  # only two values: flipping is already symmetric
    if mode == "balanced":
        return rng.choice([v for v in VALUES[q.kind] if v != q.answer])
    if mode == "biased":
        if q.kind == "color":
            return rng.choice(OFF_PALETTE)      # a colour no image ever contains
        if q.kind == "count":
            return str(int(q.answer) + 1)       # always one too many
        if q.kind == "object":
            return rng.choice(["star", "hexagon"])  # a shape no image ever contains
        if q.kind == "ocr":
            i = rng.randrange(len(q.answer))    # a misspelling, never a real word
            return q.answer[:i] + rng.choice("QXZJ") + q.answer[i + 1:]
    raise ValueError(f"unknown mode {mode!r}")
Listing 4The balanced sampler draws from the same set as true values. The biased sampler uses tempting shortcuts.

Try both. Pick a kind, switch the sampler, and read the note under the pair.

Prompt

Chosen

Rejected

Figure 1The hallucination-negative generator, ported to JavaScript from preference.py. Dashed outlines mark the objects the question is about. The scene layouts here use a browser random generator, so they differ from the Python seeds, but the sampling rules are the same.

A note on true values. If we let true counts follow the scene generator, they skew towards 1 and 2. Then a rejected answer of 3 would mostly appear on the rejected side, and text alone would predict the label. So build_pairs picks the target true value first, uniformly, then searches for a scene that has it.

def build_pairs(n: int, mode: str = "balanced", seed: int = 0, kinds: tuple[str, ...] = KINDS) -> list[PreferencePair]:
    """n pairs, kinds in round-robin, true answers uniform over VALUES[kind].

    We pick the target true value first and then search scenes until one has
    that answer. Without this stratification, true counts skew towards 1 and 2,
    and "3" would mostly appear on the rejected side: a text-only shortcut.
    """
    rng = random.Random(seed)
    pairs: list[PreferencePair] = []
    scene_seed = seed * 1_000_003
    for i in range(n):
        kind = kinds[i % len(kinds)]
        target = rng.choice(VALUES[kind])
        while True:
            scene_seed += 1
            scene = sample_scene(scene_seed)
            q = ask(scene, kind, rng)
            if q is not None and q.answer == target:
                break
        wrong = wrong_value(q, rng, mode)
        pairs.append(PreferencePair(scene, q, q.sentence(), q.sentence(wrong), mode))
    return pairs
Listing 5Stratify on the true value first. Then true and wrong values have the same uniform distribution, which makes each pair exchangeable.
$ .venv/bin/python c09-vlm-post-training/scripts/show_pairs.py
--- balanced ---
color    What color is the circle?
           chosen   The circle is yellow.
           rejected The circle is blue.
count    How many triangles are there?
           chosen   The number of triangles is 3.
           rejected The number of triangles is 2.
object   What shape is the yellow object?
           chosen   The yellow object is a triangle.
           rejected The yellow object is a circle.
ocr      What word is written in the image?
           chosen   The word is KEY.
           rejected The word is BOX.
spatial  Is the red triangle to the left or to the right of the blue circle?
           chosen   The red triangle is to the left of the blue circle.
           rejected The red triangle is to the right of the blue circle.
--- biased ---
color    What color is the circle?
           chosen   The circle is yellow.
           rejected The circle is pink.
count    How many triangles are there?
           chosen   The number of triangles is 3.
           rejected The number of triangles is 4.
object   What shape is the yellow object?
           chosen   The yellow object is a square.
           rejected The yellow object is a hexagon.
ocr      What word is written in the image?
           chosen   The word is BOX.
           rejected The word is QOX.
spatial  Is the blue triangle to the left or to the right of the blue circle?
           chosen   The blue triangle is to the left of the blue circle.
           rejected The blue triangle is to the right of the blue circle.

Checkpoint

  • You can read a pair and predict the answer only by looking at the image, on the balanced side.
  • On the biased side, you can often answer without the image. Keep that in mind for step 6.
Step 03

Turn one pair into tensors

Goal A batch where chosen and rejected share an image, and only answer tokens carry a label.

Each pair makes two rows. Both rows hold the same prompt ids, and then their own answer. We tokenize the answer separately and append it. That keeps the prompt ids identical to what generate() conditions on, so we train on the same probabilities the model samples from.

def encode_answer(processor, answer: str) -> torch.Tensor:
    """Answer token ids, ending with <end_of_utterance>. Shape (T_answer,).

    We tokenize the answer on its own and append it to the prompt ids. That keeps
    the prompt ids byte-identical to what generate() conditions on, so the
    log-probabilities we train on are the ones the model would sample from.
    """
    tok = processor.tokenizer
    ids = tok(" " + answer, add_special_tokens=False)["input_ids"]
    return torch.tensor(ids + [end_of_utterance_id(processor)], dtype=torch.long)
Listing 6The answer ends with end_of_utterance, because stopping is part of what the model must learn.

Now build the batch. Rows are padded on the right, labels are -100 outside the answer, and each row keeps an index into a smaller tensor of distinct images.

def build_batch(prompts: list[torch.Tensor], answers: list[torch.Tensor], image_index: list[int],
                pixel_values: torch.Tensor, pad_id: int) -> SeqBatch:
    """Right-pad prompt+answer rows. prompts[i]: (T_p,), answers[i]: (T_a,)."""
    rows = [torch.cat([p, a]) for p, a in zip(prompts, answers)]
    T = max(len(r) for r in rows)
    B = len(rows)
    input_ids = torch.full((B, T), pad_id, dtype=torch.long)
    labels = torch.full((B, T), IGNORE, dtype=torch.long)
    attention_mask = torch.zeros((B, T), dtype=torch.long)
    for i, (p, r) in enumerate(zip(prompts, rows)):
        input_ids[i, : len(r)] = r
        attention_mask[i, : len(r)] = 1
        labels[i, len(p): len(r)] = r[len(p):]  # loss only on the answer
    return SeqBatch(input_ids, attention_mask, labels, torch.tensor(image_index), pixel_values)
Listing 7Prompt and padding positions stay at IGNORE, which is -100.
def pair_batch(processor, pairs: list[PreferencePair], images=None) -> SeqBatch:
    """2P rows: row 2i is pair i's chosen answer, row 2i+1 its rejected answer.

    Both rows of a pair point at the same image (image_index i), so the vision
    encoder runs P times, not 2P. Pass `images` to swap in other images
    (the blind check passes grey images here).
    """
    prompts, answers, image_index, pixels = [], [], [], []
    for i, pair in enumerate(pairs):
        img = pair.image() if images is None else images[i]
        p = encode_prompt(processor, img, pair.prompt)
        pixels.append(p.pixel_values)
        for answer in (pair.chosen, pair.rejected):
            prompts.append(p.input_ids[0])
            answers.append(encode_answer(processor, answer))
            image_index.append(i)
    return build_batch(prompts, answers, image_index, torch.cat(pixels), processor.tokenizer.pad_token_id)
Listing 8Row 2i is the chosen answer, row 2i+1 the rejected one. Both point at image i.

Look at what actually comes out. Two pairs give four rows and two images.

--- one batch: 2 pairs, so 4 rows and 2 images ---
input_ids       torch.Size([4, 90])  dtype=torch.int64
attention_mask  torch.Size([4, 90])  dtype=torch.int64
labels          torch.Size([4, 90])  dtype=torch.int64
image_index     torch.Size([4])  dtype=torch.int64
pixel_values    torch.Size([2, 1, 3, 512, 512])  dtype=torch.float32
image tokens in row 0: 64

--- row 0, with the 64 <image> ids collapsed ---
'<|im_start|>'           id=1      mask=1 label=-100
'User'                   id=11126  mask=1 label=-100
':'                      id=42     mask=1 label=-100
'<fake_token_around_image>' id=49189  mask=1 label=-100
'<global-img>'           id=49152  mask=1 label=-100
<image> x 64             mask=1 label=-100
'<fake_token_around_image>' id=49189  mask=1 label=-100
'What'                   id=1780   mask=1 label=-100
' color'                 id=2380   mask=1 label=-100
' is'                    id=314    mask=1 label=-100
' the'                   id=260    mask=1 label=-100
' circle'                id=7842   mask=1 label=-100
'?'                      id=47     mask=1 label=-100
'<end_of_utterance>'     id=49279  mask=1 label=-100
'\n'                     id=198    mask=1 label=-100
'Ass'                    id=9519   mask=1 label=-100
'istant'                 id=9531   mask=1 label=-100
':'                      id=42     mask=1 label=-100
' The'                   id=378    mask=1 label=378
' circle'                id=7842   mask=1 label=7842
' is'                    id=314    mask=1 label=314
' yellow'                id=5724   mask=1 label=5724
'.'                      id=30     mask=1 label=30
'<end_of_utterance>'     id=49279  mask=1 label=49279
'<|im_end|>'             id=2      mask=0 label=-100
A batch of P = 2 preference pairs
TensorShapeMeaning
input_ids(2P, T) = (4, 90)Prompt ids, then answer ids, then right padding.
attention_mask(2P, T)0 on padding.
labels(2P, T)Answer ids. -100 on prompt and padding.
image_index(2P,)Which row of pixel_values this sequence looks at.
pixel_values(P, 1, 3, 512, 512)One entry per distinct image, not per row.

Figure 2One real pair as tensors. The camera moves from the token rows, to the labels, to the image placeholders, and then into the answer, where the real per-token log-probabilities of the pretrained model are drawn.

Checkpoint

  • Row 0 has 64 image tokens, and only its 6 answer tokens have labels.
  • test_chosen_and_rejected_share_the_prompt_and_differ_in_the_answer passes.
Step 04

Compute sequence log-probabilities, naively and then fast

Goal One number per row: the log-probability of its answer, verified against the Hugging Face loss, with the vision encoder run only once per image.

Everything in DPO and GRPO reduces to one quantity, the sum of log-probabilities over answer tokens. The tensor work is three lines: shift, log-softmax, gather.

def token_logprobs(logits: torch.Tensor, labels: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Per-token log p(label) and its mask, shifted so position t predicts token t+1.

    logits (B, T, V), labels (B, T) -> logp (B, T-1), mask (B, T-1) bool.
    """
    logits = logits[:, :-1].float()          # log-softmax in fp32: bf16 here loses ~0.1 nats
    targets = labels[:, 1:]
    mask = targets != IGNORE
    logp = torch.gather(F.log_softmax(logits, dim=-1), 2, targets.clamp_min(0).unsqueeze(-1)).squeeze(-1)
    return logp * mask, mask
Listing 9Position t predicts token t+1, so logits drop their last position and labels drop their first.

Read it line by line. logits[:, :-1] drops the last position, because nothing follows it. labels[:, 1:] drops the first label, so position t lines up with token t+1. The mask marks positions whose target is a real answer token.

clamp_min(0) exists only so that gather does not see an index of -100. Multiplying by the mask then zeroes those positions. The result is one log-probability per answer token, and zero everywhere else.

The naive way to get logits is to hand pixel_values to the model. It runs the vision encoder once per row. But chosen and rejected share an image, and G rollouts share an image. So we run it once per distinct image and write the features into the placeholder slots ourselves.

def merge_image_tokens(model, input_ids: torch.Tensor, feats: torch.Tensor) -> torch.Tensor:
    """Write image features into the <image> placeholder slots.

    input_ids: (B, T), feats: (B, N, D) -> inputs_embeds: (B, T, D).
    The b-th row's N placeholders receive feats[b] in order.
    """
    embeds = model.get_input_embeddings()(input_ids)                      # (B, T, D)
    slots = (input_ids == model.config.image_token_id).unsqueeze(-1)      # (B, T, 1)
    return embeds.masked_scatter(slots, feats.to(embeds.dtype).reshape(-1, feats.shape[-1]))
Listing 10masked_scatter fills the image slots with features in order. Gradients flow through it into the connector and the vision encoder.
def forward_logits(model, batch: SeqBatch, encode_once: bool = True) -> torch.Tensor:
    """Logits (B, T, V).

    encode_once=False is the naive path: hand pixel_values to the model, which
    runs the vision encoder once per ROW. Chosen and rejected share an image, and
    G rollouts share an image, so that repeats the same encoder work 2x or Gx.
    encode_once=True runs the encoder once per DISTINCT image and indexes into it.
    Gradients still flow into the vision tower and the connector either way.
    """
    if not encode_once:
        pv = batch.pixel_values[batch.image_index]                        # (B, 1, 3, H, W)
        return model(input_ids=batch.input_ids, attention_mask=batch.attention_mask, pixel_values=pv).logits
    feats = image_features(model, batch.pixel_values)                     # (I, N, D)
    embeds = merge_image_tokens(model, batch.input_ids, feats[batch.image_index])
    return model(inputs_embeds=embeds, attention_mask=batch.attention_mask).logits
Listing 11The naive path and the fast path. A test checks that they return the same logits on a tiny random model.

Now measure what the fast path saves. One forward and backward pass on one image and G rollouts, with all three model parts trainable. We run it on the CPU, and again on an H100 with one more group size.

$ .venv/bin/python c09-vlm-post-training/benchmarks/bench_encode_once.py --groups 4 8 16
$ .venv/bin/python c09-vlm-post-training/benchmarks/bench_encode_once.py --groups 4 8 16 32   # on the H100
device=cpu  freeze=all  one image, G rollouts, median of 5
   G   naive (ms)    once (ms)  speed-up
   4         6922         2081     3.33x
   8        12952         2857     4.53x
  16        34549         4514     7.65x
device=cuda  freeze=all  one image, G rollouts, median of 5
   G   naive (ms)    once (ms)  speed-up
   4          226          205     1.10x
   8          286          208     1.38x
  16          398          209     1.90x
  32          618          207     2.99x
One forward and backward pass on one image and G rollouts, all three parts trainable, median of 5. Milliseconds. Computed from results/bench_encode_once.log (CPU: AMD EPYC 7R13, 8 threads, shared with other jobs) and results/bench_encode_once_gpu.log (H100: NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2).
GCPU naiveCPU onceCPU speed-upH100 naiveH100 onceH100 speed-up
46,9222,0813.33x2262051.10x
812,9522,8574.53x2862081.38x
1634,5494,5147.65x3982091.90x
32not runnot runnot run6182072.99x

Checkpoint

  • test_encode_once_equals_naive_path, test_sequence_logprob_matches_hf_loss and test_padding_does_not_change_a_row pass.
Step 05

Write image-conditioned DPO by hand

Goal The DPO loss with the image inside every term, trained on balanced negatives, with no second model in memory.

The derivation is in the theory post. Here is what the loss looks like in code. The image does not appear in this function, because it is already inside each log-probability.

Derivation inTeaching a model what we prefer
def dpo_loss(pi_chosen: torch.Tensor, pi_rejected: torch.Tensor, ref_chosen: torch.Tensor,
             ref_rejected: torch.Tensor, beta: float = 0.1) -> dict[str, torch.Tensor]:
    """All inputs (P,) sequence log-probs for P pairs. Returns the loss and diagnostics."""
    chosen_reward = beta * (pi_chosen - ref_chosen)        # implicit reward of y_w
    rejected_reward = beta * (pi_rejected - ref_rejected)  # implicit reward of y_l
    margin = chosen_reward - rejected_reward
    return {
        "loss": -F.logsigmoid(margin).mean(),
        "margin": margin.detach(),
        "chosen_reward": chosen_reward.detach(),
        "rejected_reward": rejected_reward.detach(),
        "accuracy": (margin > 0).float().mean().detach(),
    }
Listing 13The implicit rewards are log-ratios against the reference. The margin is their difference.

Each log-ratio asks one question: did the policy raise or lower this answer, compared with where it started? We multiply by beta, take chosen minus rejected, and pass the margin through -logsigmoid. At the first step policy and reference are the same model, so both ratios are about 0, the margin is about 0, and the loss is ln 2 to four digits. Any other first value means a bug.

The standard loss needs a reference model. A full second copy of SmolVLM costs about 1 GB. We avoid it in two ways.

First, the reference never changes, so we score every training pair once and keep the numbers. Second, we train a LoRA adapter, whose zero initial state means a fresh adapter leaves the model exactly at the reference.

def reference_logprobs(model, processor, pairs: list[PreferencePair], batch_pairs: int = 8,
                       device="cpu") -> tuple[torch.Tensor, torch.Tensor]:
    """Score every pair once with the frozen starting model.

    The reference never changes, so precomputing it removes the second model
    from memory and halves the forward passes during training.
    """
    model.eval()
    chosen, rejected = [], []
    for s in range(0, len(pairs), batch_pairs):
        c, r = pair_logprobs(model, pair_batch(processor, pairs[s: s + batch_pairs]).to(device))
        chosen.append(c.cpu())
        rejected.append(r.cpu())
    return torch.cat(chosen), torch.cat(rejected)
Listing 14Score the frozen starting model once, then keep two numbers per pair.

Compare this with a trusted implementation, TRL 1.17.1. Its default loss line in DPOTrainer is -F.logsigmoid(self.beta * delta_score), which is the same as ours. It also accepts a PEFT model and disables the adapter to get the reference, as our lora_disabled can.

One difference matters here. TRL has a precompute_ref_log_probs option, but it raises an error on vision datasets, because it processes images on the fly.

Our pairs are small and synthetic, so scoring them once is cheap. We write the loss by hand so nothing is hidden, not because the library is wrong.

TheoryHow LoRA changes a model without rewriting it
class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int = 16, alpha: int = 32):
        super().__init__()
        self.base = base
        self.r, self.scale = r, alpha / r
        self.lora_A = nn.Parameter(torch.empty(r, base.in_features, device=base.weight.device))
        self.lora_B = nn.Parameter(torch.zeros(base.out_features, r, device=base.weight.device))
        nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))  # same init as PEFT
        self.enabled = True

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        out = self.base(x)
        if self.enabled:
            out = out + (x @ self.lora_A.T @ self.lora_B.T) * self.scale
        return out
Listing 15B starts at zero, so a fresh adapter is an exact no-op. A test checks this, and another compares against PEFT.

Here is one training step, from the script. The pair indices select both the batch and its stored reference values.

    for step in range(args.steps):
        idx = order[(torch.arange(args.pairs) + step * args.pairs) % len(train)]
        batch = pair_batch(proc, [train[int(i)] for i in idx]).to(device)
        pi_c, pi_r = pair_logprobs(model, batch)
        out = dpo_loss(pi_c, pi_r, ref_c[idx].to(device), ref_r[idx].to(device), args.beta)
        opt.zero_grad(set_to_none=True)
        out["loss"].backward()
        gnorm = torch.nn.utils.clip_grad_norm_(params, 1.0)
Listing 16One DPO step. Pair indices select both the batch and its stored reference values.
$ .venv/bin/python c09-vlm-post-training/scripts/train_dpo.py --negatives balanced --steps 150
[dpo_balanced] reference scored for 600 pairs in 488s
[dpo_balanced] device=cpu trainable={'vision': 0, 'connector': 0, 'llm': 4884480, 'lm_head': 0, 'total': 4884480}
step   0 loss=0.6931 margin=+0.000 pair_acc=0.00 grad=0.64 t=5s
step  10 loss=0.6271 margin=+0.149 pair_acc=0.50 grad=0.82 t=48s
step  20 loss=0.6001 margin=+0.264 pair_acc=0.50 grad=1.24 t=90s
step  30 loss=0.5511 margin=+0.336 pair_acc=0.75 grad=1.30 t=132s
step  40 loss=0.2640 margin=+1.480 pair_acc=1.00 grad=2.02 t=173s
step  50 loss=0.2928 margin=+1.098 pair_acc=1.00 grad=1.42 t=217s
step  60 loss=0.6471 margin=+0.760 pair_acc=0.75 grad=2.78 t=261s
step  70 loss=0.3582 margin=+1.153 pair_acc=0.75 grad=2.69 t=305s
step  80 loss=0.2515 margin=+1.416 pair_acc=1.00 grad=1.31 t=352s
step  90 loss=0.1243 margin=+2.212 pair_acc=1.00 grad=0.43 t=404s
step 100 loss=0.1389 margin=+2.327 pair_acc=1.00 grad=2.57 t=458s
step 110 loss=0.4417 margin=+1.718 pair_acc=0.75 grad=3.82 t=505s
step 120 loss=0.0622 margin=+3.116 pair_acc=1.00 grad=0.25 t=555s
step 130 loss=0.5597 margin=+1.116 pair_acc=0.50 grad=5.91 t=606s
step 140 loss=0.1248 margin=+2.138 pair_acc=1.00 grad=0.60 t=653s
step 149 loss=0.2337 margin=+1.763 pair_acc=1.00 grad=1.14 t=699s

Figure 3DPO on one real held-out pair, run on the CPU. Hollow dots are the reference, which is the pretrained model. Filled dots are the policy after 150 steps. The pair is the one of five worked pairs whose margin changed most, so it is the clearest example and not a typical one. The lower panel is the real batch loss of this run.

Both runs trained for 150 steps on 4 pairs per step, on the CPU, in 699 s (balanced) and 567 s (biased). Balanced DPO raised the real-image accuracy on balanced pairs from 79.3% to 88.7%, which is 14 more pairs right out of 150. That is one seed, so read it as a direction and not as a measured effect. The batch loss fell from a mean of 0.65 over the first 10 steps to 0.22 over the last 10.

Preference accuracy on 150 held-out pairs (30 per kind), before and after 150 DPO steps. CPU: AMD EPYC 7R13, 8 threads. One seed. Computed from results/dpo_balanced.json and results/dpo_biased.json.
Trained onScored onReal imageGrey image
balanced negativesbalanced pairs79.3% to 88.7%47.3% to 56.0%
balanced negativesbiased pairs74.0% to 94.0%83.3% to 57.3%
biased negativesbalanced pairs79.3% to 84.0%47.3% to 49.3%
biased negativesbiased pairs74.0% to 96.0%83.3% to 90.0%

The figure shows something the loss hides. In all five worked pairs the log-probability of the whole chosen sentence fell, for example from −7.33 to −35.26 in the OCR pair. Most of that fall sits in the tokens that the chosen and rejected sentences share, and in the trailing period, which cancel in the margin. In the OCR pair the shared prefix The word is went from −6.38 to −32.59 of the 27.93-nat decline, while the true-answer token CAT went from −0.95 to −0.08.

The true-answer token rose in three of the five pairs (colour −0.21 to −0.07, count −5.96 to −2.93, OCR −0.95 to −0.08), stayed at about 0 in spatial, and fell only in object (−0.14 to −0.79). This is a description of five pairs, with no experiment that isolates a cause. It does not look like the failure where the true answer itself becomes less likely. It looks more like format drift, with the policy no longer starting its answer with The, which fits our untested explanation for the short-answer drop below.

Short answers got slightly worse on average, with mean accuracy falling from 58.7% to 53.3% after balanced DPO and to 52.0% after biased DPO. The 5.4-point drop is 8 of 150 questions, which is about the size of the noise on a mean, and one question is 3.3 points. By kind the pattern is mixed, with count up and object down. A likely cause is that DPO trained on full sentences while this test scores the first word of a short answer, which we did not test.

Short-answer accuracy (exact match on the first word, 30 questions per kind), before and after DPO. CPU: AMD EPYC 7R13, 8 threads. One seed. Computed from results/dpo_balanced.json and results/dpo_biased.json.
KindPretrainedAfter balanced DPOAfter biased DPO
color67%77%90%
count7%53%30%
object77%23%60%
ocr97%80%53%
spatial47%33%27%
mean59%53%52%

Checkpoint

  • The first batch has loss 0.693 and margin 0.
  • test_one_dpo_step_increases_the_margin and test_fresh_lora_is_an_exact_no_op pass.
Step 06

Check whether the preference needs the image

Goal Two judges that cannot see: a text-only probe on the dataset, and the VLM on grey images.

Nothing in the DPO loss forces the model to use the image. If the words predict the label, the cheapest way to lower the loss is to learn the words. Agrawal and colleagues showed the same effect for VQA, where models learned answer priors from biased splits. So we test for it directly, in two ways.

Judge 1: a text-only probe on the dataset

This judge never loads the model. It is a logistic regression over word counts, predicting which of two answers was chosen. Its features flip sign when the two answers swap, so it cannot learn to prefer whichever comes first.

def pair_features(vocab: Vocab, prompt: str, a: str, b: str) -> torch.Tensor:
    """phi(a) - phi(b), plus prompt-word x answer-word crosses so 'how many' can interact with '3'.

    Antisymmetric by construction: swapping a and b negates the features, so the
    probe cannot prefer whichever answer happens to be listed first.
    """
    da = vocab.bow(a) - vocab.bow(b)                       # (W,)
    cross = torch.outer(vocab.bow(prompt).clamp(max=1), da)  # (W, W)
    return torch.cat([da, cross.flatten()])
Listing 17Antisymmetric features, plus prompt-by-answer crosses. The probe has no bias term.
$ .venv/bin/python c09-vlm-post-training/scripts/blind_probe.py --train 1000 --test 500
negatives    train    test   per kind (test)
balanced     0.570   0.490   color=0.43  count=0.49  object=0.46  ocr=0.49  spatial=0.58
biased       0.912   0.914   color=1.00  count=1.00  object=1.00  ocr=0.99  spatial=0.58

On balanced pairs the probe scores 49% on held-out data, which is about chance. On biased pairs it reaches 100% for colour, count and object, and 99% for OCR. Spatial stays at 58% on both sets, because a flip of left and right has no text-only hint. The biased total is 91% only because spatial pulls it down.

Each kind has 100 held-out pairs, so a score of 58% is within about two standard errors of 50%. The probe is a single fit on one seed.

Judge 2: the VLM on a grey image

The second judge is the model itself. We replace every image with a grey square of the same size and score the same pairs. The code path is the same: we only swap the images passed to pair_batch.

def preference_accuracy(model, processor, pairs: list[PreferencePair], blind: bool = False,
                        batch_pairs: int = 8) -> dict[str, float]:
    """Fraction of pairs where log pi(chosen) > log pi(rejected).

    blind=True replaces every image with a grey square of the same size. A model
    that truly grounds its preference should fall to about 50% here.
    """
    model.eval()
    margins: dict[str, list[float]] = defaultdict(list)
    for s in range(0, len(pairs), batch_pairs):
        chunk = pairs[s: s + batch_pairs]
        images: list[Image.Image] | None = [blank_like(p.scene) for p in chunk] if blind else None
        c, r = pair_logprobs(model, pair_batch(processor, chunk, images).to(model.device))
        for p, m in zip(chunk, (c - r).tolist()):
            margins[p.kind].append(m)
    out = {k: sum(m > 0 for m in v) / len(v) for k, v in margins.items()}
    every = [m for v in margins.values() for m in v]
    out["mean"] = sum(m > 0 for m in every) / len(every)
    out["mean_margin"] = sum(every) / len(every)
    return out
Listing 18The blind path differs by one line: the image.

Figure 4Preference accuracy with and without visual evidence. The orange dashed line is 50%, which is where any blind scorer lands on a balanced set. The text-only probe uses 500 held-out pairs, 100 per kind. The VLM stages use 150 held-out pairs, 30 per kind, from the two CPU DPO runs. All stages are real results from one seed.

The VLM stages of the figure come from the two CPU DPO runs. The pretrained model scores 79.3% on balanced pairs with the real image and 47.3% with a grey one. That 47.3% matches the 50% of a blind scorer, and the gap above it is evidence that the model reads the pixels.

The shortcut shows up in one place. On biased pairs with a grey image, the pretrained model already scores 83.3%, because the wrong values are easy to reject from words alone. Biased DPO raised that to 90.0%, and balanced DPO lowered it to 57.3%. The gap exceeds the binomial noise of 150 pairs, but the two numbers come from two different training runs, and seed-to-seed variance is unmeasured.

Even the 57.3% hides a surviving shortcut. Per kind it is colour 50.0%, count 100%, object 30.0%, OCR 53.3% and spatial 53.3%, so the count pairs are still all answered correctly without the image. This is why a blind score should be read per kind and not only in total.

The effect on balanced pairs with the real image is weaker. The balanced run scores 88.7% and the biased run 84.0%. That gap is 7 pairs of 150, so one seed cannot show it is real. We read it as the direction we expected, and not as a measurement.

Checkpoint

  • test_text_probe_sees_bias_but_not_balance passes.
  • You would now run this probe before any preference training, because it costs seconds and needs no GPU.
Step 07

Write and test visual reward functions

Goal Small tested functions from prediction and ground truth to a number in [0, 1], one per visual task.

A reward is a specification. It should be short enough to read at once and tested like any other function. We write one for each skill in the plan.

def exact_match(pred: str, gold: str) -> float:
    """R = 1[normalize(y) == normalize(y*)]."""
    return float(normalize(pred) == normalize(gold))
Listing 19VQA: exact match after normalising case, punctuation, articles and number words.
def box_iou(a: Box, b: Box) -> float:
    """Intersection over union of two axis-aligned boxes."""
    ix0, iy0 = max(a[0], b[0]), max(a[1], b[1])
    ix1, iy1 = min(a[2], b[2]), min(a[3], b[3])
    inter = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
    union = box_area(a) + box_area(b) - inter
    return inter / union if union > 0 else 0.0
Listing 20Boxes: intersection over union.
def mask_dice(pred: np.ndarray, gold: np.ndarray) -> float:
    """2|P ∩ G| / (|P| + |G|). Dice = 2 IoU / (1 + IoU), so it is always >= IoU."""
    pred, gold = pred.astype(bool), gold.astype(bool)
    total = pred.sum() + gold.sum()
    return 1.0 if total == 0 else float(2 * np.logical_and(pred, gold).sum() / total)
Listing 21Masks: Dice, which is always at least IoU.
def anls(pred: str, golds: str | list[str], tau: float = 0.5) -> float:
    """Average Normalized Levenshtein Similarity (DocVQA). Similarity below 1 - tau scores 0."""
    golds = [golds] if isinstance(golds, str) else golds
    best = 0.0
    p = " ".join(pred.lower().split())
    for g in golds:
        g = " ".join(g.lower().split())
        nl = levenshtein(p, g) / max(1, len(p), len(g))
        best = max(best, 1 - nl if nl < tau else 0.0)
    return best
Listing 22OCR: ANLS. Similarity below 0.5 is cut to zero.
def field_accuracy(pred_json: str, gold: dict[str, str]) -> float:
    """Fraction of gold fields whose value matches exactly after normalisation.

    Invalid JSON scores 0, and extra keys earn nothing: the model cannot pad its
    way to reward.
    """
    try:
        pred = json.loads(pred_json)
    except (json.JSONDecodeError, TypeError):
        return 0.0
    if not isinstance(pred, dict) or not gold:
        return 0.0
    hits = sum(normalize(str(pred.get(k, ""))) == normalize(str(v)) for k, v in gold.items())
    return hits / len(gold)
Listing 23Structured extraction: fraction of gold fields that match. Extra keys earn nothing.
Visual reward functions
TaskFunctionPrediction typeKey property
VQAexact_matchstrAll or nothing. No gradient of quality.
Boxbox_rewardstr, parsed to 4 numbersIoU, and 0 if unparseable, so format is part of the task.
Maskmask_iou, mask_dice(H, W) boolDice = 2 IoU / (1 + IoU).
OCRanls, cerstrRewards near-misses. ANLS caps garbage at 0.
Structuredfield_accuracyJSON strInvalid JSON scores 0. Extra keys add nothing.

We also write two deliberately weak rewards for step 10. center_in_box pays if the gold centre lies inside the predicted box. caption_recall pays for each true item mentioned.

Before training on any reward, audit it with hand-written bad answers. This costs nothing.

$ .venv/bin/python c09-vlm-post-training/scripts/reward_audit.py
task: box (gold = 120 200 220 300 on a 512 canvas)
  answer                      center_in_box     iou
  120 200 220 300                      1.00   1.000
  130 210 230 310                      1.00   0.681
  0 0 512 512                          1.00   0.038
  the box is here                      0.00   0.000

task: list colours (truth = red, blue)
  answer                              recall      f1
  red and blue                          1.00    1.00
  red                                   0.50    0.67
  red, blue, green, yellow, purple      1.00    0.57
  blue, green                           0.50    0.50

task: count (truth = 3)
  answer                      contains   exact
  3                               1.00    1.00
  three.                          1.00    1.00
  1 2 3 4 5                       1.00    0.00
  4                               0.00    0.00

Drag the blue box below. Then press the whole-image preset, which is the third row of the first table.

IoU0
Dice of boxes0
Weak: centre in box0

Figure 5IoU against a weak reward. The green box and dot are the gold box and its centre. Drag the blue box to move it, and drag its square corner to resize it, or focus the corner and use the arrow keys. A tiny box at the centre also scores full marks on the weak reward. Only IoU penalises both kinds of cheating.

Checkpoint

  • All nine tests in tests/test_rewards.py pass.
  • The audit table shows a whole-image box scoring 1.00 on the weak reward and 0.038 on IoU.
Step 08

Build visual GRPO

Goal G sampled answers per image, rewards from the scene, relative advantages, one policy update.

GRPO needs no value model. For each image and prompt it samples G answers and compares them with each other. The method comes from DeepSeekMath, and the theory post covers why it works. We only add the image.

Derivation inHow reinforcement learning teaches models to reason
def group_advantages(rewards: torch.Tensor, eps: float = 1e-4, scale_by_std: bool = True) -> torch.Tensor:
    """rewards (P, G) -> advantages (P, G).

    Each answer is compared only with the other answers to the SAME image. A
    group where all G answers score the same has zero advantage everywhere: it
    teaches nothing, however good or bad the answers are.
    """
    centered = rewards - rewards.mean(dim=1, keepdim=True)
    if not scale_by_std:  # Dr. GRPO drops the std to avoid up-weighting near-uniform groups
        return centered
    return centered / (rewards.std(dim=1, keepdim=True) + eps)
Listing 24Each answer is compared only with others for the same image. We keep the optional std scale, and Dr. GRPO's variant without it.

Rollouts are sampled at temperature 1 with no top-k or top-p, so that we sample the policy we then differentiate. Every row in a group shares one image, so the fast path from step 4 pays off here most.

def sample_group(model, processor, prompt: PromptInputs, group_size: int, max_new_tokens: int = 16,
                 temperature: float = 1.0, top_p: float = 1.0) -> Rollouts:
    """G sampled answers for one image. temperature=1.0, top_p=1.0 samples the policy itself."""
    eou, pad = end_of_utterance_id(processor), processor.tokenizer.pad_token_id
    p = prompt.to(model.device)
    out = model.generate(input_ids=p.input_ids, attention_mask=torch.ones_like(p.input_ids),
                         pixel_values=p.pixel_values, do_sample=True, temperature=temperature, top_p=top_p,
                         top_k=0, num_return_sequences=group_size, max_new_tokens=max_new_tokens,
                         eos_token_id=eou, pad_token_id=pad)
    comp = out[:, p.input_ids.shape[1]:].cpu()                       # (G, L)
    is_eou = comp == eou
    # length = first end_of_utterance (inclusive), or L if the model never stopped
    first = torch.where(is_eou.any(1), is_eou.float().argmax(1) + 1, torch.full((len(comp),), comp.shape[1]))
    comp = comp.masked_fill(torch.arange(comp.shape[1]) >= first[:, None], pad)
    texts = processor.batch_decode(comp, skip_special_tokens=True)
    return Rollouts(p.input_ids[0].cpu(), p.pixel_values.cpu(), comp, first, texts)
Listing 25num_return_sequences gives G samples for one image. Everything after the first end_of_utterance becomes padding.
def grpo_loss(logp: torch.Tensor, old_logp: torch.Tensor, adv: torch.Tensor, mask: torch.Tensor,
              clip_eps: float = 0.2, ref_logp: torch.Tensor | None = None, beta: float = 0.0) -> torch.Tensor:
    """Clipped policy-gradient loss averaged over all completion tokens.

    logp, old_logp, ref_logp, mask: (B, T-1) per token. adv: (B,), one value per rollout,
    broadcast to every token of that rollout. With one update per batch,
    old_logp == logp.detach(), the ratio is 1, and the gradient is A * grad log pi.
    """
    ratio = torch.exp(logp - old_logp)
    a = adv[:, None]
    per_token = -torch.min(ratio * a, ratio.clamp(1 - clip_eps, 1 + clip_eps) * a)
    if ref_logp is not None and beta > 0:
        # k3 estimator of KL(pi || ref): unbiased, always >= 0
        d = ref_logp - logp
        per_token = per_token + beta * (torch.exp(d) - d - 1)
    return (per_token * mask).sum() / mask.sum().clamp_min(1)
Listing 26The clipped objective. With one update per batch the ratio is 1, so the gradient is the advantage times the score. KL to a reference is optional.
$ .venv/bin/python c09-vlm-post-training/scripts/show_rollouts.py --group 8
prompt: How many circles are there? Answer with a number.   truth: 1
rollout tokens reward    adv  text
      0      3    0.0  -0.35  ' 2'
      1      3    1.0  +2.47  ' 1'
      2      3    0.0  -0.35  ' 2'
      3      3    0.0  -0.35  ' 2'
      4      3    0.0  -0.35  ' 2'
      5      3    0.0  -0.35  ' 2'
      6      9    0.0  -0.35  ' 1\nAnswer: 1.'
      7      3    0.0  -0.35  ' 3'

prompt: How many circles are there? Answer with a number.   truth: 1
rollout tokens reward    adv  text
      0      3    0.0  -0.72  ' 2'
      1      3    0.0  -0.72  ' 3'
      2      3    1.0  +1.21  ' 1'
      3      3    0.0  -0.72  ' 3'
      4      3    1.0  +1.21  ' 1'
      5      3    0.0  -0.72  ' 2'
      6      3    0.0  -0.72  ' 2'
      7      3    1.0  +1.21  ' 1'

prompt: How many circles are there? Answer with a number.   truth: 3
rollout tokens reward    adv  text
      0      3    0.0  +0.00  ' 5'
      1      3    0.0  +0.00  ' 5'
      2      3    0.0  +0.00  ' 5'
      3      3    0.0  +0.00  ' 5'
      4      3    0.0  +0.00  ' 5'
      5      3    0.0  +0.00  ' 5'
      6      3    0.0  +0.00  ' 5'
      7      3    0.0  +0.00  ' 5'

one group as a batch
input_ids       torch.Size([8, 89])
attention_mask  torch.Size([8, 89])
labels          torch.Size([8, 89])
image_index     torch.Size([8])
pixel_values    torch.Size([1, 1, 3, 512, 512])
answer tokens per row: [3, 3, 3, 3, 3, 3, 3, 3]

Read the third group. All eight samples are wrong and identical, so every advantage is zero. Nothing is learned from that image, however bad the answers are.

Now read rollout 6 of the first group. It starts with the right number, but it scores 0, because exact_match compares the whole answer and the model kept talking. So this reward also teaches the model to stop. That is what we want here, but it is a choice the reward makes for us.

Figure 6One real GRPO group for one synthetic image, from show_rollouts.py, run on 8 threads of an AMD EPYC 7R13. Rollouts appear, the scene scores them, the group mean and standard deviation become advantages, and the advantages decide which tokens move up or down.
Shapes in one GRPO step (P = 4 images, G = 8 rollouts)
TensorShapeMeaning
completions(G, L)Sampled ids per image, padded after the stop token.
rewards(P, G) = (4, 8)One number per rollout.
advantages(P, G) → (32,)Zero mean within each image.
input_ids(32, T)Prompts plus completions, right padded.
pixel_values(4, 1, 3, 512, 512)Four images, not 32.
logp, mask(32, T − 1)Per token. Each advantage is broadcast along its row.

One training step, from the script. It is short because the pieces already exist.

        # 1) rollouts: G samples per image from the current policy
        model.eval()
        groups = [sample_group(model, proc, encode_prompt(proc, render(ex.scene), ex.prompt), args.group,
                               max_new_tokens=args.max_new_tokens, temperature=args.temperature)
                  for ex in batch_ex]
        # 2) verifiable rewards, read off the scene
        rewards = torch.tensor([[REWARDS[args.reward](t, ex) for t in g.texts] for g, ex in zip(groups, batch_ex)])
        strict_r = torch.tensor([[REWARDS[strict](t, ex) for t in g.texts] for g, ex in zip(groups, batch_ex)])
        # 3) group-relative advantages: (P, G) -> (P*G,)
        adv = group_advantages(rewards).flatten().to(device)
        # 4) one on-policy update
        model.train()
        batch = rollout_batch(groups, pad).to(device)
        logp, mask = policy_token_logprobs(model, batch)
        loss = grpo_loss(logp, logp.detach(), adv, mask.float())
        opt.zero_grad(set_to_none=True)
Listing 27One visual GRPO step. We also log a strict reward, even when training on a weak one.

Checkpoint

  • test_group_advantages_are_relative_within_each_image and test_on_policy_grpo_gradient_is_advantage_times_score pass.
  • A flat group gives zero advantage in your own printout.
Step 09

Ask whether RL improved perception or reasoning

Goal The same GRPO run three times, with different parts allowed to learn, and tests that separate seeing from counting.

Counting is SmolVLM’s weakest skill here, so it is the task with the most room to move. We run GRPO on it with exact-match reward, three times. The seed and the data are the same. Only the trainable set changes, and the devices do not all match: the first two runs used an H100 and the third used the CPU.

def configure_trainable(model: nn.Module, mode: str, r: int = 16, alpha: int = 32) -> dict[str, int]:
    """Freeze everything, then open up the parts `mode` names. Returns trainable counts per part."""
    if mode not in MODES:
        raise ValueError(f"mode must be one of {MODES}")
    for p in model.parameters():
        p.requires_grad_(False)
    add_lora(model, TEXT_LINEARS, r, alpha)
    if mode == "all":
        add_lora(model, VISION_LINEARS, r, alpha)
    if mode in ("projector+llm", "all"):
        for p in model.model.connector.parameters():
            p.requires_grad_(True)
    for n, p in model.named_parameters():
        if "lora_" in n:
            p.requires_grad_(True)
    return trainable_counts(model)
Listing 28Freeze everything, then open up one part at a time. A test checks that image features cannot change when the vision encoder and connector are frozen.
$ .venv/bin/python c09-vlm-post-training/scripts/train_grpo.py --freeze llm --steps 60 --eval both
$ .venv/bin/python c09-vlm-post-training/scripts/train_grpo.py --freeze projector+llm --steps 60
$ .venv/bin/python c09-vlm-post-training/scripts/train_grpo.py --freeze all --steps 60

An accuracy gain alone does not separate perception from reasoning. So we measure three things after each run.

def text_count_accuracy(model, processor, items: list[tuple[Scene, Question]]) -> float:
    """Counting from a written list of objects, with a grey image.

    No perception is needed here: the objects are spelled out in the prompt.
    If RL lifts this score, it improved counting in language, not seeing.
    """
    model.eval()
    hits = []
    for scene, q in items:
        out = generate(model, processor, blank_like(scene), describe(scene) + " " + q.short_prompt(), max_new_tokens=6)[0]
        hits.append(exact_match(first_word(out), q.answer))
    return sum(hits) / len(hits)
Listing 29The control for reasoning: the same counting question with the objects written in the prompt and a grey image.
def probe_accuracy(xtr, ytr, xte, yte) -> float:
    """Ridge regression to the count of each shape; one hit per shape whose count rounds to the truth."""
    mu, sd, ym = xtr.mean(0), xtr.std(0) + 1e-6, ytr.mean(0)  # ym is the intercept: centred features have none
    xtr, xte = (xtr - mu) / sd, (xte - mu) / sd
    w = torch.linalg.solve(xtr.T @ xtr + 10.0 * torch.eye(xtr.shape[1]), xtr.T @ (ytr - ym))
    return float((((xte @ w) + ym).round() == yte).float().mean())
Listing 30The control for perception: ridge regression from image features to per-shape counts. The mean count is the intercept, because the features are centred.

A first version of this probe had no intercept. It scored 0.000 on features that held the answer, because the centred features give predictions of count minus the mean count, which run from -1.3 to +1.7, so rounding never matches. A score of exactly zero is a bug and not a finding.

The fix is the ym term in the listing, and tests/test_probe.py checks one case that is readable and one that is not. Every probe number in this post comes from the fixed script.

Figure 7The freeze ablation. Left: which parts train, with real trainable counts. Right: real held-out accuracy before and after 60 GRPO steps on counting, using 100 images for the first group, 60 for the second and 120 questions for the last. The title names the device of each run. It is one experiment with a hardware footnote and one seed, not a controlled comparison.
[grpo_count_exact_llm] device=cuda trainable={'vision': 0, 'connector': 0, 'llm': 4884480, 'lm_head': 0, 'total': 4884480}
before {'count': 0.08, 'other': {'color': 0.7, 'object': 0.7666666666666667, 'spatial': 0.6, 'ocr': 1.0, 'mean': 0.7666666666666666}, 'text_count': 0.0}
step   0 reward=0.094 strict=0.094 len=3.2 flat_groups=0.75 t=2s | ' 5'
step  30 reward=0.469 strict=0.469 len=3.0 flat_groups=0.50 t=46s | ' 1'
step  59 reward=0.656 strict=0.656 len=3.3 flat_groups=0.50 t=88s | ' 2'
after {'count': 0.6, 'other': {'color': 0.9333333333333333, 'object': 0.7333333333333333, 'spatial': 0.7333333333333333, 'ocr': 1.0, 'mean': 0.85}, 'text_count': 0.5}
[grpo_count_exact_projector_llm] device=cuda trainable={'vision': 0, 'connector': 7077888, 'llm': 4884480, 'lm_head': 0, 'total': 11962368}
step   0 reward=0.094 strict=0.094 len=3.2 flat_groups=0.75 t=5s | ' 5'
step  30 reward=0.750 strict=0.750 len=3.9 flat_groups=1.00 t=86s | ' 1.'
step  59 reward=0.500 strict=0.500 len=3.9 flat_groups=1.00 t=159s | ' 1.'
after {'count': 0.55, 'other': {'color': 0.9, 'object': 0.6666666666666666, 'spatial': 0.7333333333333333, 'ocr': 1.0, 'mean': 0.825}, 'text_count': 0.0}
[grpo_count_exact_all] device=cpu trainable={'vision': 2654208, 'connector': 7077888, 'llm': 4884480, 'lm_head': 0, 'total': 14616576}
step   0 reward=0.094 strict=0.094 len=3.0 flat_groups=0.75 t=17s | ' 5'
step  30 reward=0.219 strict=0.219 len=4.0 flat_groups=0.50 t=456s | ' 2.'
step  59 reward=0.469 strict=0.469 len=3.0 flat_groups=0.75 t=934s | ' Two.'
after {'count': 0.52, 'other': {'color': 0.8666666666666667, 'object': 0.6666666666666666, 'spatial': 0.5333333333333333, 'ocr': 1.0, 'mean': 0.7666666666666666}, 'text_count': 0.0}
features                               per-shape count accuracy
pretrained                                                0.995
grpo_count_exact_llm                                      0.995
grpo_count_exact_projector_llm                            0.995
grpo_count_exact_all                                      0.990

One more run needs no model. It prints how often each answer occurs in the held-out counting questions and in the training images, so a counting score can be read against the best constant answer.

$ .venv/bin/python c09-vlm-post-training/scripts/majority_baseline.py
held-out counting questions (100, seed 12345): n=100  '1': 55, '2': 34, '3': 11  | best constant answer '1' scores 0.550
training images, all 60 steps (240): n=240  '1': 119, '2': 80, '3': 37, '4': 4  | best constant answer '1' scores 0.496
training images, first 8 steps (32): n=32  '1': 22, '2': 7, '3': 2, '4': 1  | best constant answer '1' scores 0.688
training images, last 8 steps (32): n=32  '1': 11, '2': 15, '3': 6  | best constant answer '2' scores 0.469
Counting with an exact-match reward, 60 GRPO steps, 4 images by 8 rollouts per step. Held-out sets: 100 counting questions, 60 written-list questions, 120 questions on the other four kinds. One seed. The pretrained row was measured once, on the H100, in the LLM-only run: the other two JSON files hold before: null, so the 8%, 0% and 77% in their cells assume it, including for the CPU run. The first row is the share of held-out answers that are 1, from results/majority_baseline.txt. Computed from results/grpo_count_exact_*.json, results/majority_baseline.txt and results/perception_probe.json.
TrainableParametersRan onCount from pixelsCount from a written list (grey image)Other four kinds, meanPerception probe
Always answer 1 (no model)0no model55.0%not applicablenot applicablenot applicable
Pretrained0H1008%0%76.7%99.5%
LLM LoRA only4.9MH1008% to 60%0% to 50%76.7% to 85.0%99.5%
Connector + LLM LoRA12.0MH1008% to 55%0% to 0%76.7% to 82.5%99.5%
Vision LoRA + connector + LLM LoRA14.6MCPU8% to 52%0% to 0%76.7% to 76.7%99.0%

Read the rows as one experiment with hardware footnotes. The first two runs used an H100 and the third used the CPU, the sampling streams differ across devices, and there is one seed. The pretrained values in all three rows were measured once, on the H100, in the LLM-only run, because the other two JSON files hold before: null.

The held-out counting questions are not balanced. Of the 100, 55 have the answer 1, so always answering 1 scores 55.0% with no model at all. All three runs end near that rate, at 60%, 55% and 52%. So we cannot call any of them a counting gain on the held-out score alone.

The connector plus LLM run most likely collapsed to a constant answer of 1. Its training reward over the last 8 steps, 0.344, equals the share of 1 answers among the last 32 training images (11 of 32). Its groups were flat from about step 6 (52 of the 54 steps after it), and the logged sample for each of the 4 images in steps 46 to 59 was 1. or One.. Its held-out 55% is the majority rate and not a counting gain.

Only the LLM-only run has evidence above the constant baseline. Its last-8 training reward is 0.645, against 0.469 for the best constant answer, which is 2, on the same 32 images. Its held-out score of 60% against 55% is within the noise of 100 questions. The pretrained 8% is below any constant guess because the model writes out-of-range numbers ( 5 at step 0), so much of the rise is learning the answer range and prior.

Training reward and held-out accuracy are not directly comparable. Training reward is whole-text exact match with 12 new tokens, while the held-out score is the first word with 6 new tokens. An output such as 1\nAnswer: 1. scores 0 in training and 1 in evaluation. We saved no per-item predictions, so none of this could be checked per question.

What the training logs show. Training reward is the mean over the first and last 8 steps. A flat group is one image whose 8 rollouts all got the same reward, so its advantages are zero. The first row is the share of 1 answers among the training images of those steps. On the last 32 images the best constant answer is 2, at 0.469. Computed from results/grpo_count_exact_*.json and results/majority_baseline.txt.
TrainableRan onTraining rewardFlat groups (fraction)Train time
Always answer 1 (no model)no model0.69 to 0.34not applicablenot applicable
LLM LoRA onlyH1000.14 to 0.640.66 to 0.3488 s
Connector + LLM LoRAH1000.39 to 0.340.72 to 1.00159 s
Vision LoRA + connector + LLM LoRACPU0.09 to 0.550.91 to 0.84934 s

The written-list control rose from 0% to 50% only in the LLM-only run, and the other two stayed at 0%. The pretrained 0% is mostly a scoring artefact: the model answers in sentences such as There are 2 squares., and the first-word scorer gives any There are N ... a 0 even when N is right. In a spot check of 12 of the 60 items on the CPU, which is not saved in results/, 8 answers began with There are, 4 were other sentences, and none scored.

The written-list set is also skewed, with 38 of its 60 answers equal to 1. So the 50% may be counting from words, answer format or the prior, and we did not separate them.

Counting reward also changed the other four kinds, with the mean going from 76.7% to 85.0%, 82.5% and 76.7%. The 8.3-point rise in the LLM-only run is 10 of 120 questions, about the size of the noise on a mean, and the CPU run shows no change. Colour rose from 70.0% to 93.3% in the LLM-only run, which is 7 of 30. A likely cause is a shift in answer format, such as stopping after one word, which we did not test.

The perception probe is at its ceiling. It scores 99.5% on the pretrained features, and 99.5%, 99.5% and 99.0% after the three runs. With 600 scored shape counts, 99.0% and 99.5% differ by three counts, which is noise. So the probe cannot show that RL improved the features, and we do not claim it did.

What the probe does show is that per-shape counts were linearly readable from the pretrained features, while the model’s own counting started at 8%. The LLM-only run cannot change the vision tower or the connector by construction, yet it ends at about the same held-out score as the runs that can. That does not separate counting from learning the answer range and prior, and this probe does not either.

Checkpoint

  • test_freeze_modes_control_what_moves passes for all three modes.
  • results/grpo_count_exact_*.json and results/perception_probe.json hold your own numbers.
Step 10

Hack the reward on purpose

Goal Train on a weak reward, watch how the policy responds, and build the monitors that catch it.

The prompt is List the colors of the shapes in the image. The weak reward is recall: the fraction of true colours mentioned. A caption that names every colour earns full marks. Hallucinated colours cost nothing, which links this step back to the start of the tutorial.

def caption_recall(text: str, true_items: set[str], vocabulary: list[str]) -> float:
    """A WEAK reward: fraction of true items mentioned. Mentioning everything maximises it."""
    if not true_items:
        return 0.0
    return len(mentioned(text, vocabulary) & true_items) / len(true_items)
Listing 31The weak reward. Nothing penalises naming a colour that is not there.
def caption_f1(text: str, true_items: set[str], vocabulary: list[str]) -> float:
    """The fixed reward: F1 of mentioned vs true items. Hallucinated mentions cost precision."""
    said = mentioned(text, vocabulary)
    hit = len(said & true_items)
    if hit == 0:
        return 0.0
    precision, recall = hit / len(said), hit / len(true_items)
    return 2 * precision * recall / (precision + recall)
Listing 32The fix. A hallucinated mention costs precision.

The monitors are small. We count the colours named, the colours named that are not in the image, the answer length, and a strict reward we do not train on. We log them on every step, whatever the training reward is.

def caption_stats(text: str, ex: RLExample) -> dict[str, float]:
    """Monitors for the caption task: how many colours named, how many were not in the image."""
    said = mentioned(text, COLOR_VOCAB)
    return {"n_colors": len(said), "hallucinated": len(said - ex.truth),
            "f1": caption_f1(text, ex.truth, COLOR_VOCAB), "recall": caption_recall(text, ex.truth, COLOR_VOCAB)}
Listing 33Monitors. The training reward cannot see them, so they cannot be gamed by accident.
$ .venv/bin/python c09-vlm-post-training/scripts/train_grpo.py --task caption --reward color_recall --steps 60 --max-new-tokens 24 --eval both
$ .venv/bin/python c09-vlm-post-training/scripts/train_grpo.py --task caption --reward color_f1 --steps 60 --max-new-tokens 24

Figure 8A run trained on the weak recall reward. Left: weak reward against honest F1. Right: colours named against colours that were not in the image. Curves are moving averages of 8 steps, with 32 rollouts per step. Both runs used 8 threads of an AMD EPYC 7R13.
[grpo_caption_color_recall_llm] device=cpu trainable={'vision': 0, 'connector': 0, 'llm': 4884480, 'lm_head': 0, 'total': 4884480}
before {'n_colors': 1.9, 'hallucinated': 0.06, 'f1': 0.7649523809523809, 'recall': 0.7416666666666667}
step   0 reward=0.698 strict=0.682 len=16.4 flat_groups=0.00 colors=1.84 halluc=0.16 t=18s | ' Blue, Yellow.'
step  30 reward=0.979 strict=0.767 len=18.0 flat_groups=0.75 colors=3.84 halluc=1.66 t=496s | ' Blue, green, gray, blue, green, gray, blue, green, pink, gray, blue, green,'
step  59 reward=1.000 strict=0.686 len=21.4 flat_groups=1.00 colors=5.44 halluc=2.94 t=1014s | ' Blue, pink, red, green, yellow, yellow, red, yellow, red, green, blue, yellow'
after {'n_colors': 5.46, 'hallucinated': 2.98, 'f1': 0.7034155844155844, 'recall': 1.0}
[grpo_caption_color_f1_llm] device=cpu trainable={'vision': 0, 'connector': 0, 'llm': 4884480, 'lm_head': 0, 'total': 4884480}
step   0 reward=0.682 strict=0.682 len=16.4 flat_groups=0.00 colors=1.84 halluc=0.16 t=21s | ' Blue, Yellow.'
step  30 reward=0.950 strict=0.950 len=8.2 flat_groups=1.00 colors=2.00 halluc=0.00 t=472s | ' Blue, Green, Blue.'
step  59 reward=1.000 strict=1.000 len=10.8 flat_groups=1.00 colors=2.50 halluc=0.00 t=860s | ' Blue, blue, red, red.'
after {'n_colors': 2.48, 'hallucinated': 0.0, 'f1': 1.0, 'recall': 1.0}
Caption task, 60 GRPO steps, CPU: AMD EPYC 7R13, 8 threads. Left four columns: 50 held-out scenes after training. Right two: training logs, mean of the first 8 and last 8 steps. One seed. The before row was measured once, in the recall run. Computed from results/grpo_caption_color_recall_llm.json and results/grpo_caption_color_f1_llm.json.
RunColours named per answerColours not in the image per answerRecallF1Training reward, first 8 to last 8 stepsHonest F1 monitor, first 8 to last 8 steps
Before training1.900.060.7420.765not applicablenot applicable
Trained on recall (weak)5.462.981.0000.7030.88 to 1.000.85 to 0.63
Trained on F12.480.001.0001.0000.84 to 1.000.84 to 1.00

The weak reward was gamed. Trained on recall, the policy reached recall 1.00 by naming 5.46 colours per answer, and 2.98 of them were not in the image. Its honest F1 on 50 held-out scenes fell from 0.765 to 0.703. In training, the honest F1 monitor fell from 0.85 to 0.63 while the training reward rose from 0.88 to 1.00.

The F1 reward did not show this. It reached F1 1.00 with 0.00 colours not in the image, and 2.48 colours named per answer. One line in the reward closed the exploit. That is a result about this reward and this task, and not a general claim about reward design.

Each run is one seed, scored on 50 scenes with four possible colours. By the last 8 steps nearly every group was flat, 1.00 for the recall run and 0.97 for the F1 run, because the reward was saturated. So the runs stopped learning because there was nothing left to push on. The F1 run reaching exactly 1.00 also shows the task is easy once the reward is right, so it says little about harder rewards.

Checkpoint

  • Your log shows colors= and halluc= next to the reward.
  • You can name, for each reward in this post, one output that games it.

The training modes compared

Rows are the post-training runs we did. Columns are the aspects this post introduced. Read across a row to see what a run could change and what it actually changed. Then read down the “can it use a shortcut” column: that is what you need to check first.

Computed from results/. CPU is an AMD EPYC 7R13 with 8 threads. H100 is an NVIDIA H100 80GB HBM3. The three counting runs ran on different hardware, so read them as one experiment with a footnote.
RunWhat learnsTraining signalCan it use a shortcut?Check firstResult on held-out data (one seed, small sets)Train time, hardware
DPO, balanced negativesDecoder LoRA, 4.88MPreference pairsNo. Text carries no hint.Grey-image accuracy on balanced pairs, near 50%Real image, balanced pairs 79% to 89%. Grey image, balanced pairs 47% to 56%. Grey image, biased pairs 83% to 57%.12 min, CPU
DPO, biased negativesDecoder LoRA, 4.88MPreference pairsYes. Words predict the label.Text-only probe, before trainingReal image, balanced pairs 79% to 84%. Grey image, balanced pairs 47% to 49%. Grey image, biased pairs 83% to 90%.9 min, CPU
GRPO, LLM onlyDecoder LoRA, 4.88MExact count, from the sceneYes. An answer prior or a constant answer (55 of 100 held-out answers are 1).Always answering 1, then counting from a written listPixels 8% to 60% (always answering 1 scores 55%). Written list 0% to 50%. Flat groups in the last 8 steps: 0.34.1.5 min, H100
GRPO, connector + LLMDecoder LoRA and connector, 11.96MExact count, from the sceneYes. A constant answer: this run most likely collapsed to always 1.Always answering 1, then the perception probePixels 8% to 55% (always answering 1 scores 55%). Written list 0% to 0%. Flat groups in the last 8 steps: 1.00.2.7 min, H100
GRPO, all threeDecoder, vision and connector LoRA, 14.62MExact count, from the sceneYes. An answer prior or a constant answer.Always answering 1, then the perception probePixels 8% to 52% (always answering 1 scores 55%). Written list 0% to 0%. Flat groups in the last 8 steps: 0.84.15.6 min, CPU
GRPO, recall rewardDecoder LoRA, 4.88MColour recall, weakYes. Naming more colours pays.Colours named, colours not in the imageF1 0.765 to 0.703. Colours not in the image, per answer: 0.06 to 2.98.17 min, CPU
GRPO, F1 rewardDecoder LoRA, 4.88MColour F1Less. A false colour costs precision.Colours named, colours not in the imageF1 0.765 to 1.000. Colours not in the image, per answer: 0.06 to 0.00.14 min, CPU

Run everything

The final folder, and every command that produced a number in this post. scripts/run_all.sh runs them in order and writes logs and JSON to results/. It also writes results/run_all.log, which records the hardware and the seconds of each run.

c09-vlm-post-training/ final tree
c09-vlm-post-training/
├── README.md                 # how to run everything, results table
├── conftest.py
├── vlmalign/
│   ├── scenes.py             # synthetic images with exact facts
│   ├── tasks.py              # questions and sentence templates
│   ├── preference.py         # hallucination negatives, balanced and biased
│   ├── model.py              # SmolVLM loading, prompts, answers
│   ├── logprobs.py           # batches, encode-once path, sequence log-probs
│   ├── dpo.py                # image-conditioned DPO loss and pair batches
│   ├── blind.py              # text-only preference probe
│   ├── rewards.py            # exact match, IoU, Dice, CER, ANLS, field accuracy
│   ├── rl_tasks.py           # RL tasks and reward registry
│   ├── grpo.py               # rollouts, relative advantages, clipped loss
│   ├── lora.py               # a minimal LoRA
│   ├── freeze.py             # the three freeze modes
│   ├── evaluate.py           # VQA and preference accuracy, real or grey image
│   ├── tiny.py               # tiny random Idefics3 for offline tests
│   └── device.py
├── scripts/
│   ├── show_pairs.py         # pairs and one batch, tensor by tensor
│   ├── blind_probe.py        # the text-only check
│   ├── reward_audit.py       # hand-written answers against every reward
│   ├── show_rollouts.py      # one GRPO group printed
│   ├── train_dpo.py
│   ├── train_grpo.py         # freeze ablation and reward hacking
│   ├── perception_probe.py   # did image features change?
│   └── run_all.sh
├── benchmarks/
│   └── bench_encode_once.py
├── results/                  # real logs and JSON
└── tests/
    ├── test_rewards.py
    ├── test_data.py
    ├── test_logprobs_dpo.py
    ├── test_lora_freeze.py
    ├── test_grpo.py
    └── test_smolvlm_network.py
$ .venv/bin/python -m pytest c09-vlm-post-training -m "not slow and not gpu and not network"
$ .venv/bin/python -m pytest c09-vlm-post-training -m network
$ c09-vlm-post-training/scripts/run_all.sh
37 passed, 4 deselected in 12.25s
4 passed, 37 deselected in 21.87s

The offline tests use a tiny random model with SmolVLM’s layout, so they need no weights. The 4 network tests load the real processor and weights, and one of them is also marked slow. On CUDA, pick_device selects the GPU automatically.

# One line per run. Hardware: CPU = AMD EPYC 7R13, 8 threads, shared with other jobs. H100 = NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2.
# "wall" includes model loading, evaluation and, for GPU runs, time spent waiting for a free GPU. Training seconds are in each run's JSON.
exit 0 show_pairs            CPU   wall 20s
exit 0 blind_probe           CPU   wall 9s
exit 0 reward_audit          CPU   wall 0s
exit 0 show_rollouts         CPU   wall 30s
exit 0 bench_encode_once     CPU   wall 412s
exit 0 dpo_balanced          CPU   wall 2692s   train 699s
exit 0 dpo_biased            CPU   wall 2431s   train 567s
exit 0 grpo_llm              H100  wall 363s    train 88s
exit 0 grpo_projector        H100  wall 1263s   train 159s
exit 0 grpo_all              CPU   wall 1197s   train 934s
exit 0 hack_recall           CPU   wall 1201s   train 1014s
exit 0 hack_f1               CPU   wall 939s    train 860s
exit 0 perception_probe      CPU   wall 1706s   (a first run had no intercept in the probe and is discarded)
exit 0 bench_encode_once_gpu H100  wall not recorded

This ledger names the device of each run. The two H100 counting runs and the GPU benchmark are the only GPU results in this post. The wall time of a GPU run includes time spent waiting for a free GPU, so the training seconds in each run’s JSON are the honest cost.

Key insights and nuances

Exercises

  1. Grounding with GRPOHard Add a task that asks for the box of a named object, using box_reward. Train it on the weak center_in_box reward and then on IoU. Log mean box area as the monitor.
    Hint

    SmolVLM rarely writes four numbers unprompted. Give the format in the prompt, and count how many rollouts parse at all. If none parse, every group is flat, and nothing is learned.

  2. Measure the shortcut per kindMedium Make only OCR biased in wrong_value and leave the rest balanced. Train DPO and report grey-image accuracy per kind. Does the shortcut stay in OCR, or does it reach the other kinds?
  3. Make the shapes smallerMedium Make object sizes smaller in sample_scene and rerun the perception probe on the pretrained features. Find the size at which counting stops being linearly readable.
    Hint

    A 16-pixel patch merges into one token per 64 pixels. Objects smaller than that share a token.

  4. Switch off the std scaleEasy Pass scale_by_std=False to group_advantages and compare counting after 60 steps. Then compare the fraction of groups with one correct answer at each setting, to see how Dr. GRPO changes the weight of those groups.
  5. A better shortcut meterHard Replace the bag-of-words probe with a small sequence model trained on the same pairs. Can a stronger blind judge beat 50% on the balanced set? If it does, you have found a leak in the generator, and you should fix it.

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Metrics