Coding tutorial · Build it from scratch

Train a Real VLM

We take a pretrained vision encoder, a pretrained language model and a random projector, and train them in stages on six tasks, measuring each task and checking what the language model forgets.

Multimodal trainingTask mixturesVLM evaluation

A staged training system for a vision-language model: one sample format for six tasks, a loss mask you can inspect, freeze presets with per-module learning rates, four task mixtures, text replay with a forgetting check, tiling, packing, LoRA on any module, grounding tokens, and a metric for every task.

Time
About 2 hours to read and run the tests. Training time depends on your hardware, and each run below states its own.
Hardware
Tests run on any CPU. The results here come from two machines: an 8-thread AMD EPYC 7R13 CPU and one NVIDIA H100 80GB HBM3 GPU. Every result names the one that produced it.
You need
Python 3.10+, PyTorch, transformers, Pillow, matplotlib, pytest. C7 is optional.
Package
vlmtrain
Final repo tree c08-vlm-training/
c08-vlm-training/
├── README.md                # how to run everything, results table
├── conftest.py
├── configs/
│   ├── stage1_align.yaml    # projector only, captions only
│   └── stage2_mixture.yaml  # six tasks, 10% text replay
├── vlmtrain/
│   ├── synth/
│   │   ├── shapes.py        # scenes with exact geometry
│   │   ├── text.py          # rendered text and invoices
│   │   └── charts.py        # bar charts with known values
│   ├── data.py              # the unified sample format
│   ├── processor.py         # chat template, image tokens, loss mask
│   ├── tokenizer.py         # adds image and location tokens
│   ├── metrics.py           # exact match, CER, WER, ANLS, IoU
│   ├── evaluate.py          # one metric family per task
│   ├── freeze.py            # who trains, in each stage
│   ├── optim.py             # per-module learning rates
│   ├── train.py             # the staged trainer
│   ├── mixture.py           # four mixture strategies
│   ├── replay.py            # text replay, forgetting check
│   ├── resolution.py        # resize, pad, tile
│   ├── packing.py           # budgets and block-causal masks
│   ├── lora.py              # LoRA on any module
│   ├── grounding.py         # points, boxes, masks as tokens
│   ├── c07_adapter.py       # the only file that touches C7
│   ├── model.py             # standalone model, same contract
│   └── device.py
├── scripts/
│   ├── train.py             # one stage from a YAML config
│   ├── run_all.sh           # every CPU run behind the numbers
│   ├── run_gpu.sh           # the H100 runs, one job per GPU
│   ├── evaluate.py          # a checkpoint against two controls
│   ├── inspect_batch.py     # prints what is in the tensors
│   ├── param_report.py      # trainable parameters per preset
│   ├── break_it.py          # each failure, on purpose
│   ├── multi_image.py       # several images in one example
│   └── show_samples.py
├── benchmarks/
│   ├── bench_packing.py
│   └── bench_resolution.py
├── results/                 # real logs and JSON; gpu/ holds the H100 runs
└── tests/                   # one test file per module

The plan

You have a pretrained vision encoder, a pretrained language model and a projector full of random numbers. What should train first, on which data, and how would you know that one task improved without another getting worse?

In C7 we assembled this model. It runs, and it answers nonsense, because nothing connects what the encoder sees to what the language model reads. This tutorial builds the system that fixes that.

We work in stages. First the projector learns alone on captions. Then the language model joins, on a mixture of six tasks. Along the way we add the parts that a single training loop does not show you: how often each task is drawn, whether the language model forgets plain text, what an image costs in tokens, and which metric each task needs.

All the data is synthetic. We draw every image ourselves, so every caption, count, bounding box and chart value is exact. No label is estimated.

That also means the results here say whether the training system works. They do not say how well a model would do on real photographs.

The runs are also smaller than we planned, and every number is one seed. We planned a 3,000-step Stage 1, an 8,000-step Stage 2 and 2,000-step comparisons. A first 8,000-step attempt reached step 1,400 in 34 minutes on an oversubscribed server, so we stopped it and kept none of its output.

The table gives what was run instead. Every result table below repeats its own run size and hardware.

The size of every run. Computed from the config field of the result files in results/ and results/gpu/. The plan column is the setting we first intended for the H100 runs. One seed per run.
RunHardwareSteps x batchTest samples per taskPlan
Stage 1 alignmentNVIDIA H100 80GB HBM33,000 x 322563,000 steps; 256 samples
Stage 2 main run and no-replay runNVIDIA H100 80GB HBM31,000 x 161288,000 steps; 256 samples
Comparisons: freeze, mixture, LoRA, resolution, groundingNVIDIA H100 80GB HBM3250 x 161282,000 steps; 256 samples
Longer grounding-only runsNVIDIA H100 80GB HBM31,500 x 16128added after the 250-step runs
Stage 1 alignmentAMD EPYC 7R13, 8 threads600 x 864–
Stage 2 main run and no-replay runAMD EPYC 7R13, 8 threads500 x 448 (64 in the controls)–
Comparisons: freeze, mixture, resolution, groundingAMD EPYC 7R13, 8 threads200 x 448–
Comparisons: LoRAAMD EPYC 7R13, 8 threads150 x 448–

Three more limits apply to everything below. Both machines were shared with other jobs while the runs went, so only the quality numbers compare across rows, and the seconds per step do not. With 128 test samples, a score near 0.5 has a standard error of about 0.04, and with 64 samples about 0.06. Treat smaller differences between rows as noise.

Clone the repo once. Every command below runs from its root.

$ 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]"

The trainer needs three things from a model: submodules named .vision, .projector and .lm, and C7’s forward and generate. It uses C7’s package when ../c07-vlm is present. Otherwise it falls back to vlmtrain/model.py, the same contract in one file, so this folder also runs alone. Only one file touches C7’s internals.

def _finish(model, c07_processor, strategy: str, max_tiles: int, bins: int):
    """Grow the vocabulary for the location tokens and wrap the model with our unified-sample processor."""
    from .processor import TinyVLMProcessor
    from .tokenizer import add_vlm_tokens

    tok = add_vlm_tokens(c07_processor.tokenizer, bins)
    # C7 pads the embedding matrix to a multiple of 64, so the real model already has spare rows.
    if model.lm.get_input_embeddings().num_embeddings < len(tok):
        model.lm.resize_token_embeddings(len(tok), mean_resizing=True)
    proc = TinyVLMProcessor(tok, model.config.image_seq_len, model.config.vision_config.image_size,
                            strategy, max_tiles)
    return tok, model.train(), proc
Listing 1The one seam with C7. The tokenizer grows for the location tokens, and the embedding matrix grows only if C7’s spare rows are not enough.
Step 01

Give every task one sample format

Goal Captions, questions, OCR, documents, charts and grounding all become the same dict, so nothing downstream branches on the task.

A real training system reads dozens of datasets. If each one reaches the trainer in its own shape, every later feature has to be written once per dataset. So we fix one format first: a list of images and a list of chat messages.

def user(text_: str, n_images: int = 1) -> dict:
    return {"role": "user", "content": [{"type": "image"}] * n_images + [{"type": "text", "text": text_}]}


def assistant(text_: str) -> dict:
    return {"role": "assistant", "content": [{"type": "text", "text": text_}]}


def sample(task: str, images: list, question: str, answer: str, **meta) -> dict:
    return {"task": task, "images": images, "messages": [user(question, len(images)), assistant(answer)],
            "meta": {"answer": answer, **meta}}


def validate(s: dict) -> None:
    """Fail loudly on the two mistakes that silently ruin VLM training data."""
    n_slots = sum(c.get("type") == "image" for m in s["messages"] for c in _content(m))
    if n_slots != len(s["images"]):
        raise ValueError(f"{n_slots} image slots in messages but {len(s['images'])} images")
    roles = [m["role"] for m in s["messages"]]
    if roles != ["text"] and (not roles or roles[-1] != "assistant"):
        raise ValueError(f"a training sample must end with an assistant turn, got roles {roles}")
Listing 2The unified sample, and the check that guards it. A mismatch between image slots and images is the mistake that silently ruins VLM data, so it fails loudly here.

Two details matter. sample keeps a meta dict that holds whatever the metric for this task will need, such as a bounding box for grounding. And validate runs on every sample, because a wrong sample is far cheaper to catch here than after hours of training.

Each sample is a pure function of its task, split and index. The same index always gives the same pixels, so a run can resume without saving any data, and train and test can never overlap.

def rng_for(task: str, split: str, index: int) -> random.Random:
    """Sample `index` of a task is a pure function of (task, split, index): reproducible and resumable."""
    return random.Random(zlib.crc32(f"{task}/{split}/{index}".encode()))
Listing 3A seed derived from the sample’s name. There is nothing to download and nothing to shuffle on disk.
def gen_vqa(rng: random.Random, **_) -> dict:
    img, objs = shapes.make_scene(rng, 1, 5)
    q, a = shapes.vqa_pair(rng, objs)
    return sample("vqa", [img], q + " Answer with one word.", a)
Listing 4One generator. It draws a scene, computes the answer from what it drew, and returns the unified dict.

Here is sample 0 of every task, rendered by those generators. Pick a task to see its image and its dict.


          
Image
Tiles
Visual tokens
Target tokens
Figure 1Sample 0 of each task, drawn by make_example. The token counts come from results/logs/inspect_batch.txt. Every task reaches the processor in the same shape, and only the images and the text differ.

Real corpora are not the same size. Captions are plentiful, and documents and charts are scarce. We copy that imbalance with nominal corpus sizes, because that is what mixture strategies have to deal with in step 6.

TASKS = ("caption", "vqa", "ocr", "doc", "chart", "grounding")

# Nominal corpus sizes. They mimic the imbalance of real mixtures (captions are plentiful,
# documents and charts are scarce), and they are what "proportional" mixing is proportional to.
TASK_SIZES = {"caption": 40_000, "vqa": 20_000, "ocr": 8_000, "doc": 1_000, "chart": 2_000, "grounding": 4_000}
Listing 5The six tasks. The sizes are a stand-in for a real imbalance of 40 to 1.

Checkpoint

  • Calling make_example("vqa", 0) twice gives identical pixels.
  • scripts/show_samples.py saves one image per task.
Step 02

Turn a sample into tensors

Goal Expand images into tokens, mark the tokens the model is graded on, and see exactly what one batch contains.

The processor is where most VLM bugs live. It has three jobs. It writes the chat template.

It replaces each image with one <image> token per visual token. And it decides which tokens count towards the loss.

    def encode(self, sample: dict, for_generation: bool = False) -> Encoded:
        """One sample -> token ids, labels and pixel tiles. Generation drops the final answer."""
        messages = sample["messages"]
        if for_generation:
            messages = messages[:-1]
        pix = [preprocess(img, self.strategy, self.tile, self.max_tiles) for img in sample["images"]]
        tiles = [p.shape[0] for p in pix]
        image_iter = iter(tiles)
        ids: list[int] = []
        labels: list[int] = []

        def add(tokens: list[int], supervised: bool) -> None:
            ids.extend(tokens)
            labels.extend(tokens if supervised else [IGNORE] * len(tokens))

        for m in messages:
            if m["role"] == "text":  # plain-text replay: no template, every token is a target
                add(self._ids(m["content"][0]["text"]) + [self.eos_id], supervised=True)
                continue
            is_answer = m["role"] == "assistant"
            add(self._ids(f"{IM_START}{m['role']}\n"), supervised=False)
            for c in m["content"]:
                if c["type"] == "image":
                    add([self.image_token_id] * (next(image_iter) * self.tokens_per_tile), supervised=False)
                else:
                    add(self._ids(c["text"]), supervised=is_answer)
            add([self.eos_id], supervised=is_answer)
            add(self._ids("\n"), supervised=False)
        if for_generation:
            add(self._ids(f"{IM_START}assistant\n"), supervised=False)
        if len(ids) > self.max_length:
            # Truncating would cut visual tokens loose from their tiles, so refuse instead.
            raise ValueError(f"sample has {len(ids)} tokens > max_length {self.max_length}")
        return Encoded(ids, labels, torch.cat(pix) if pix else None, tiles, sample["task"], sample.get("meta", {}))
Listing 6One sample to token ids and labels. The highlighted lines are the whole logic of the loss mask.

Read the add helper first. Every token goes into ids. Its label is either the token itself or -100, which PyTorch’s cross-entropy skips. Only the assistant’s answer is supervised, along with its closing <|im_end|>. That last token is what teaches the model to stop.

Text replay is the exception. A "text" message has no chat wrapper, and every token is a target, exactly like language-model pretraining.

Now run it on one sample of each task, plus one text passage. The script needs no model weights.

$ .venv/bin/python c08-vlm-training/scripts/inspect_batch.py
task             image  tiles  visual  text  target  answer
caption        224x224      1      49    21       5  Two blue triangles.
vqa            224x224      1      49    23       2  yellow
ocr            336x224      3     147    22       3  yellow honey
doc            448x448      5     245    29      11  2026-07-15
chart          224x224      1      49    19       2  2
grounding      224x224      1      49    25       5  <loc_3><loc_8><loc_9><loc_14>
text                 -      0       0    34      34  (all tokens)

input_ids      (7, 274)
attention_mask (7, 274) padding share 60.3%
labels         (7, 274) supervised share 3.2%
pixel_values   (12, 3, 224, 224)

This output is worth reading slowly. These counts come from the tokenizer and the generators, so they do not depend on your hardware.

The batch above (B = 7 samples, N = 274 positions, 12 tiles)
TensorShapeMeaning
input_ids(7, 274)Token ids. Visual positions hold the <image> id.
attention_mask(7, 274)1 for real tokens, 0 for padding on the right.
labels(7, 274)The token itself on targets, -100 everywhere else.
pixel_values(12, 3, 224, 224)All tiles of all samples, in sequence order.

Figure 2The batch from inspect_batch.py, drawn position by position. Blue is visual tokens, grey is prompt text, orange is targets, and the hatched part is padding.

The token-by-token view of the VQA sample shows the mask directly.

One VQA sample, token by token (run-length encoded):
  '<|im_start|>' x1   -100
  'user'         x1   -100
  '\n'           x1   -100
  '<image>'      x49  -100
  'What'         x1   -100
  ' color'       x1   -100
  ' is'          x1   -100
  ' the'         x1   -100
  ' square'      x1   -100
  '?'            x1   -100
  ' Answer'      x1   -100
  ' with'        x1   -100
  ' one'         x1   -100
  ' word'        x1   -100
  '.'            x1   -100
  '<|im_end|>'   x1   -100
  '\n'           x1   -100
  '<|im_start|>' x1   -100
  'ass'          x1   -100
  'istant'       x1   -100
  '\n'           x1   -100
  'yellow'       x1   target
  '<|im_end|>'   x1   target
  '\n'           x1   -100

Checkpoint

  • inspect_batch.py prints a VQA sample with exactly two targets: the answer and <|im_end|>.
  • test_only_the_answer_and_its_end_token_are_supervised and test_visual_tokens_are_never_supervised pass.
Step 03

Choose a metric for every task

Goal Before any training, decide how each task is scored, and write each metric small enough to check by hand.

A mixed model has no single accuracy. A loss curve cannot tell you that charts improved while OCR got worse. So we write the metrics before we train.

Background inMeasuring what a VLM can do
def anls(pred: str, golds: str | list[str], tau: float = 0.5) -> float:
    """Average Normalized Levenshtein Similarity for one question (DocVQA definition).

    score = max over golds of (1 - NL) if NL < tau else 0, with NL = lev(p, g) / max(|p|, |g|)
    on lowercased, whitespace-trimmed strings. The threshold keeps a wrong answer that happens to
    share characters with the gold one from earning partial credit.
    """
    golds = [golds] if isinstance(golds, str) else golds
    p = " ".join(pred.lower().split())
    best = 0.0
    for g in golds:
        g = " ".join(g.lower().split())
        if not p and not g:
            return 1.0
        nl = levenshtein(p, g) / max(len(p), len(g))
        best = max(best, 1.0 - nl if nl < tau else 0.0)
    return best
Listing 8ANLS, the DocVQA metric. The threshold keeps an unrelated answer from earning partial credit for shared characters.
def relaxed_accuracy(pred: str, gold: str, tol: float = 0.05) -> float:
    """ChartQA relaxed accuracy: numeric answers may be off by `tol` relative error.

    Non-numeric gold answers (a category name, "yes") fall back to exact match.
    """
    g = parse_number(gold)
    if g is None:
        return exact_match(pred, gold)
    p = parse_number(pred)
    if p is None:
        return 0.0
    if g == 0:
        return float(p == 0)
    return float(abs(p - g) / abs(g) <= tol)
Listing 9ChartQA’s relaxed accuracy. Numeric answers may be off by 5%, and anything else falls back to exact match.

score maps each task to its metrics. Evaluation then greedily decodes held-out samples and averages them. It never touches the training indices, because the split is part of the seed.

def score(task: str, pred: str, meta: dict) -> dict[str, float]:
    gold = meta["answer"]
    if task in ("caption", "vqa"):
        return {"em": M.exact_match(pred, gold)}
    if task == "ocr":
        return {"cer": M.cer(pred.strip(), gold), "wer": M.wer(pred.strip(), gold), "em": M.exact_match(pred, gold)}
    if task == "doc":
        return {"anls": M.anls(pred, gold), "em": M.exact_match(pred, gold)}
    if task == "chart":
        return {"relaxed_acc": M.relaxed_accuracy(pred, gold)}
    if task == "grounding":
        w, h = meta["size"]
        if meta["kind"] == "point":
            p = G.decode_point(pred, w, h, meta["fmt"])
            return {"point_acc": 0.0 if p is None else M.point_in_box(p, meta["box"]), "parse_fail": float(p is None)}
        if meta["kind"] == "mask":
            poly = G.decode_polygon(pred, w, h, meta["fmt"])
            iou = 0.0 if poly is None else G.mask_iou(G.polygon_to_mask(poly, w, h), G.rle_to_mask(meta["rle"]))
            return {"mask_iou": iou, "parse_fail": float(poly is None)}
        box = G.decode_box(pred, w, h, meta["fmt"])
        iou = 0.0 if box is None else M.box_iou(box, meta["box"])
        return {"iou": iou, "acc@0.5": float(iou >= 0.5), "parse_fail": float(box is None)}
    raise ValueError(task)
Listing 10One metric family per task. A grounding answer that does not parse scores zero, and we count those failures separately. Boxes, points and outlines each have their own metric.

A score alone says little. A model can score well on “how many circles?” by always answering “2”. So every score we quote gets two controls. blind=True runs the same model on grey images, so a score that does not drop was never coming from the image. majority_baseline uses no model at all.

def majority_baseline(tasks: list[str], n: int = 64, n_train: int = 1000, grounding_format: str = "tokens") -> dict:
    """No model: always answer with the most common training answer of the task, then score on the test split."""
    results = {}
    for task in tasks:
        common = Counter(make_example(task, i, "train", grounding_format)["meta"]["answer"]
                         for i in range(n_train)).most_common(1)[0][0]
        sums: dict[str, float] = defaultdict(float)
        counts: dict[str, int] = defaultdict(int)
        for i in range(n):
            for k, v in score(task, common, make_example(task, i, "test", grounding_format)["meta"]).items():
                sums[k] += v
                counts[k] += 1
        results[task] = {"answer": common, **{k: sums[k] / counts[k] for k in sums}}
    return results
Listing 11The no-model control: always give the most common training answer, then score it on the test split.
What each task is scored on
TaskHeadline metricAlso recordedDirection
captionExact match–Higher is better
vqaExact match after normalising–Higher is better
ocrCERWER, exact matchLower is better
docANLSExact matchHigher is better
chartRelaxed accuracy at 5%–Higher is better
groundingAccuracy at IoU 0.5Mean IoU, point in box, mask IoU, parse failuresHigher is better

Metrics disagree with each other more than you might expect. Try a few wrong answers. The scores below are computed in your browser by a port of metrics.py.

Figure 3Five metrics on one answer. Each uses the same definitions as vlmtrain/metrics.py. CER and WER are error rates, so lower is better. They can exceed 1 when the prediction is much longer than the reference.

Checkpoint

  • You can state which metric each task uses, and which way is better.
  • test_anls, test_cer_wer, test_relaxed_accuracy and test_box_iou pass.
Step 04

Decide what trains, and how fast

Goal Name the freezing choices as presets, count what each one trains, and give each module its own learning rate.

The three modules are in very different states. The vision encoder and the language model are pretrained and fragile. The projector is new and has nothing to lose. So each needs its own treatment, and that treatment changes between stages.

def set_trainable(model: nn.Module, preset: str, vision_layers_to_train: int = 0) -> None:
    if preset not in PRESETS:
        raise ValueError(f"unknown freeze preset {preset!r}, pick one of {PRESETS}")
    on = {"align": {"projector"}, "lm": {"projector", "lm"}, "partial": {"projector", "lm"},
          "full": set(MODULES), "none": set()}[preset]
    for name in MODULES:
        getattr(model, name).requires_grad_(name in on)
    if preset == "partial":
        if vision_layers_to_train <= 0:
            raise ValueError("preset 'partial' needs vision_layers_to_train > 0")
        for layer in list(vision_layers(model))[-vision_layers_to_train:]:
            layer.requires_grad_(True)
        # The norm after the last block feeds the projector directly, so it trains with the top layers.
        for n, m in model.vision.named_modules():
            if n.endswith("post_layernorm"):
                m.requires_grad_(True)
Listing 12Five presets. Partial unfreezing takes the top k vision blocks, plus the norm that feeds the projector directly.

Learning rates follow from the same reasoning. Each module gets its own AdamW parameter group, so the ratios between modules are a deliberate choice.

def _no_decay(name: str, p: nn.Parameter) -> bool:
    # Biases and norm gains are not weights that overfit by growing. Embeddings are excluded too:
    # decoupled decay would shrink the rows of words the data never uses.
    return p.ndim < 2 or "norm" in name or "embed" in name


def param_groups(model: nn.Module, lrs: dict[str, float], weight_decay: float = 0.0) -> list[dict]:
    """Group trainable parameters by top-level module. Frozen parameters never reach the optimizer."""
    groups: dict[tuple[str, bool], dict] = {}
    for name, p in model.named_parameters():
        if not p.requires_grad:
            continue
        module = name.split(".")[0]
        if module not in MODULES:
            raise ValueError(f"parameter {name} is outside vision/projector/lm")
        key = "lora" if "lora_" in name and "lora" in lrs else module
        nd = _no_decay(name, p)
        g = groups.setdefault((key, nd), {"name": f"{key}{'/no_decay' if nd else ''}", "params": [],
                                          "lr": lrs[key], "weight_decay": 0.0 if nd else weight_decay})
        g["params"].append(p)
    return list(groups.values())
Listing 13One group per module and decay setting. Frozen parameters never reach the optimizer.
AdamW inWhat an optimizer actually does

The comment on _no_decay hides a real trap. Decoupled weight decay shrinks every weight it touches, however small its gradient is. Most of the vocabulary never appears in our synthetic tasks, so decay would slowly erode words the model already knew. We exclude embeddings from decay. Every run in this post sets weight_decay to 0.0, so the exclusion changes nothing in them. It matters once you turn decay on.

The schedule is a linear warmup and then a cosine decay. It multiplies each group’s own base rate by the same factor, so the ratios between modules hold for the whole run.

def warmup_cosine(warmup: int, total: int, min_ratio: float = 0.1):
    """LR multiplier: linear warmup to 1, cosine decay to min_ratio at `total`."""
    def f(step: int) -> float:
        if step < warmup:
            return (step + 1) / warmup
        t = min(1.0, (step - warmup) / max(1, total - warmup))
        return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * t))
    return f
Listing 14The LR multiplier, shared by all groups.

Now count what each preset trains. The numbers below are for C7’s model: SigLIP base, an MLP projector and SmolLM2-135M.

$ .venv/bin/python c08-vlm-training/scripts/param_report.py
module         trainable         total   share
vision                 0    85,797,120    0.0%
projector      2,102,400     2,102,400  100.0%
lm                     0   134,551,872    0.0%
all            2,102,400   222,451,392    0.9%

The script prints one block like this for each of eight settings: four freeze presets and four LoRA placements. The saved log lost the headings that name the blocks, so the other blocks are read from results/param_report.json.

Stage 1 trains 0.9% of the model. Parameter counts are hardware independent, and they add up by hand. The projector is 3072 × 576 + 576 weights in its first layer and 576 × 576 + 576 in its second, which gives 2,102,400. Four vision blocks at 7,087,872 each, plus 1,536 for the final norm, give the 28,353,024 of the partial top 4 entry in that file.

Choose a preset and see which blocks turn on. The block sizes and totals are read from results/param_report.json.

Trainable
Of all weights
Largest group
Learning rates
Figure 4What each freeze preset trains. Each cell is one block. Orange trains fully, blue means only LoRA factors train, and grey is frozen. The learning rates are the values used by the runs in this post.

Checkpoint

  • param_report.py prints 2,102,400 trainable parameters for align.
  • test_each_trainable_parameter_is_in_exactly_one_group and test_scheduler_keeps_the_lr_ratios pass.
Step 05

Stage 1: align the projector

Goal Write the training loop once, then use it to teach the projector alone to speak the language model’s embedding space.

This is the simplest version of the recipe, in the style of LLaVA. Both towers are frozen. Only the projector moves, and we train it on captions only. If this cannot work, nothing later will.

Why alignment comes firstTeaching language models to see

The whole recipe uses one loop. A stage is only a configuration of it.

# Stage 1: projector alignment. Vision and LM are frozen; only the 2.1M-parameter projector trains.
name: stage1_align
freeze: align
tasks: [caption]
steps: 600
batch_size: 8
lrs: {projector: 1.0e-3}
warmup: 20
ppl_passages: 0
eval_n: 64
save: true
Listing 16Stage 1 in full, with the CPU settings. The H100 run overrides steps, batch_size, warmup and eval_n. A high learning rate is safe here, because the projector has nothing pretrained to destroy.

We compute the loss ourselves rather than asking the model for it. We want a loss per sample, so we can log each task on its own, and later so that packed rows can be split back into samples.

def per_sample_loss(logits: torch.Tensor, labels: torch.Tensor, sample_index: torch.Tensor, n_samples: int):
    """Next-token cross-entropy summed per sample.

    logits (B, N, V), labels (B, N), sample_index (B, N) -> (loss_sum (S,), token_count (S,))
    Position t predicts token t+1, so logits drop the last column and labels drop the first.
    """
    tgt = labels[:, 1:]
    tok_loss = F.cross_entropy(logits[:, :-1].float().transpose(1, 2), tgt, ignore_index=IGNORE, reduction="none")
    idx = sample_index[:, 1:].reshape(-1)
    valid = (tgt.reshape(-1) != IGNORE) & (idx >= 0)
    sums = torch.zeros(n_samples, device=logits.device).index_add_(0, idx[valid], tok_loss.reshape(-1)[valid])
    ones = torch.ones(int(valid.sum()), device=logits.device)
    counts = torch.zeros(n_samples, device=logits.device).index_add_(0, idx[valid], ones)
    return sums, counts
Listing 17Next-token cross-entropy, summed per sample. Position t predicts token t + 1, so the logits drop the last column and the labels drop the first.
Shapes inside one Stage 1 step, for one 224-pixel tile
TensorShapeMeaning
pixel_values(n_tiles, 3, 224, 224)Values in [-1, 1], as SigLIP was trained.
Vision output(n_tiles, 196, 768)14 × 14 patches of 16 pixels.
Pixel shuffle(n_tiles, 49, 3072)Each 2 × 2 block of patches folded into channels.
Projector output(n_tiles, 49, 576)One language-model embedding per visual token.
Merged embeddings(B, N, 576)<image> rows replaced, in order.
logits(B, N, V)One distribution over the vocabulary per position.
loss_sum, token_count(S,), (S,)Summed loss and target count for each of S samples.

Figure 5One Stage 1 step, tensor by tensor. Grey modules are frozen and the orange module trains. On the way back, the gradient passes through the frozen language model and stops at the projector.

The step itself is short. Draw samples, build the batch, run forward, take the per-sample loss, then backward, clip and step.

    for step in range(cfg.steps):
        samples = []
        for _ in range(cfg.batch_size):
            task, i = sampler.draw()
            samples.append(replay[i] if task == "text" else make_example(task, i, "train", cfg.grounding_format))
        b = make_batch(cfg, proc, samples)
        dev = {k: b[k].to(device) for k in ("input_ids", "labels", "attention_mask", "sample_index")}
        out = model(dev["input_ids"], None if b["pixel_values"] is None else b["pixel_values"].to(device),
                    attention_mask=dev["attention_mask"],
                    position_ids=b["position_ids"].to(device) if "position_ids" in b else None)
        sums, counts = per_sample_loss(out.logits, dev["labels"], dev["sample_index"], len(b["tasks"]))
        if cfg.loss_norm == "token":
            loss = sums.sum() / counts.sum()
        else:
            loss = (sums / counts.clamp(min=1)).mean()
        opt.zero_grad(set_to_none=True)
        loss.backward()
        gnorm = torch.nn.utils.clip_grad_norm_([p for g in opt.param_groups for p in g["params"]], cfg.grad_clip)
        opt.step()
        sched.step()
Listing 18The core of the trainer. Everything else in run is logging and evaluation.

Run it. The config saves only the parameters that train, so this checkpoint holds the projector and nothing else. The first command is the CPU run. The second is the H100 run, with the overrides that run_gpu.sh sets (3,000 steps of batch 32, and 256 test samples).

$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage1_align.yaml
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh stage1_align
[stage1_align] AMD EPYC 7R13 Processor, 8 threads, loaded 0 tensors, lora on 0 linears
all            2,102,400   222,451,392    0.9%
step     1  loss 2.985  gnorm 16.49  caption=3.09  2.3s
step   100  loss 0.511  gnorm 2.19  caption=0.47  181.6s
step   200  loss 0.224  gnorm 1.70  caption=0.25  357.0s
step   300  loss 0.152  gnorm 1.68  caption=0.12  553.0s
step   400  loss 0.139  gnorm 1.21  caption=0.10  728.5s
step   500  loss 0.113  gnorm 0.74  caption=0.08  913.3s
step   600  loss 0.035  gnorm 0.68  caption=0.05  1123.2s
task       metric          value   other
caption    em              0.797   
saved 2,102,400 trainable parameters (8.0 MB) to outputs/stage1_align/
Stage 1 on tinyvlm, caption task only. Computed from results/stage1_align.json and results/gpu/stage1_align.json. The GPU run was an NVIDIA H100 80GB HBM3 with torch 2.15.0+cu132 and CUDA 13.2. One seed per row. The loss is the caption loss at the first and the last logged step.
RunHardwareSteps x batchCaption loss, first to last stepCaption exact matchTest samplesCheckpoint
CPUAMD EPYC 7R13, 8 threads600 x 83.09 to 0.050.797648.0 MB
GPUNVIDIA H100 80GB HBM33,000 x 323.26 to 0.010.9802568.0 MB

Is that score coming from the image? Run the CPU checkpoint with the two controls from step 3.

$ .venv/bin/python c08-vlm-training/scripts/evaluate.py outputs/stage1_align/trainable.safetensors --name stage1_align --tasks caption
stage1_align with real images, with grey images, and with no model. 64 held-out samples per task, AMD EPYC 7R13 Processor, 8 threads. Computed from results/eval_stage1_align.json. One seed.
TaskMetricReal imagesGrey imagesNo modelThe no-model answer
captionexact match0.7970.0000.062A purple triangle.
The first held-out answers from stage1_align, AMD EPYC 7R13 Processor, 8 threads. They are the first test samples in index order, not a selection of good or bad ones. Read from the examples field of results/stage1_align.json.
TaskQuestionTrue answerModel answer
captionDescribe the image.A red circle and a yellow triangle.A red circle and a yellow triangle.
captionWhat is in this picture?An orange triangle.An orange triangle.
captionWhat is in this picture?A purple triangle.A purple triangle.

On the CPU run, the caption loss fell from 3.09 to 0.05 over 600 steps. The projector scores 0.797 exact match on 64 held-out captions, which is 51 of them. Exact match is strict here, because one wrong colour fails a whole caption. Nothing in either tower moved, so 2.1M projector weights did all of this work.

The controls say the score comes from the image. With grey images the same checkpoint scores 0.000, and always giving the most common caption scores 0.062. We ran the controls on the CPU checkpoint only.

The H100 run is five times longer, with batches four times larger: 3,000 steps of 32 samples. It reaches 0.980 exact match on 256 held-out captions. It passes over the 40,000 nominal captions 2.4 times, so it repeats training images, and the test captions are different ones.

We did not run the grey-image control on this checkpoint. The CPU controls, on the same task and recipe, are the evidence that the score comes from the image. Each number is one seed.

Checkpoint

  • The log reports 2,102,400 trainable parameters and a falling loss.
  • outputs/stage1_align/trainable.safetensors exists, and test_save_and_load_trainable_round_trip passes.
Step 06

Mix the tasks

Goal Implement four ways to decide how often each task is drawn, and record what actually got drawn.

Stage 2 trains on six tasks at once, so every sample needs an answer to the question “which task next?” The choice is one vector of probabilities, and it decides which capabilities the model gets.

Theory inMixing data without losing capabilities
def mixture_weights(sizes: dict[str, int], strategy: str = "temperature", temperature: float = 2.0,
                    manual: dict[str, float] | None = None) -> dict[str, float]:
    """Sampling probabilities per task. They always sum to 1."""
    if strategy == "proportional":
        raw = {k: float(n) for k, n in sizes.items()}
    elif strategy == "uniform":
        raw = {k: 1.0 for k in sizes}
    elif strategy == "temperature":
        raw = {k: float(n) ** (1.0 / temperature) for k, n in sizes.items()}
    elif strategy == "manual":
        if manual is None or set(manual) != set(sizes):
            raise ValueError("manual mixing needs one weight per task")
        raw = {k: float(manual[k]) for k in sizes}
    else:
        raise ValueError(f"unknown mixture strategy {strategy!r}")
    total = sum(raw.values())
    return {k: v / total for k, v in raw.items()}
Listing 20Four strategies in one function. Temperature moves smoothly between the first two: T = 1 is proportional, and a large T approaches uniform.
Sampling probabilities from mixture_weights on the nominal corpus sizes, before any text replay. Computed from the code, not measured. The manual column weights the tasks in the order of the rows.
TaskCorpus sizeProportionalTemperature, T = 2Temperature, T = 4UniformManual (1, 1, 2, 3, 2, 3)
caption40,00053.3%35.1%25.4%16.7%8.3%
vqa20,00026.7%24.8%21.3%16.7%8.3%
ocr8,00010.7%15.7%17.0%16.7%16.7%
doc1,0001.3%5.5%10.1%16.7%25.0%
chart2,0002.7%7.8%12.0%16.7%16.7%
grounding4,0005.3%11.1%14.3%16.7%25.0%

Proportional mixing gives documents 1.3% of the draws. At that rate, the 1,000-step Stage 2 run with a batch of 16 would draw about 213 documents in 16,000 samples. Uniform fixes that, but it asks a scarce corpus to supply as many samples as an abundant one. Temperature is the usual compromise, and the config uses T = 2.

Move the sliders. Besides the probabilities, the figure shows how many passes the run makes over each corpus, because repeating a small corpus too often is how it gets memorised.

Figure 6The four strategies, ported from mixture.py. Bars show the probability of drawing each task. The right column shows epochs over each corpus. Text replay takes its share first, and the tasks split the rest in their usual ratios. The values are computed from the formula, not measured.

The sampler records every draw. Each task walks its own fixed permutation, so repeats start only after a full epoch, and the state fits in a small dict, so resuming is exact.

class MixtureSampler:
    """Draws (task, index) pairs. Each task walks its own shuffled order, so repeats only start after an epoch."""

    def __init__(self, weights: dict[str, float], sizes: dict[str, int], seed: int = 0):
        self.tasks = list(weights)
        self.probs = [weights[t] for t in self.tasks]
        self.sizes = sizes
        self.rng = random.Random(seed)
        self.cursor = Counter()
        self.counts: Counter[str] = Counter()

    def draw(self) -> tuple[str, int]:
        task = self.rng.choices(self.tasks, weights=self.probs, k=1)[0]
        size = self.sizes.get(task, 1 << 30)
        i = self.cursor[task]
        self.cursor[task] += 1
        self.counts[task] += 1
        # A cheap fixed permutation of 0..size-1: an affine map with a multiplier coprime to size.
        return task, (i * _coprime(size) + 7) % size
Listing 21The sampler. The affine map is a cheap permutation of a corpus we never have to load.

Now the runs. Each trains the same model for the same 250 steps of batch 16 on the H100, with no replay, and only the mixture changes. All four start from the same Stage 1 projector.

Because the Stage 2 config already uses T = 2, the temperature row is the vision-frozen run of step 7 (freeze_lm). The manual weights are 1, 1, 2, 3, 2 and 3 for the tasks in the order of the table.

$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh mix_uniform
# which runs, with results_dir=results/gpu out_dir=outputs/gpu added:
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=mix_uniform init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 mixture=uniform
One model, four mixtures, the same 250 steps of batch 16, no replay. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from results/gpu/mix_proportional.json, freeze_lm.json, mix_uniform.json, mix_manual.json. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Steps x batch, test samples per task
Proportional0.9610.9060.7540.0520.1090.000250 x 16, n=128
Temperature, T = 20.9530.8440.6920.1960.1170.000250 x 16, n=128
Uniform0.9610.7730.6210.2240.1250.000250 x 16, n=128
Manual0.9300.6800.6680.1730.1330.000250 x 16, n=128

The clearest difference between these four runs is VQA, and it follows the share of draws. VQA scores 0.906 with proportional mixing, where it is 26.7% of draws. It scores 0.844 at T = 2 (24.8%), 0.773 with uniform mixing (16.7%) and 0.680 with the manual weights (8.3%).

With 128 test samples, the standard error of a score near 0.8 is about 0.035. The gap between the first and last rows, 0.23, is well outside that. The gaps between neighbouring rows are not.

We read this as a statement about draws: with the budget fixed, more draws of a task gave a higher score on it. It is not a ranking of mixtures. A mixture that wins on VQA loses draws on something else.

The other tasks do not show the same pattern. Caption stays between 0.930 and 0.961. Chart stays between 0.109 and 0.133, and one test sample is 0.008.

Documents range from 0.052 to 0.224. The proportional run is the lowest of the four. It draws documents 1.3% of the time, about 53 documents in 4,000 samples, and it scores below the 0.197 that the 1,000-step main run gets on grey images.

We did not estimate the noise on a document score, and the grey-image figure comes from a different run. So we call this run the lowest of four, not clearly low, and we did not test why.

OCR error is between 0.62 and 0.75 in all four runs, far from the 0.013 that the longer main run reaches. So OCR is still early at 250 steps, and we do not rank the rows.

The grounding column is 0.000 in every run, and in every run the model produced no parsable answer (the unparsable rate is 1.000 in each results file). Every run here is a single seed, so none of these differences should be taken as a recipe.

Checkpoint

  • Every run logs both mixture_target and mixture_observed, and the two agree closely (the table in step 8 shows the main run).
  • All tests in tests/test_mixture.py pass.
Step 07

Stage 2: train on the full mixture

Goal Start from the aligned projector, unfreeze the language model, and track each task separately while comparing how much of the vision encoder should train.

Stage 2 loads the Stage 1 checkpoint and adds the language model to the trainable set. The main run keeps vision frozen. Then we ask how far to unfreeze: keep vision frozen, unfreeze its top blocks, or train everything. LoRA is a fourth answer, which step 11 builds.

# Stage 2: multimodal pretraining on a six-task mixture, starting from the Stage 1 projector.
name: stage2_main
init_from: outputs/stage1_align/trainable.safetensors
freeze: lm
steps: 500
batch_size: 4
lrs: {vision: 1.0e-6, projector: 2.0e-4, lm: 5.0e-5}
loss_norm: sample        # every sample counts once, so long replay passages cannot dominate
warmup: 20
mixture: temperature
temperature: 2.0
replay_ratio: 0.1
strategy: tile
max_tiles: 4
grounding_format: tokens
eval_n: 48
eval_every: 250
eval_n_mid: 24
ppl_passages: 64
Listing 22Stage 2, with the CPU settings of 500 steps and batch 4. The H100 runs override these (1,000 steps of batch 16 for the main run). The projector’s rate drops, because it is no longer random. Vision stays at a very low rate even in presets that train it.
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml save=true
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh stage2_main eval_stage2_main

The second command is the H100 run behind the numbers below: 1,000 steps of batch 16, 128 test samples per task and 128 perplexity passages. Its log follows. It is one of two runs in this post at this size, with the no-replay run below.

[stage2_main] NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2, loaded 4 tensors, lora on 0 linears
all          136,654,272   222,451,392   61.4%
text perplexity before: 35.32
step     1  loss 9.082  gnorm 118.96  grounding=17.15 chart=6.41 vqa=16.68 caption=0.01 ocr=10.65 text=4.19  1.7s
step   100  loss 2.217  gnorm 7.66  grounding=9.90 caption=0.02 vqa=0.42 text=3.88 ocr=4.65 chart=1.91 doc=2.67  53.9s
step   200  loss 2.557  gnorm 7.61  grounding=7.55 ocr=3.73 caption=0.02 text=3.45 vqa=0.35 chart=1.24 doc=0.92  107.8s
step   300  loss 1.779  gnorm 9.17  vqa=0.21 caption=0.01 grounding=5.22 text=3.49 ocr=2.92 chart=1.31 doc=1.86  159.5s
step   400  loss 1.065  gnorm 2.83  vqa=0.28 caption=0.01 text=3.42 doc=1.24 ocr=0.93 grounding=3.54 chart=1.53  209.5s
step   500  loss 0.387  gnorm 2.79  vqa=0.18 ocr=0.38 text=3.64 grounding=3.01 caption=0.02 doc=1.80 chart=1.15  262.8s
step   600  loss 0.523  gnorm 4.81  vqa=0.14 caption=0.01 ocr=0.27 text=3.30 doc=1.27 grounding=2.96 chart=1.09  344.2s
step   700  loss 0.643  gnorm 2.75  ocr=0.10 grounding=2.80 vqa=0.04 chart=1.05 text=3.38 caption=0.02 doc=1.13  398.9s
step   800  loss 1.098  gnorm 5.09  vqa=0.12 text=3.60 caption=0.00 doc=1.57 grounding=2.67 ocr=0.01 chart=1.04  447.4s
step   900  loss 0.608  gnorm 3.52  grounding=2.65 vqa=0.14 caption=0.02 ocr=0.03 chart=1.08 text=3.12 doc=1.43  498.2s
step  1000  loss 1.117  gnorm 3.97  caption=0.00 vqa=0.03 text=3.04 chart=1.00 grounding=2.86 doc=1.36 ocr=0.05  548.7s
task       metric          value   other
caption    em              0.930   
vqa        em              0.953   
ocr        cer             0.013   wer=0.020, em=0.969
doc        anls            0.191   em=0.023
chart      relaxed_acc     0.148   
grounding  acc@0.5         0.000   point_acc=0.069, parse_fail=0.086, iou=0.000, mask_iou=0.000
text perplexity after: 23.19 (before 35.32)
saved 136,654,272 trainable parameters (521.3 MB) to outputs/gpu/stage2_main/

The trainer logs the loss per task, not only the total. That is why we built per_sample_loss. A task that stops improving shows up here long before the final evaluation.

Figure 7Loss per task, from the log field of each result file. The buttons name the run and its hardware. Every task shares one axis, in nats per target token. Hover to read the values at one step.
The main Stage 2 run. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from results/gpu/stage2_main.json. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Text perplexity, before to afterSteps x batch, test samples per task
T = 2 mixture, 10% replay0.9300.9530.0130.1910.1480.00035.32 to 23.191,000 x 16, n=128

The same two controls again, now on all six tasks. The H100 columns come from the run above. The CPU columns come from the 500-step, batch-4 run that the config reproduces by default.

$ .venv/bin/python c08-vlm-training/scripts/evaluate.py outputs/stage2_main/trainable.safetensors --name stage2_main
The Stage 2 main run with real images, grey images and no model. GPU: NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2, 1,000 x 16, 128 test samples per task. CPU: AMD EPYC 7R13 Processor, 8 threads, 500 x 4, 64 test samples per task. Computed from results/eval_gpu_stage2_main.json and results/eval_stage2_main.json. One seed per run.
TaskMetricGPU realGPU greyGPU no modelCPU realCPU greyCPU no model
captionexact match0.9300.0230.0470.8280.0310.062
vqaexact match0.9530.2340.2500.7190.4380.281
ocrCER, lower is better0.0130.8470.8910.4690.8300.896
docANLS0.1910.1970.0310.1670.2020.016
chartrelaxed accuracy0.1480.1170.1250.1250.0310.125
groundingacc at IoU 0.50.0000.0000.0000.0000.0000.000
The main Stage 2 run evaluated twice. Step 500 uses 48 test samples per task and step 1,000 uses 128, so the second row is the less noisy one. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from the curve field of results/gpu/stage2_main.json. One seed.
Stepcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)
5000.9170.8960.1230.1860.167
1,0000.9300.9530.0130.1910.148
The first held-out answers from stage2_main, NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. They are the first test samples in index order, not a selection of good or bad ones. Read from the examples field of results/gpu/stage2_main.json.
TaskQuestionTrue answerModel answer
captionDescribe the image.A red circle and a yellow triangle.A red circle and a yellow triangle.
captionWhat is in this picture?An orange triangle.An orange triangle.
vqaHow many shapes are there? Answer with one word.55
vqaHow many green squares are there? Answer with one word.11
ocrWhat does the text in the image say?pearl oysterpearl oyster
ocrWhat does the text in the image say?square pearlsquare pearl
docWhat is the total?79.5032.50
docHow many items are on the invoice?51
chartWhat is the value of yak?51
chartWhat is the value of fox?41
groundingPoint to the green circle.<loc_17><loc_14><loc_15><loc_15>
groundingFind the red square. Give its bounding box.<loc_23><loc_15><loc_31><loc_22><loc_15><loc_15><loc_15><loc_15>

Three tasks are learned. On the H100 run, caption scores 0.930 against 0.023 on grey images, VQA scores 0.953 against 0.234, and OCR has a character error rate of 0.013 against 0.847. Of the 128 OCR answers, 96.9% are an exact match. In every one of these tasks the real-image score is far from both controls.

Two tasks are not learned, and the controls are what show it. Documents score 0.191 with real images and 0.197 with grey images, so the model answers invoice questions without reading the invoice. It gives 32.50 for a total of 79.50, and 1 for a count of 5.

Charts score 0.148, against 0.125 for always answering the most common value and 0.117 on grey images. With 128 samples the standard error of 0.148 is about 0.03, so this is not above the controls.

The training loss agrees. The chart loss fluctuates and trends from about 1.2 to about 1.05. Of the 95 logged points from step 60 on, 60 sit between 1.0 and 1.2, 28 are above 1.2 (the highest is 2.27) and 7 are below 1.0. The means of each 100 steps fall from 1.31 to 1.04.

That is about what guessing among nine values gives on a two-token answer. The digit costs ln 9, or 2.2, and the end token costs almost nothing, so the average is near 1.1. Between step 500 and step 1,000 the document and chart scores do not move, while OCR error falls from 0.123 to 0.013 (table below, with the two evaluations at different sample sizes).

A likely cause is that reading a total or a bar height out of a small rendered image is a harder skill than reading a short word, and the run drew about 800 invoices in 1,000 steps. We did not run anything that separates these explanations. Because the two scores were flat over the last 500 steps, more steps with the same recipe may not be enough. We did not test that either.

Grounding scores 0.000, with 8.6% of answers unparsable, and step 12 covers it. The CPU run, with 500 steps of batch 4, learned caption and VQA and part of OCR, and it also does not read documents or charts. A CPU row and an H100 row are different experiments.

On the 64-sample control file the CPU scores are caption 0.828, VQA 0.719 and OCR error 0.469. The table of every CPU run uses 48 samples and lists 0.812, 0.729 and 0.442 for the same checkpoint.

We cannot say that the H100 run had converged. Its OCR error is 0.123 at 48 samples at step 500 and 0.013 at 128 samples at step 1,000, which are two evaluations at different sizes.

The OCR training loss is flat over the last 300 steps (0.052, 0.030 and 0.042). The no-replay run, with the same recipe, reaches an OCR error of 0.003. A full-scale Stage 2 is not measured.

Now the freezing question. Each run below starts from the same Stage 1 projector and trains for the same 250 steps of batch 16 on the H100, with no replay. The rows compare with each other, but not with the longer main run.

$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh freeze_lm freeze_partial freeze_full
# freeze_partial and freeze_full run, with results_dir=results/gpu out_dir=outputs/gpu added:
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=freeze_partial init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 \
    freeze=partial vision_layers_to_train=4 lrs.vision=1e-5
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=freeze_full init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 freeze=full
How far to unfreeze, the same 250 steps of batch 16, no replay. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from results/gpu/freeze_lm.json, freeze_partial.json, freeze_full.json. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Steps x batch, test samples per task
Vision frozen0.9530.8440.6920.1960.1170.000250 x 16, n=128
Top 4 vision blocks train0.8980.8360.6120.1740.1330.000250 x 16, n=128
Everything trains0.9610.8280.6700.2110.1250.000250 x 16, n=128

None of the gaps between the three presets is clearly larger than noise. The largest is caption exact match for partial unfreezing: 0.898, against 0.953 and 0.961. The standard error of that difference is about 0.03, so the gap is about two standard errors. That is borderline for one seed, and we do not call it a difference.

VQA, OCR and charts sit within a few points of each other. Documents and charts stay at the reference levels from the previous table in all three of these rows.

So this experiment does not say which freezing choice is best. Unfreezing the vision tower at a low learning rate made no measurable difference within 250 steps. A likely reason is that the encoder already represents these simple scenes well, but the data here cannot say so. Finding a real difference needs longer runs, several seeds, or harder images.

The presets also differ in another way. The partial run used a vision learning rate of 1e-5 and the full run used 1e-6, a factor of ten. So the comparison mixes the number of trained layers with the learning rate, and it cannot separate them.

The cost differences are exact, though. Partial unfreezing trains 28.4M more weights than the frozen row, and full unfreezing trains 85.8M more. Peak GPU memory in these three runs was 11.6, 13.5 and 17.4 GB in float32 at batch 16 (the peak_device_mb field of the result files).

Checkpoint

  • The log prints a metric for each of the six tasks, and its first line says how many tensors were loaded from Stage 1 (4).
  • test_stage2_variants_run passes for every preset on the tiny model.
Step 08

Mix in plain text, and measure forgetting

Goal Add text-only samples to the batches, and measure whether the language model got worse at language.

When a pretrained language model trains on short visual answers, its weights drift towards those answers. Nothing in a multimodal loss notices that it can no longer write a paragraph. So we need two things: replay to resist the drift, and a measurement to see it.

Replay needs almost no new code. A text passage is one more task in the mixture, and with_replay fixes its share before the rest is split.

def with_replay(weights: dict[str, float], replay_ratio: float, name: str = "text") -> dict[str, float]:
    """Reserve `replay_ratio` of all samples for text-only replay and rescale the rest."""
    if replay_ratio <= 0:
        return dict(weights)
    out = {k: v * (1 - replay_ratio) for k, v in weights.items()}
    out[name] = replay_ratio
    return out
Listing 23Replay takes its share first. The image tasks keep their ratios to each other.

The measurement is perplexity on held-out text, before and after training. Only the language model is involved, so no image can help or hide anything. Train and test passages come from different WikiText-2 splits, so the check never sees a replayed passage. It does see the same kind of text, and the results below come back to that.

@torch.no_grad()
def perplexity(lm: torch.nn.Module, tokenizer, passages: list[str], device: torch.device,
               max_tokens: int = 128, batch_size: int = 16) -> float:
    """Token-weighted perplexity of a causal LM on plain text (the language side of the VLM only)."""
    was_training = lm.training
    lm.eval()
    nll, count = 0.0, 0
    for i in range(0, len(passages), batch_size):
        enc = tokenizer(passages[i:i + batch_size], return_tensors="pt", padding=True, truncation=True,
                        max_length=max_tokens).to(device)
        logits = lm(input_ids=enc.input_ids, attention_mask=enc.attention_mask).logits.float()
        target = enc.input_ids[:, 1:].masked_fill(enc.attention_mask[:, 1:] == 0, -100)
        nll += F.cross_entropy(logits[:, :-1].transpose(1, 2), target, ignore_index=-100, reduction="sum").item()
        count += int((target != -100).sum())
    lm.train(was_training)
    return math.exp(nll / count)
Listing 24Token-weighted perplexity. The function sums the loss and the count over all batches and divides at the end, so a short batch is not over-counted.

Now the choice we flagged in step 2. A replay passage has about 96 target tokens, and a VQA answer has 2. With a token mean, 10% of the samples can dominate the loss. loss_norm controls this: token averages over all targets, and sample averages the per-sample means, so every sample counts once.

The H100 comparison is the main run against the same run with no replay. The CPU also has a short run with the token mean.

$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh stage2_noreplay
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=stage2_noreplay replay_ratio=0
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=stage2_replay_tokenmean steps=100 eval_every=0 loss_norm=token
What replay costs and what it saves, the same 1,000 steps of batch 16. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from results/gpu/stage2_main.json, stage2_noreplay.json. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Text perplexity, before to afterSteps x batch, test samples per task
10% replay0.9300.9530.0130.1910.1480.00035.32 to 23.191,000 x 16, n=128
No replay0.9530.9450.0030.1970.1020.00035.32 to 49.851,000 x 16, n=128
Perplexity of the language model on held-out WikiText-2 test passages, before and after Stage 2. Computed from the JSON files in results/gpu/ and results/. One seed per row.
RunHardwareSteps x batch, passagesPerplexity beforePerplexity afterChange
10% replayNVIDIA H100 80GB HBM31,000 x 16, 12835.3223.19-12.13
No replayNVIDIA H100 80GB HBM31,000 x 16, 12835.3249.85+14.53
10% replayAMD EPYC 7R13, 8 threads500 x 4, 6438.3728.78-9.58
No replayAMD EPYC 7R13, 8 threads500 x 4, 6438.3745.10+6.73
10% replay, token-mean lossAMD EPYC 7R13, 8 threads100 x 4, 6438.3731.61-6.76
stage2_main, NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2, 1,000 x 16. Computed from results/gpu/stage2_main.json. The last column counts supervised tokens.
TaskTarget share of samplesObserved share of samplesShare of supervised tokens
caption31.6%31.5%22.7%
vqa22.3%22.2%3.1%
ocr14.1%14.4%3.5%
doc5.0%4.9%1.9%
chart7.1%7.2%1.0%
grounding10.0%10.1%4.4%
text10.0%9.8%63.4%

Without replay, perplexity on held-out WikiText-2 rises from 35.32 to 49.85 after 1,000 steps, an increase of 14.5. That is the forgetting. The CPU run, with 500 steps of batch 4, moves in the same direction, from 38.37 to 45.10. The before values differ because the H100 test uses 128 passages and the CPU test uses 64.

With replay, perplexity falls, from 35.32 to 23.19. Most of that fall is not retention. The replay passages are WikiText-2 training text and the check uses WikiText-2 test text, a different split of the same kind of writing. So replay also adapts the model to the test domain.

The no-replay row is the real measure of forgetting, and the replay row shows that replay works against it. We did not measure how much of the fall is kept ability and how much is adaptation.

Task scores with and without replay are within noise of each other: caption 0.930 against 0.953, VQA 0.953 against 0.945, and OCR error 0.013 against 0.003. At this scale replay cost no measurable task quality. One seed cannot rule out a small cost.

Replay is 10% of the samples and 63.4% of the supervised tokens (the table above). A passage has up to 96 target tokens, and the answers in the batch of step 2 have 2 to 11. That is why the main config averages the loss per sample.

The token-mean run on the CPU lasted only 100 steps, so it is not a fair comparison with the 500-step runs. This post does not measure what loss_norm=token costs. We also measured only perplexity, so whether instruction following survived is not measured.

Checkpoint

  • The log prints perplexity before and after, and mixture_observed shows about 10% text.
  • test_replay_reaches_the_target_share and test_text_replay_is_fully_supervised_and_has_no_pixels pass.
Step 09

Handle images of any size

Goal Turn any image into square tiles, and see what that choice costs in tokens.

The encoder only accepts 224-pixel squares. A 448-pixel invoice has body text about 20 pixels tall. Squash it into one tile and that text becomes about 10 pixels, and reading it may no longer be possible. So we compare three strategies.

The token budget inThe cost of a picture
def tiles_for(img: Image.Image, strategy: str = "tile", tile: int = 224, max_tiles: int = 4) -> list[Image.Image]:
    """The list of tile images the encoder will see, in the order their tokens appear in the sequence."""
    if strategy == "resize":
        return [img.resize((tile, tile), Image.BICUBIC)]
    if strategy == "pad":
        side = max(img.size)
        canvas = Image.new("RGB", (side, side), (255, 255, 255))
        canvas.paste(img, ((side - img.width) // 2, (side - img.height) // 2))
        return [canvas.resize((tile, tile), Image.BICUBIC)]
    if strategy != "tile":
        raise ValueError(f"unknown resolution strategy {strategy!r}")
    rows, cols = choose_grid(img.width, img.height, tile, max_tiles)
    if rows * cols == 1:
        return [img.resize((tile, tile), Image.BICUBIC)]
    big = img.resize((cols * tile, rows * tile), Image.BICUBIC)
    crops = [big.crop((c * tile, r * tile, (c + 1) * tile, (r + 1) * tile)) for r in range(rows) for c in range(cols)]
    # The thumbnail comes first: a low-resolution view of the whole layout, then the detail tiles.
    return [img.resize((tile, tile), Image.BICUBIC)] + crops
Listing 25Three strategies. Tiling also adds a low-resolution thumbnail first, so the model keeps a view of the whole layout.

Tiling must first choose a grid. It takes the grid whose aspect ratio is closest to the image, and it breaks ties by pixel count, so that a small image is not blown up into many tiles.

def choose_grid(width: int, height: int, tile: int, max_tiles: int) -> tuple[int, int]:
    """(rows, cols) with rows*cols <= max_tiles whose aspect ratio is closest to the image's.

    Ties go to the grid whose pixel count is closest to the image's, so a small image is not blown
    up into many tiles just because the ratios match (InternVL uses the same tie-break idea).
    """
    best, best_key = (1, 1), None
    target = math.log(width / height)
    for rows in range(1, max_tiles + 1):
        for cols in range(1, max_tiles // rows + 1):
            ratio_err = abs(math.log(cols / rows) - target)
            area_err = abs(math.log(rows * cols * tile * tile / (width * height)))
            key = (round(ratio_err, 6), area_err)
            if best_key is None or key < best_key:
                best, best_key = (rows, cols), key
    return best
Listing 26The grid choice. Rounding the ratio error is what makes ties possible.

Grid
Tiles
Visual tokens
Stretch
Figure 8How one image becomes tiles, ported from resolution.py. The token count is tiles times 49, and it is exact for any size. Change the image and watch the budget. The processor refuses any sample over 1,024 tokens.
A 448 by 448 document at each strategy
Strategypixel_valuesVisual tokensWhat is lost
resize(1, 3, 224, 224)49Half the resolution. Aspect ratio if the image is not square.
pad(1, 3, 224, 224)49The same resolution loss, plus pixels spent on padding if the image is not square.
tile(5, 3, 224, 224)245Nothing in the crops. The cost is five times the tokens.

Next, measure what this costs and what it buys.

$ .venv/bin/python c08-vlm-training/benchmarks/bench_resolution.py
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh res_tile res_resize
# res_resize runs, with results_dir=results/gpu out_dir=outputs/gpu added:
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=res_resize init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 "tasks=[doc,ocr]" strategy=resize

The token counts do not depend on hardware. The encoder timings do, and the CPU log is below.

image                 resize     pad    tile   (visual tokens)
scene 224x224             49      49      49
ocr 336x224               49      49     147
ocr 448x160               49      49     196
ocr 448x224               49      49     147
document 448x448          49      49     245

Encoding one 448x448 document on AMD EPYC 7R13 Processor, 8 threads
strategy    tiles  ms/image
resize          1        82
tile            5       346

The same benchmark on the H100 prints the same token counts. Its timing lines are these.

Encoding one 448x448 document on NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2
strategy    tiles  ms/image
resize          1        10
tile            5         7
Tiling against one squashed tile, documents and OCR only, no replay. Computed from results/gpu/res_tile.json, res_resize.json and results/res_tile.json, res_resize.json. One seed per row.
Runocr (CER, lower is better)doc (ANLS)Steps x batch, test samples per task, hardware
Tile0.0550.188250 x 16, n=128, NVIDIA H100 80GB HBM3
Resize0.0450.185250 x 16, n=128, NVIDIA H100 80GB HBM3
Tile0.3470.268200 x 4, n=48, AMD EPYC 7R13, 8 threads
Resize0.2820.226200 x 4, n=48, AMD EPYC 7R13, 8 threads

Tiling did not help in these runs. On the H100, OCR error is 0.055 with tiles and 0.045 with one resized tile, and document ANLS is 0.188 and 0.185. Both runs read the short OCR words to a similar degree.

Neither run probably reads documents, because both document scores sit near the grey-image level of 0.197. That level comes from the main run, since we ran no grey-image control on these two. The tile idea is about reading small text on the 448-pixel invoice. This test cannot show an advantage or a loss there.

On the CPU, with 200 steps of batch 4 and 48 test samples, tiles gave OCR error 0.347 and document ANLS 0.268, and one resized tile gave 0.282 and 0.226. Gaps of this size are within noise at 48 samples.

What tiling costs is exact: an invoice takes 245 visual tokens against 49. Encoding one invoice took 82 ms with one resized tile and 346 ms with 5 tiles on the CPU. On the H100 the same call took 10 ms and 7 ms. That is a single call on a shared machine, so the order of the two is noise.

Checkpoint

  • n_tiles(448, 448) is 5, and a 224 by 224 image stays at 1.
  • test_choose_grid, test_tile_counts_for_a_document and test_tiles_cut_in_row_major_order pass.
Step 10

Stop paying for padding

Goal Fit several samples into one row of a fixed token budget, in a way that computes exactly what separate samples would.

Tiling made lengths vary a lot. Our batch had rows from 34 to 274 tokens, and 60.3% of its positions were padding. Sorting by length helps. Packing goes further: it concatenates short samples into one row.

The first part is bin packing. First-fit decreasing is a simple and well-known heuristic: take the longest sample first and put it in the first row with room.

def first_fit_decreasing(lengths: list[int], budget: int) -> list[list[int]]:
    """Bin packing: longest samples first, each into the first row with room. Returns index lists."""
    order = sorted(range(len(lengths)), key=lambda i: -lengths[i])
    rows: list[list[int]] = []
    room: list[int] = []
    for i in order:
        if lengths[i] > budget:
            raise ValueError(f"sample {i} has {lengths[i]} tokens > budget {budget}")
        for r, free in enumerate(room):
            if lengths[i] <= free:
                rows[r].append(i)
                room[r] -= lengths[i]
                break
        else:
            rows.append([i])
            room.append(budget - lengths[i])
    return rows
Listing 27First-fit decreasing, over token lengths.

Rows
Positions
Wasted
Attention pairs
Figure 9First-fit decreasing on the seven sample lengths from inspect_batch.py. The readout compares packed rows with the padded batch: 7 rows of 274, which is 1,918 positions and 525,532 attention pairs. These values are computed from the lengths, not timed.

Placing samples in one row is the easy part. Three things must hold, or the row computes something different from the separate samples.

  1. A token may only attend to earlier tokens of its own sample. That needs a block-diagonal causal mask.
  2. Position ids restart at 0 for each sample.
  3. The first token of a sample is not a target for the last token of the previous one.
def block_causal_mask(seg_ids: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor:
    """(B, L) segment ids (-1 = padding) -> additive mask (B, 1, L, L): 0 where allowed, min where blocked."""
    L = seg_ids.shape[1]
    same = seg_ids.unsqueeze(2) == seg_ids.unsqueeze(1)                    # (B, L, L) same sample
    causal = torch.ones(L, L, dtype=torch.bool, device=seg_ids.device).tril()
    real = (seg_ids >= 0).unsqueeze(1)                                     # keys that are not padding
    allowed = same & causal & real
    # A padding query row would be all-blocked, which makes softmax NaN; let it see itself.
    allowed |= torch.eye(L, dtype=torch.bool, device=seg_ids.device)
    mask = torch.zeros(allowed.shape, dtype=dtype, device=seg_ids.device)
    return mask.masked_fill(~allowed, torch.finfo(dtype).min).unsqueeze(1)
Listing 28= torch.eye
    for b, row in enumerate(rows):
        pos = 0
        for s, i in enumerate(row):
            e = items[i]
            L = len(e.input_ids)
            input_ids[b, pos:pos + L] = torch.tensor(e.input_ids)
            lab = torch.tensor(e.labels)
            lab[0] = IGNORE  # rule 3: never predict across a sample boundary
            labels[b, pos:pos + L] = lab
            position_ids[b, pos:pos + L] = torch.arange(L)
            seg_ids[b, pos:pos + L] = s
            if e.pixel_values is not None:
                pix.append(e.pixel_values)
            tasks.append(e.task)
            meta.append(e.meta)
            pos += L
Listing 29Rules 2 and 3 in code. Pixel tiles are concatenated in slot order, so visual tokens stay correct with no extra work.

Build the mask yourself. Change the lengths, then turn the block mask off to see which pairs would leak.

Allowed pairs
Leaking pairs
Shape(1, 1, 18, 18)
Figure 10One packed row with a budget of 18 tokens, ported from block_causal_mask. Rows are queries and columns are keys. Blue cells may attend, red cells would leak between samples, and pale cells on the diagonal keep padding rows from producing NaN.
A packed batch (R rows, budget L, S samples)
TensorShapeMeaning
input_ids, labels(R, L)Samples end to end. The first label of each sample is -100.
position_ids(R, L)Restarts at 0 for each sample.
seg_ids(R, L)Which sample owns each position. -1 is padding.
attention_mask(R, 1, L, L)Additive: 0 where allowed, the most negative float where blocked.
pixel_values(n_tiles, 3, 224, 224)Tiles of all samples, row by row.

The trainer turns seg_ids into a sample index, so per_sample_loss works unchanged.

def make_batch(cfg: TrainConfig, proc: TinyVLMProcessor, samples: list[dict]) -> dict:
    enc = [proc.encode(s) for s in samples]
    if cfg.pack_budget:
        b = pack(enc, cfg.pack_budget, proc.pad_id)
        # sample k of the packed batch is (row, segment); number them in packing order
        offsets = torch.tensor([0] + [len(r) for r in b["rows"]]).cumsum(0)[:-1]
        b["sample_index"] = torch.where(b["seg_ids"] >= 0, b["seg_ids"] + offsets[:, None], -1)
        return b
    b = proc.collate(enc)
    b["sample_index"] = torch.where(b["attention_mask"] > 0,
                                    torch.arange(len(enc))[:, None].expand_as(b["input_ids"]), -1)
    return b
Listing 30One batch, padded or packed. Both paths produce a sample_index, so nothing later can tell them apart.

Samples with more than one image need nothing new. The processor expands each image slot in order and records tiles_per_image, and the tiles go into the same tensor. No training task in this tutorial uses more than one image, so this script only shows that the path works and what it costs, with real forward passes through C7’s model.

$ .venv/bin/python c08-vlm-training/scripts/multi_image.py
AMD EPYC 7R13 Processor, 8 threads
images            sizes                       tiles_per_image   slots        pixel_values              logits
one scene         224x224                     [1]                  49    (1, 3, 224, 224)             (1, 67)
scene + ocr       224x224, 336x224            [1, 3]              196    (4, 3, 224, 224)            (1, 214)
scene + doc       224x224, 448x448            [1, 5]              294    (6, 3, 224, 224)            (1, 312)
doc + doc + doc   448x448, 448x448, 448x448   [5, 5, 5]           735   (15, 3, 224, 224)            (1, 753)

Rows needed for 32 examples of each kind, by token budget:
images             tokens  budget 512  budget 1024
one scene              67           5            3
scene + ocr           214          16            8
scene + doc           312          32           11
doc + doc + doc       753    too long           32

Now the benchmark. The first table only counts tokens, and those numbers are exact. The second times real forward and backward passes, and those were taken while other jobs shared the machine. After that, two short CPU training runs check the trainer itself, padded and packed.

$ .venv/bin/python c08-vlm-training/benchmarks/bench_packing.py --n 480 --budget 512
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=train_packed steps=60 batch_size=8 eval_n=8 eval_every=0 replay_ratio=0 ppl_passages=0 pack_budget=512
480 samples, 49,251 real tokens, length min 68 / mean 103 / max 274
layout                      rows  positions   wasted
pad, random (B=8)            480     98,984    50.2%
pad, grouped (B=8)           480     50,040     1.6%
pack (budget 512)            100     51,200     3.8%

Timed forward + backward on AMD EPYC 7R13 Processor, 8 threads, 64 samples, 6,734 real tokens
layout                      seconds  real tok/s
pad, random                    29.3         230
pack                           21.3         316

The same script on the H100 prints the same counts. Only its timed lines differ.

Timed forward + backward on NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2, 64 samples, 6,734 real tokens
layout                      seconds  real tok/s
pad, random                     1.6       4,245
pack                            1.7       3,910
The trainer itself, padded and packed, 60 steps of batch 8 on the same samples. Computed from results/train_padded.json and results/train_packed.json. Another job shared this CPU, so the timing columns are not a speed comparison. One seed per row.
RunSeconds per stepReal tokens per secondPeak memoryScores on 8 test samples (caption, vqa)Hardware
Padded3.8621210,395 MB0.625, 0.500AMD EPYC 7R13, 8 threads
Packed, budget 5123.4024210,032 MB0.625, 0.500AMD EPYC 7R13, 8 threads

The token counts are exact. Padding in random order wastes 50.2% of positions, sorting by length wastes 1.6%, and packing into rows of 512 wastes 3.8%. So packing does not beat sorting on waste here. It needs 100 rows where padding needs 480.

The timings do not settle which layout is faster. They were taken while other jobs shared the machine. On the CPU, the packed layout ran at 316 real tokens per second against 230 padded, and on the H100 it ran at 3,910 against 4,245. We read neither gap as real.

The benchmark also runs each packed row alone, at batch 1, against padded batches of 8, so it does not compare equal shapes.

What the runs do support is correctness. The 60-step padded and packed training runs gave the same scores on 8 test samples, which is a weak check. The test test_packed_loss_equals_separate_samples is the strong one, because it shows that packed and separate losses agree to a relative 1e-4.

Checkpoint

  • You can name the three rules, and point to the line that enforces each.
  • test_block_causal_mask_by_hand, test_boundary_targets_are_ignored and test_break_it_without_the_block_mask_samples_leak pass.
Step 11

Place LoRA on any module

Goal Write one LoRA wrapper, then choose where it goes: language model, vision encoder, projector or a combination.

Freezing is all or nothing per block. LoRA gives a third option: leave a weight matrix frozen and train a small low-rank correction next to it. In a VLM the interesting decision is where the correction goes, because the three modules can fail in different ways.

Derivation inHow LoRA changes a model without rewriting it
class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int = 8, alpha: float = 16.0, dropout: float = 0.0):
        super().__init__()
        self.base = base
        self.base.requires_grad_(False)
        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))  # PEFT's default initialisation for A
        self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """(..., d_in) -> (..., d_out). The low-rank path costs r * (d_in + d_out) per token."""
        return self.base(x) + (self.dropout(x) @ self.lora_A.T @ self.lora_B.T) * self.scale
Listing 32The wrapper. B starts at zero, so a fresh wrap computes exactly what the base layer computed.

Figure 11The matrices inside one LoRALinear. The values are illustrative and use small sizes, so that each cell can be seen. The last frame uses the real parameter counts from param_report.py, at r = 16.

Placement is a regular expression over module names. Because apply_lora only looks at names, one function covers every combination.

TARGETS = {
    "lm": r"^lm\..*\.(q_proj|k_proj|v_proj|o_proj|gate_proj|up_proj|down_proj)$",
    "vision": r"^vision\..*\.(q_proj|k_proj|v_proj|out_proj|fc1|fc2)$",
    "projector": r"^projector\..*",
}
Listing 33The three placements. Vision excludes its embeddings, and the language model targets its attention and feed-forward projections.
Trainable parameters per LoRA placement at rank 16, without the new-token embedding rows. Computed from results/param_report.json, which scripts/param_report.py writes.
PlacementWrapped linearsTrainable parametersShare of all weights
LoRA on the language model2104,884,4802.15%
LoRA on the vision encoder722,654,2081.18%
LoRA on the projector276,8000.03%
LoRA on all three2847,615,4883.31%

The share divides by all weights including the LoRA factors. For the language model, 4,884,480 of 227,335,872 is 2.15%. Against the base model alone it is 2.20%.

These numbers add up by hand too. Per language-model layer, the wrapped layers at r = 16 are q and o (576 to 576), k and v (576 to 192), and the feed-forward gate, up and down (576 and 1536). That is 162,816 per layer, and 30 layers make 4,884,480.

One practical trap remains. With the language model’s weights frozen, the new <loc_k> embedding rows cannot learn, and the output layer is tied to them, so the model has almost no way to learn to choose one bin over another. The only route left is a change to the hidden state, for example through LoRA.

train_new_token_rows makes only those rows trainable, with a gradient hook. It starts at the first new token id, so the <image> row is trainable too.

def train_new_token_rows(model: nn.Module, first_new_id: int):
    """Let only the embedding rows of added tokens (<loc_k>, <image>) learn, the rest stay frozen.

    Needed when the LM is frozen or LoRA-adapted but the grounding format uses new tokens: without
    it the <loc_k> rows keep their initial values and the model cannot learn to emit them. The
    gradient of the old rows is zeroed by a hook. AdamW then leaves them untouched as long as their
    weight decay is 0, which optim.param_groups guarantees for embeddings.
    """
    emb = model.lm.get_input_embeddings().weight
    emb.requires_grad_(True)
    keep = torch.zeros(emb.shape[0], 1, device=emb.device, dtype=emb.dtype)
    keep[first_new_id:] = 1.0
    return emb.register_hook(lambda g: g * keep.to(g.device, g.dtype))
Listing 34The old rows get a zero gradient. AdamW leaves them alone only because embeddings have no weight decay, which is the choice we made in step 4.
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh lora_lm
# which runs, with results_dir=results/gpu out_dir=outputs/gpu added:
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=lora_lm init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 freeze=none "lora=[lm]" train_new_tokens=true

The other three runs change only the placement: [vision], [projector], and [lm,vision,projector]. Rank is 16 in all four. All four use the H100 and the same 250 steps of batch 16.

LoRA placements at rank 16, the same 250 steps of batch 16, no replay. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from results/gpu/lora_lm.json, lora_vision.json, lora_projector.json, lora_all.json. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Steps x batch, test samples per task
On the language model0.9450.8120.8540.1440.1250.000250 x 16, n=128
On vision0.5860.4451.9970.0050.0780.000250 x 16, n=128
On the projector0.8360.4611.9290.0160.0470.000250 x 16, n=128
On all three0.9610.8120.7810.1160.1330.000250 x 16, n=128

LoRA on the language model alone does about as well as training the language model on caption and VQA. It scores 0.945 on captions against 0.953, and 0.812 on VQA against 0.844 (previous tables, same 250 steps). Its OCR error is higher, 0.854 against 0.692, though neither run has learned OCR at this length. It trains 4.9M LoRA weights instead of 134.6M, with a learning rate of 2e-4 instead of 5e-5.

LoRA on the vision tower alone, or on the projector alone, did not learn the tasks. VQA is 0.445 and 0.461, against 0.812 to 0.844 for the other rows, a gap of more than 0.3. The standard error of that difference is about 0.056, while a single score near 0.8 has a standard error of 0.035. The OCR error is near 2, which means the answers are much longer than the true words.

In both runs the language model blocks are frozen. A likely reason is that the answer formats need the language model to adapt, but we did not test it.

LoRA on all three modules recovers the quality: caption 0.961, VQA 0.812, OCR error 0.781. That is within noise of the language-model-only row, so adding the other two placements gave no measurable gain here. Documents and charts are at or below the reference levels in all four runs, and grounding is zero, with no parsable answer.

All four runs use train_new_tokens=true. So the trainable counts in their result files include the 28.3M-weight embedding matrix, although a hook zeroes the gradient of every old row.

Checkpoint

  • param_report.py reports 210 wrapped linears on the language model and 72 on vision.
  • test_placements_touch_only_their_module passes for every combination.
Step 12

Teach the model to point

Goal Turn points, boxes and masks into text a language model can write, and parse them back without losing track of the error.

A language model can only point by writing tokens. So grounding needs an encoding from pixel geometry to text, and a decoder for the metric. We quantise coordinates into 32 bins across each side, which makes one bin 7 pixels on a 224-pixel image.

Theory inWhen language must point
def encode_box(box: Box, width: float, height: float, fmt: str = "tokens", bins: int = LOC_BINS) -> str:
    """Pixel box (x0, y0, x1, y1), right/bottom edges exclusive -> grounding string.

    The far edges are quantised through the last covered pixel (x1 - 0.5), so a box that fills
    bins 0..3 encodes as 0..3 and not 0..4.
    """
    q = [quantize(box[0], width, bins), quantize(box[1], height, bins),
         quantize(box[2] - 0.5, width, bins), quantize(box[3] - 0.5, height, bins)]
    return _format(q, fmt)
Listing 36Pixel box to grounding string. The far edge is quantised through the last covered pixel, so a box that fills bins 0 to 3 encodes as 0 to 3, not 0 to 4.
def decode_box(text: str, width: float, height: float, fmt: str = "tokens",
               bins: int = LOC_BINS) -> Box | None:
    """Grounding string -> pixel box, or None when the model did not write four coordinates.

    Bin k covers [k, k+1) * size / bins, so a box from bin a to bin b spans a's left edge to b's right
    edge. Using edges (not centres) makes encode -> decode lose at most one bin per side.
    """
    q = parse_coords(text, fmt)
    if len(q) < 4:
        return None
    x0, y0, x1, y1 = (min(max(v, 0), bins - 1) for v in q[:4])
    x0, x1 = sorted((x0, x1))
    y0, y1 = sorted((y0, y1))
    sx, sy = width / bins, height / bins
    return (x0 * sx, y0 * sy, (x1 + 1) * sx, (y1 + 1) * sy)
Listing 37Grounding string back to pixels. A model that writes fewer than four coordinates gets None, which the metric scores as zero and counts as a parse failure.

Two text formats carry exactly the same bins. The tokens format uses one new vocabulary item per coordinate, such as <loc_3>. The text format writes digits the language model already knows, such as [3, 10, 8, 15].

tokens format
text format
Decoded box
IoU with the truth
Figure 12A perfect answer, and what it scores. A model that writes the correct tokens still gets the decoded box, not the true one. Blue is the true box, shaded cells are the bins it covers, and orange is the decoded box. Ported from grounding.py. Shapes in the data are 28 to 56 pixels wide.

Points use the same bins, and they are scored by whether the decoded point lands inside the true box. Masks have no natural token form, so the model writes an outline: a flat list of quantised vertices. The true mask is stored as a COCO run-length encoding. In the grounding task, 60% of the samples ask for a box, 20% for a point and 20% for an outline.

def mask_to_rle(mask: np.ndarray) -> dict:
    """Binary mask (H, W) -> uncompressed COCO RLE {"size": [H, W], "counts": [...]}.

    COCO flattens in column-major (Fortran) order and the first count is the number of zeros,
    so a mask that starts with a foreground pixel begins with a 0 count.
    """
    flat = np.asarray(mask, dtype=bool).flatten(order="F")
    counts, prev, run = [], False, 0
    for v in flat:
        if v != prev:
            counts.append(run)
            prev, run = v, 0
        run += 1
    counts.append(run)
    return {"size": list(mask.shape), "counts": counts}
Listing 38COCO run-length encoding. It flattens in column order, and the first count is always the number of zeros.
def encode_polygon(points: list[tuple[float, float]], width: float, height: float,
                   fmt: str = "tokens", bins: int = LOC_BINS) -> str:
    """A mask outline as a flat list of quantised (x, y) vertices: one way to put a mask in text."""
    q: list[int] = []
    for x, y in points:
        q += [quantize(x, width, bins), quantize(y, height, bins)]
    return _format(q, fmt)
Listing 39A mask outline as a flat list of quantised vertices.
def polygon_to_mask(points: list[tuple[float, float]], width: int, height: int) -> np.ndarray:
    """Rasterise a polygon to a binary mask (H, W), so a generated outline can be scored with mask IoU."""
    m = Image.new("L", (width, height), 0)
    ImageDraw.Draw(m).polygon(points, fill=255)
    return np.array(m) > 0
Listing 40To score an outline, we rasterise it and compare it with the true mask using mask IoU.

Now the comparison: the same training on grounding alone, with only the format changed. We ran it at 250 steps of batch 16, and then again at 1,500 steps, because 250 steps gave almost no correct boxes. A third variant, loc_init=spread, gives each new location row the old mean plus noise with the vocabulary’s spread, so the rows start apart. It is opt-in, and the default is unchanged.

$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh ground_tokens ground_text ground_tokens_spread
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh ground_tokens_long ground_text_long ground_tokens_spread_long
# ground_text runs, with results_dir=results/gpu out_dir=outputs/gpu added:
$ .venv/bin/python c08-vlm-training/scripts/train.py c08-vlm-training/configs/stage2_mixture.yaml \
    name=ground_text init_from=outputs/gpu/stage1_align/trainable.safetensors steps=250 batch_size=16 \
    warmup=100 eval_n=128 eval_every=0 replay_ratio=0 ppl_passages=0 "tasks=[grounding]" grounding_format=text
Grounding only, three formats, the same held-out samples. The first six rows are an NVIDIA H100 80GB HBM3 and test 128 samples: 70 boxes, 29 points and 29 outlines. The last three rows are an AMD EPYC 7R13 with 8 threads and test 48 samples. Computed from the JSON files in results/gpu/ and results/. One seed per row.
RunSteps x batchBox acc at IoU 0.5Mean box IoUPoint in boxOutline mask IoUUnparsable answersHardware
New location tokens, default init250 x 160.0000.0020.1030.0000.047NVIDIA H100 80GB HBM3
New location tokens, loc_init=spread250 x 160.0000.0380.1030.0030.016NVIDIA H100 80GB HBM3
Plain digits250 x 160.0000.0450.0690.0400.000NVIDIA H100 80GB HBM3
New location tokens, default init1,500 x 160.0290.1040.1030.1130.000NVIDIA H100 80GB HBM3
New location tokens, loc_init=spread1,500 x 160.0570.1020.1380.0380.008NVIDIA H100 80GB HBM3
Plain digits1,500 x 160.0430.0830.1030.1090.000NVIDIA H100 80GB HBM3
New location tokens, default init200 x 40.0000.0000.0000.0001.000AMD EPYC 7R13, 8 threads
New location tokens, loc_init=spread200 x 40.0000.0100.0000.0000.521AMD EPYC 7R13, 8 threads
Plain digits200 x 40.0000.0310.1430.0050.000AMD EPYC 7R13, 8 threads

None of these models can ground in a way this data can tell from a fixed guess. In the main Stage 2 run, 0 of 70 boxes reach an IoU of 0.5, and 2 of 29 points land in the true box.

In the grounding-only runs after 1,500 steps, the default tokens get 2 of 70 boxes and 3 of 29 points. The spread tokens get 4 and 4, and plain digits get 3 and 3. With counts this small the three formats cannot be ranked. Their mean box IoU is 0.104, 0.102 and 0.083 in that order, which is also close.

We ran a control that uses no model. A constant box tuned on 600 training samples gets a mean IoU of 0.071 and hits 1 of 70 test boxes. A constant box tuned on the test samples themselves, which is an upper bound, gets 0.079 and 4 of 70, or 5 of 70 if tuned for hits.

A constant point gets 0 of 29 when tuned on training samples and 5 of 29 when tuned on the test samples. The saved majority-answer baseline in results/eval_gpu_stage2_main.json always answers <loc_13><loc_17> and gets 2 of 29.

So the main run's 2 of 29 equals that baseline, and the long runs' 3 to 4 of 29 are one or two samples above it. Their 2 to 4 of 70 boxes are within the range of a fixed guess. Their mean box IoU of 0.083 to 0.104 is slightly above the 0.057 to 0.079 of the constant boxes. We ran this control on the CPU with grounding_baseline.py, and the output is in the file grounding_baseline.txt.

Some predicted boxes in the long runs are close to the target, for example <loc_23><loc_17><loc_30><loc_25> for a target of <loc_23><loc_15><loc_31><loc_22>. Another is off by three or four bins on three of its four coordinates: <loc_17><loc_7><loc_23><loc_9> for <loc_14><loc_4><loc_19><loc_9>. Two examples do not show that the model has a skill.

The data cannot separate two readings. The model may be undertrained and would improve with more steps. Or it may have no grounding skill yet, and only learns the typical box position. We have no run that tells these apart.

The training loss for grounding is still falling at step 1,500. Its mean over the last ten logged steps is 2.06 for the default tokens and 1.38 for loc_init=spread. The text format's 0.42 is not comparable, because the formats have different token counts.

The long runs go over the same 4,000 training samples six times (24,000 samples). So a falling training loss there may be memorisation of those samples, not a skill that carries over to new images.

The main run drew about 1,600 grounding samples in 1,000 steps, against 24,000 in a long run. A likely cause of its 0.000 is that it saw about 15 times fewer grounding samples, but the control above shows that the long runs are barely better.

The starting spread of the new rows is a plausible mechanism for a slow start, but we did not isolate it. At 250 steps on the H100, the default tokens run does write coordinates (unparsable rate 0.047), and its first example for a box prompt is <loc_21><loc_21><loc_21><loc_21>, the same bin four times. At 1,500 steps the default init is not clearly worse than spread, at 2 against 4 of 70 boxes.

On the CPU, with 200 steps of batch 4, the default run never wrote a coordinate, and loc_init=spread cut the unparsable answers from 100% to 52%. That is one seed at 48 test samples. The lower training loss with spread points the same way. Its held-out scores do not show a clear gain, because the counts are too small.

The text format was evaluated with a 100-token generation limit and the tokens format with 24. A text-format outline needs up to 96 tokens, so a 24-token limit would have capped its mask IoU. Outline mask IoU is 0.04 to 0.11 after 1,500 steps, which is also low.

Checkpoint

  • encode_box((14, 70, 63, 112), 224, 224) gives <loc_2><loc_10><loc_8><loc_15>.
  • test_box_formats_carry_the_same_bins, test_malformed_output_does_not_parse and test_rle_roundtrip_and_coco_convention pass.

The training modes compared

Rows are the ways to choose what trains. The first columns are parameter counts from param_report.py, and they do not depend on hardware. Read across a row to see what each choice opens up, and what it puts at risk.

Freeze presets and LoRA placements on C7’s model. LoRA uses r = 16.
ModeVision trainableProjector trainableLM trainableShare of all weightsFits whenMain risk
Align02,102,40000.9%The projector is random.The towers cannot adapt, so quality has a low ceiling.
LM02,102,400134,551,87261.4%The image kinds suit the encoder.The language model forgets plain text.
Partial, top 428,353,0242,102,400134,551,87274.2%The images are unlike the encoder’s training data.Top blocks drift, and memory use grows.
Full85,797,1202,102,400134,551,872100.0%You have plenty of data and compute.Highest memory and the most ways to forget.
LoRA on LM004,884,4802.1%You want a small and reversible change.New tokens need train_new_token_rows.
LoRA on vision2,654,208001.2%Only perception needs to adapt.The language side stays fixed.
LoRA on projector076,80000.03%The projector is already aligned.Little capacity. Training the projector directly costs only 2.1M.
LoRA on all three2,654,20876,8004,884,4803.3%You want adaptation everywhere at low cost.More factors to tune, and more linears to wrap.

The last two columns are qualitative. They follow from what each mode can change, not from a measurement. The LoRA rows count only the LoRA factors. In the runs, train_new_tokens=true also made the 28.3M-weight embedding matrix a trainable tensor, with a hook that zeroes the gradient of the old rows.

The measured results for every run are in the next two tables, one for each machine. Read them with the limits from the start in mind: one seed, 250 steps for the comparisons, and 128 test samples. The differences that are clearly larger than noise are few.

VQA follows the share of draws in the mixture runs (0.906 down to 0.680). LoRA on the vision tower alone or on the projector alone is far worse than the other placements (VQA 0.445 and 0.461). Everything else in the comparison rows is within noise, or sits at a reference level, and the tables do not rank those methods.

Every GPU run behind this post. NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2. Computed from the JSON files in results/gpu/. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Text perplexity, before to afterSteps x batch, test samples per task
stage1_align0.980–––––not measured3,000 x 32, n=256
stage2_main0.9300.9530.0130.1910.1480.00035.32 to 23.191,000 x 16, n=128
stage2_noreplay0.9530.9450.0030.1970.1020.00035.32 to 49.851,000 x 16, n=128
freeze_lm0.9530.8440.6920.1960.1170.000not measured250 x 16, n=128
freeze_partial0.8980.8360.6120.1740.1330.000not measured250 x 16, n=128
freeze_full0.9610.8280.6700.2110.1250.000not measured250 x 16, n=128
mix_proportional0.9610.9060.7540.0520.1090.000not measured250 x 16, n=128
mix_uniform0.9610.7730.6210.2240.1250.000not measured250 x 16, n=128
mix_manual0.9300.6800.6680.1730.1330.000not measured250 x 16, n=128
res_tile––0.0550.188––not measured250 x 16, n=128
res_resize––0.0450.185––not measured250 x 16, n=128
lora_lm0.9450.8120.8540.1440.1250.000not measured250 x 16, n=128
lora_vision0.5860.4451.9970.0050.0780.000not measured250 x 16, n=128
lora_projector0.8360.4611.9290.0160.0470.000not measured250 x 16, n=128
lora_all0.9610.8120.7810.1160.1330.000not measured250 x 16, n=128
ground_tokens–––––0.000not measured250 x 16, n=128
ground_tokens_spread–––––0.000not measured250 x 16, n=128
ground_text–––––0.000not measured250 x 16, n=128
ground_tokens_long–––––0.029not measured1,500 x 16, n=128
ground_tokens_spread_long–––––0.057not measured1,500 x 16, n=128
ground_text_long–––––0.043not measured1,500 x 16, n=128
Every CPU run behind this post. AMD EPYC 7R13 Processor, 8 threads. Computed from the JSON files in results/. One seed per row.
Runcaption (exact match)vqa (exact match)ocr (CER, lower is better)doc (ANLS)chart (relaxed accuracy)grounding (acc at IoU 0.5)Text perplexity, before to afterSteps x batch, test samples per task
stage1_align0.797–––––not measured600 x 8, n=64
stage2_main0.8120.7290.4420.1380.1460.00038.37 to 28.78500 x 4, n=48
stage2_noreplay0.7290.7290.4500.2500.1250.00038.37 to 45.10500 x 4, n=48
stage2_replay_tokenmean0.7080.5620.8300.1350.1040.00038.37 to 31.61100 x 4, n=48
mix_temperature0.7290.6460.7870.1520.1040.000not measured200 x 4, n=48
mix_proportional0.7080.5620.8220.0210.1040.000not measured200 x 4, n=48
mix_uniform0.6250.5830.7530.2440.1250.000not measured200 x 4, n=48
mix_manual0.7080.5620.8030.2310.1250.000not measured200 x 4, n=48
freeze_partial (top 2 vision blocks)0.7080.6250.7730.1820.0830.000not measured200 x 4, n=48
freeze_full0.7080.6040.7890.1510.1040.000not measured200 x 4, n=48
ground_tokens–––––0.000not measured200 x 4, n=48
ground_tokens_spread–––––0.000not measured200 x 4, n=48
ground_text–––––0.000not measured200 x 4, n=48
res_tile––0.3470.268––not measured200 x 4, n=48
res_resize––0.2820.226––not measured200 x 4, n=48
lora_lm0.7500.5420.8080.0210.1040.000not measured150 x 4, n=48
lora_vision0.5620.1254.1620.0210.1040.000not measured150 x 4, n=48
lora_projector0.5830.4792.2900.0000.0830.000not measured150 x 4, n=48
lora_all0.7500.5420.8110.0210.1040.000not measured150 x 4, n=48
train_padded0.6250.5000.8450.1250.1250.000not measured60 x 8, n=8
train_packed0.6250.5000.8450.1250.1250.000not measured60 x 8, n=8

Run everything

The final folder, and every command that produced a number in this post.

c08-vlm-training/ final tree
c08-vlm-training/
├── README.md                # how to run everything, results table
├── conftest.py
├── configs/
│   ├── stage1_align.yaml    # projector only, captions only
│   └── stage2_mixture.yaml  # six tasks, 10% text replay
├── vlmtrain/
│   ├── synth/
│   │   ├── shapes.py        # scenes with exact geometry
│   │   ├── text.py          # rendered text and invoices
│   │   └── charts.py        # bar charts with known values
│   ├── data.py              # the unified sample format
│   ├── processor.py         # chat template, image tokens, loss mask
│   ├── tokenizer.py         # adds image and location tokens
│   ├── metrics.py           # exact match, CER, WER, ANLS, IoU
│   ├── evaluate.py          # one metric family per task
│   ├── freeze.py            # who trains, in each stage
│   ├── optim.py             # per-module learning rates
│   ├── train.py             # the staged trainer
│   ├── mixture.py           # four mixture strategies
│   ├── replay.py            # text replay, forgetting check
│   ├── resolution.py        # resize, pad, tile
│   ├── packing.py           # budgets and block-causal masks
│   ├── lora.py              # LoRA on any module
│   ├── grounding.py         # points, boxes, masks as tokens
│   ├── c07_adapter.py       # the only file that touches C7
│   ├── model.py             # standalone model, same contract
│   └── device.py
├── scripts/
│   ├── train.py             # one stage from a YAML config
│   ├── run_all.sh           # every CPU run behind the numbers
│   ├── run_gpu.sh           # the H100 runs, one job per GPU
│   ├── evaluate.py          # a checkpoint against two controls
│   ├── inspect_batch.py     # prints what is in the tensors
│   ├── param_report.py      # trainable parameters per preset
│   ├── break_it.py          # each failure, on purpose
│   ├── multi_image.py       # several images in one example
│   └── show_samples.py
├── benchmarks/
│   ├── bench_packing.py
│   └── bench_resolution.py
├── results/                 # real logs and JSON; gpu/ holds the H100 runs
└── tests/                   # one test file per module
$ .venv/bin/python -m pytest c08-vlm-training -m "not slow and not gpu and not network" -q
$ .venv/bin/python -m pytest c08-vlm-training -m network -q    # downloads the real SigLIP and SmolLM2 weights
$ c08-vlm-training/scripts/run_all.sh                # every CPU run, one at a time
$ c08-vlm-training/scripts/run_all.sh stage2         # or one group: stage1, stage2, mixture, freeze, grounding, resolution, lora, packing
$ c08-vlm-training/scripts/run_all.sh capture        # logs, benchmarks, controls and every Break it
$ CUDA_VISIBLE_DEVICES=0 bash c08-vlm-training/scripts/run_gpu.sh stage1_align    # GPU jobs: stage1_align first, then any other job

The tests pass: 130 offline and 5 with the real weights, and there are no slow or GPU tests. The log below is the saved capture on the CPU. The GPU jobs write to results/gpu/: 21 training runs, the evaluation of the main run, and two benchmarks.

$ pytest c08-vlm-training -m "not slow and not gpu and not network"   (AMD EPYC 7R13, 8 threads)
..........................................................               [100%]
130 passed, 5 deselected in 35.75s

$ pytest c08-vlm-training -m network   (real SigLIP + SmolLM2 weights)
.....                                                                    [100%]
5 passed, 130 deselected in 35.02s

What these runs do not show

The runs are smaller than the plan, and several things were never measured. This is the list, so that the tables above are not read as more than they are.

The real runs also exposed bugs that the tests on tiny models had missed. A lrs.vision=1e-5 override was read as a string, which crashed the first freeze_partial run, and parse_value now returns a float. The standalone model loaded SigLIP with an argument the class rejects, and loaded the language model in bfloat16 while the rest ran in float32.

On the CPU, grounding never produced a coordinate with the default <loc_k> initialisation, which led to the opt-in loc_init=spread. A single generation limit of 24 tokens would have capped text-format outlines, so each grounding format now has its own limit. And mask outlines gained a decoder, a scorer and a training task, because they had an encoder and nothing else.

Key insights and nuances

Exercises

  1. Add a seventh taskMedium Write a generator for a new kind of image, such as a small table with a question about one cell. Add a size to TASK_SIZES and a metric to score. Check that no other file needs to change.
    Hint

    If you find yourself editing the trainer, the sample format has leaked. Everything a metric needs belongs in meta.

  2. Make the mixture respond to the task lossesHard The trainer already logs a loss per task. Raise the probability of tasks whose loss has stopped falling, and compare the final metrics with T = 2 on the same number of steps.
    Hint

    Change the probabilities in MixtureSampler between log intervals. Compare mixture_observed with supervised_token_share so you can see what really changed.

  3. Find the best budgetMedium Run bench_packing.py at budgets from 274 to 1024. Plot real tokens per second against budget, and explain the shape using the attention pair count from figure 9.
  4. Unfreeze against LoRA for documentsMedium Train on [doc,ocr] with the top two vision blocks unfrozen, then with LoRA on vision. Compare ANLS, trainable parameters and checkpoint size. Our own runs never learned documents, so expect ANLS near the grey-image level unless you train much longer.
  5. Measure the noiseEasy Run freeze_lm three more times with seed=1, seed=2 and seed=3. Report the spread of each score, and decide which differences in the comparison tables survive it.
    Hint

    Use the same overrides as the H100 comparison runs and change only seed and name. Compare the spread with the binomial standard error of about 0.04 at 128 samples.

  6. Measure the grounding ceilingEasy Using only encode_box, decode_box and box_iou, measure the best possible accuracy at IoU 0.5 and 0.75 for bins of 16, 32 and 64 on the boxes the generator draws. No model is needed.

Continue reading

References

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

Models used here