What you will build
blog-coding-tutorials/c08-vlm-trainingA 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.
- Theory first
- 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.
| Run | Hardware | Steps x batch | Test samples per task | Plan |
|---|---|---|---|---|
| Stage 1 alignment | NVIDIA H100 80GB HBM3 | 3,000 x 32 | 256 | 3,000 steps; 256 samples |
| Stage 2 main run and no-replay run | NVIDIA H100 80GB HBM3 | 1,000 x 16 | 128 | 8,000 steps; 256 samples |
| Comparisons: freeze, mixture, LoRA, resolution, grounding | NVIDIA H100 80GB HBM3 | 250 x 16 | 128 | 2,000 steps; 256 samples |
| Longer grounding-only runs | NVIDIA H100 80GB HBM3 | 1,500 x 16 | 128 | added after the 250-step runs |
| Stage 1 alignment | AMD EPYC 7R13, 8 threads | 600 x 8 | 64 | – |
| Stage 2 main run and no-replay run | AMD EPYC 7R13, 8 threads | 500 x 4 | 48 (64 in the controls) | – |
| Comparisons: freeze, mixture, resolution, grounding | AMD EPYC 7R13, 8 threads | 200 x 4 | 48 | – |
| Comparisons: LoRA | AMD EPYC 7R13, 8 threads | 150 x 4 | 48 | – |
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
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}")
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()))
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)
Here is sample 0 of every task, rendered by those generators. Pick a task to see its image and its dict.
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}
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", {}))
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.
- A document costs 245 visual tokens. A chart costs 49. One long sample sets the width of the whole batch, which is why 60.3% of this batch is padding.
- Only 3.2% of all positions are targets. The rest of the batch is context.
- There are 12 tiles in
pixel_valuesand 7 samples. The tile tensor has no batch dimension of its own. Tiles are stacked in the order their tokens appear.
| Tensor | Shape | Meaning |
|---|---|---|
| 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. |
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
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 dodef 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
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)
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)
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
| Task | Headline metric | Also recorded | Direction |
|---|---|---|---|
| caption | Exact match | – | Higher is better |
| vqa | Exact match after normalising | – | Higher is better |
| ocr | CER | WER, exact match | Lower is better |
| doc | ANLS | Exact match | Higher is better |
| chart | Relaxed accuracy at 5% | – | Higher is better |
| grounding | Accuracy at IoU 0.5 | Mean IoU, point in box, mask IoU, parse failures | Higher 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.
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.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)
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())
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
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.
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 seeThe 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
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
| Tensor | Shape | Meaning |
|---|---|---|
| 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. |
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()
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/
| Run | Hardware | Steps x batch | Caption loss, first to last step | Caption exact match | Test samples | Checkpoint |
|---|---|---|---|---|---|---|
| CPU | AMD EPYC 7R13, 8 threads | 600 x 8 | 3.09 to 0.05 | 0.797 | 64 | 8.0 MB |
| GPU | NVIDIA H100 80GB HBM3 | 3,000 x 32 | 3.26 to 0.01 | 0.980 | 256 | 8.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
| Task | Metric | Real images | Grey images | No model | The no-model answer |
|---|---|---|---|---|---|
| caption | exact match | 0.797 | 0.000 | 0.062 | A purple triangle. |
| Task | Question | True answer | Model answer |
|---|---|---|---|
| caption | Describe the image. | A red circle and a yellow triangle. | A red circle and a yellow triangle. |
| caption | What is in this picture? | An orange triangle. | An orange triangle. |
| caption | What 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.
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 capabilitiesdef 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()}
| Task | Corpus size | Proportional | Temperature, T = 2 | Temperature, T = 4 | Uniform | Manual (1, 1, 2, 3, 2, 3) |
|---|---|---|---|---|---|---|
| caption | 40,000 | 53.3% | 35.1% | 25.4% | 16.7% | 8.3% |
| vqa | 20,000 | 26.7% | 24.8% | 21.3% | 16.7% | 8.3% |
| ocr | 8,000 | 10.7% | 15.7% | 17.0% | 16.7% | 16.7% |
| doc | 1,000 | 1.3% | 5.5% | 10.1% | 16.7% | 25.0% |
| chart | 2,000 | 2.7% | 7.8% | 12.0% | 16.7% | 16.7% |
| grounding | 4,000 | 5.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.
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
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
| Run | caption (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 |
|---|---|---|---|---|---|---|---|
| Proportional | 0.961 | 0.906 | 0.754 | 0.052 | 0.109 | 0.000 | 250 x 16, n=128 |
| Temperature, T = 2 | 0.953 | 0.844 | 0.692 | 0.196 | 0.117 | 0.000 | 250 x 16, n=128 |
| Uniform | 0.961 | 0.773 | 0.621 | 0.224 | 0.125 | 0.000 | 250 x 16, n=128 |
| Manual | 0.930 | 0.680 | 0.668 | 0.173 | 0.133 | 0.000 | 250 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.
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
$ .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.
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.| Run | caption (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 after | Steps x batch, test samples per task |
|---|---|---|---|---|---|---|---|---|
| T = 2 mixture, 10% replay | 0.930 | 0.953 | 0.013 | 0.191 | 0.148 | 0.000 | 35.32 to 23.19 | 1,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
| Task | Metric | GPU real | GPU grey | GPU no model | CPU real | CPU grey | CPU no model |
|---|---|---|---|---|---|---|---|
| caption | exact match | 0.930 | 0.023 | 0.047 | 0.828 | 0.031 | 0.062 |
| vqa | exact match | 0.953 | 0.234 | 0.250 | 0.719 | 0.438 | 0.281 |
| ocr | CER, lower is better | 0.013 | 0.847 | 0.891 | 0.469 | 0.830 | 0.896 |
| doc | ANLS | 0.191 | 0.197 | 0.031 | 0.167 | 0.202 | 0.016 |
| chart | relaxed accuracy | 0.148 | 0.117 | 0.125 | 0.125 | 0.031 | 0.125 |
| grounding | acc at IoU 0.5 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 | 0.000 |
| Step | caption (exact match) | vqa (exact match) | ocr (CER, lower is better) | doc (ANLS) | chart (relaxed accuracy) |
|---|---|---|---|---|---|
| 500 | 0.917 | 0.896 | 0.123 | 0.186 | 0.167 |
| 1,000 | 0.930 | 0.953 | 0.013 | 0.191 | 0.148 |
| Task | Question | True answer | Model answer |
|---|---|---|---|
| caption | Describe the image. | A red circle and a yellow triangle. | A red circle and a yellow triangle. |
| caption | What is in this picture? | An orange triangle. | An orange triangle. |
| vqa | How many shapes are there? Answer with one word. | 5 | 5 |
| vqa | How many green squares are there? Answer with one word. | 1 | 1 |
| ocr | What does the text in the image say? | pearl oyster | pearl oyster |
| ocr | What does the text in the image say? | square pearl | square pearl |
| doc | What is the total? | 79.50 | 32.50 |
| doc | How many items are on the invoice? | 5 | 1 |
| chart | What is the value of yak? | 5 | 1 |
| chart | What is the value of fox? | 4 | 1 |
| grounding | Point to the green circle. | <loc_17><loc_14> | <loc_15><loc_15> |
| grounding | Find 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
| Run | caption (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 frozen | 0.953 | 0.844 | 0.692 | 0.196 | 0.117 | 0.000 | 250 x 16, n=128 |
| Top 4 vision blocks train | 0.898 | 0.836 | 0.612 | 0.174 | 0.133 | 0.000 | 250 x 16, n=128 |
| Everything trains | 0.961 | 0.828 | 0.670 | 0.211 | 0.125 | 0.000 | 250 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).
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
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)
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
| Run | caption (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 after | Steps x batch, test samples per task |
|---|---|---|---|---|---|---|---|---|
| 10% replay | 0.930 | 0.953 | 0.013 | 0.191 | 0.148 | 0.000 | 35.32 to 23.19 | 1,000 x 16, n=128 |
| No replay | 0.953 | 0.945 | 0.003 | 0.197 | 0.102 | 0.000 | 35.32 to 49.85 | 1,000 x 16, n=128 |
| Run | Hardware | Steps x batch, passages | Perplexity before | Perplexity after | Change |
|---|---|---|---|---|---|
| 10% replay | NVIDIA H100 80GB HBM3 | 1,000 x 16, 128 | 35.32 | 23.19 | -12.13 |
| No replay | NVIDIA H100 80GB HBM3 | 1,000 x 16, 128 | 35.32 | 49.85 | +14.53 |
| 10% replay | AMD EPYC 7R13, 8 threads | 500 x 4, 64 | 38.37 | 28.78 | -9.58 |
| No replay | AMD EPYC 7R13, 8 threads | 500 x 4, 64 | 38.37 | 45.10 | +6.73 |
| 10% replay, token-mean loss | AMD EPYC 7R13, 8 threads | 100 x 4, 64 | 38.37 | 31.61 | -6.76 |
| Task | Target share of samples | Observed share of samples | Share of supervised tokens |
|---|---|---|---|
| caption | 31.6% | 31.5% | 22.7% |
| vqa | 22.3% | 22.2% | 3.1% |
| ocr | 14.1% | 14.4% | 3.5% |
| doc | 5.0% | 4.9% | 1.9% |
| chart | 7.1% | 7.2% | 1.0% |
| grounding | 10.0% | 10.1% | 4.4% |
| text | 10.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.
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 picturedef 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
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
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.| Strategy | pixel_values | Visual tokens | What is lost |
|---|---|---|---|
| resize | (1, 3, 224, 224) | 49 | Half the resolution. Aspect ratio if the image is not square. |
| pad | (1, 3, 224, 224) | 49 | The same resolution loss, plus pixels spent on padding if the image is not square. |
| tile | (5, 3, 224, 224) | 245 | Nothing 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
| Run | ocr (CER, lower is better) | doc (ANLS) | Steps x batch, test samples per task, hardware |
|---|---|---|---|
| Tile | 0.055 | 0.188 | 250 x 16, n=128, NVIDIA H100 80GB HBM3 |
| Resize | 0.045 | 0.185 | 250 x 16, n=128, NVIDIA H100 80GB HBM3 |
| Tile | 0.347 | 0.268 | 200 x 4, n=48, AMD EPYC 7R13, 8 threads |
| Resize | 0.282 | 0.226 | 200 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.
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
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.
- A token may only attend to earlier tokens of its own sample. That needs a block-diagonal causal mask.
- Position ids restart at 0 for each sample.
- 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)
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
Build the mask yourself. Change the lengths, then turn the block mask off to see which pairs would leak.
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.| Tensor | Shape | Meaning |
|---|---|---|
| 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
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
| Run | Seconds per step | Real tokens per second | Peak memory | Scores on 8 test samples (caption, vqa) | Hardware |
|---|---|---|---|---|---|
| Padded | 3.86 | 212 | 10,395 MB | 0.625, 0.500 | AMD EPYC 7R13, 8 threads |
| Packed, budget 512 | 3.40 | 242 | 10,032 MB | 0.625, 0.500 | AMD 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.
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 itclass 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
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\..*",
}
| Placement | Wrapped linears | Trainable parameters | Share of all weights |
|---|---|---|---|
| LoRA on the language model | 210 | 4,884,480 | 2.15% |
| LoRA on the vision encoder | 72 | 2,654,208 | 1.18% |
| LoRA on the projector | 2 | 76,800 | 0.03% |
| LoRA on all three | 284 | 7,615,488 | 3.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))
$ 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.
| Run | caption (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 model | 0.945 | 0.812 | 0.854 | 0.144 | 0.125 | 0.000 | 250 x 16, n=128 |
| On vision | 0.586 | 0.445 | 1.997 | 0.005 | 0.078 | 0.000 | 250 x 16, n=128 |
| On the projector | 0.836 | 0.461 | 1.929 | 0.016 | 0.047 | 0.000 | 250 x 16, n=128 |
| On all three | 0.961 | 0.812 | 0.781 | 0.116 | 0.133 | 0.000 | 250 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.
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 pointdef 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)
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)
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].
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}
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)
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
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
| Run | Steps x batch | Box acc at IoU 0.5 | Mean box IoU | Point in box | Outline mask IoU | Unparsable answers | Hardware |
|---|---|---|---|---|---|---|---|
| New location tokens, default init | 250 x 16 | 0.000 | 0.002 | 0.103 | 0.000 | 0.047 | NVIDIA H100 80GB HBM3 |
New location tokens, loc_init=spread | 250 x 16 | 0.000 | 0.038 | 0.103 | 0.003 | 0.016 | NVIDIA H100 80GB HBM3 |
| Plain digits | 250 x 16 | 0.000 | 0.045 | 0.069 | 0.040 | 0.000 | NVIDIA H100 80GB HBM3 |
| New location tokens, default init | 1,500 x 16 | 0.029 | 0.104 | 0.103 | 0.113 | 0.000 | NVIDIA H100 80GB HBM3 |
New location tokens, loc_init=spread | 1,500 x 16 | 0.057 | 0.102 | 0.138 | 0.038 | 0.008 | NVIDIA H100 80GB HBM3 |
| Plain digits | 1,500 x 16 | 0.043 | 0.083 | 0.103 | 0.109 | 0.000 | NVIDIA H100 80GB HBM3 |
| New location tokens, default init | 200 x 4 | 0.000 | 0.000 | 0.000 | 0.000 | 1.000 | AMD EPYC 7R13, 8 threads |
New location tokens, loc_init=spread | 200 x 4 | 0.000 | 0.010 | 0.000 | 0.000 | 0.521 | AMD EPYC 7R13, 8 threads |
| Plain digits | 200 x 4 | 0.000 | 0.031 | 0.143 | 0.005 | 0.000 | AMD 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.
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.
| Mode | Vision trainable | Projector trainable | LM trainable | Share of all weights | Fits when | Main risk |
|---|---|---|---|---|---|---|
| Align | 0 | 2,102,400 | 0 | 0.9% | The projector is random. | The towers cannot adapt, so quality has a low ceiling. |
| LM | 0 | 2,102,400 | 134,551,872 | 61.4% | The image kinds suit the encoder. | The language model forgets plain text. |
| Partial, top 4 | 28,353,024 | 2,102,400 | 134,551,872 | 74.2% | The images are unlike the encoder’s training data. | Top blocks drift, and memory use grows. |
| Full | 85,797,120 | 2,102,400 | 134,551,872 | 100.0% | You have plenty of data and compute. | Highest memory and the most ways to forget. |
| LoRA on LM | 0 | 0 | 4,884,480 | 2.1% | You want a small and reversible change. | New tokens need train_new_token_rows. |
| LoRA on vision | 2,654,208 | 0 | 0 | 1.2% | Only perception needs to adapt. | The language side stays fixed. |
| LoRA on projector | 0 | 76,800 | 0 | 0.03% | The projector is already aligned. | Little capacity. Training the projector directly costs only 2.1M. |
| LoRA on all three | 2,654,208 | 76,800 | 4,884,480 | 3.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.
| Run | caption (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 after | Steps x batch, test samples per task |
|---|---|---|---|---|---|---|---|---|
| stage1_align | 0.980 | – | – | – | – | – | not measured | 3,000 x 32, n=256 |
| stage2_main | 0.930 | 0.953 | 0.013 | 0.191 | 0.148 | 0.000 | 35.32 to 23.19 | 1,000 x 16, n=128 |
| stage2_noreplay | 0.953 | 0.945 | 0.003 | 0.197 | 0.102 | 0.000 | 35.32 to 49.85 | 1,000 x 16, n=128 |
| freeze_lm | 0.953 | 0.844 | 0.692 | 0.196 | 0.117 | 0.000 | not measured | 250 x 16, n=128 |
| freeze_partial | 0.898 | 0.836 | 0.612 | 0.174 | 0.133 | 0.000 | not measured | 250 x 16, n=128 |
| freeze_full | 0.961 | 0.828 | 0.670 | 0.211 | 0.125 | 0.000 | not measured | 250 x 16, n=128 |
| mix_proportional | 0.961 | 0.906 | 0.754 | 0.052 | 0.109 | 0.000 | not measured | 250 x 16, n=128 |
| mix_uniform | 0.961 | 0.773 | 0.621 | 0.224 | 0.125 | 0.000 | not measured | 250 x 16, n=128 |
| mix_manual | 0.930 | 0.680 | 0.668 | 0.173 | 0.133 | 0.000 | not measured | 250 x 16, n=128 |
| res_tile | – | – | 0.055 | 0.188 | – | – | not measured | 250 x 16, n=128 |
| res_resize | – | – | 0.045 | 0.185 | – | – | not measured | 250 x 16, n=128 |
| lora_lm | 0.945 | 0.812 | 0.854 | 0.144 | 0.125 | 0.000 | not measured | 250 x 16, n=128 |
| lora_vision | 0.586 | 0.445 | 1.997 | 0.005 | 0.078 | 0.000 | not measured | 250 x 16, n=128 |
| lora_projector | 0.836 | 0.461 | 1.929 | 0.016 | 0.047 | 0.000 | not measured | 250 x 16, n=128 |
| lora_all | 0.961 | 0.812 | 0.781 | 0.116 | 0.133 | 0.000 | not measured | 250 x 16, n=128 |
| ground_tokens | – | – | – | – | – | 0.000 | not measured | 250 x 16, n=128 |
| ground_tokens_spread | – | – | – | – | – | 0.000 | not measured | 250 x 16, n=128 |
| ground_text | – | – | – | – | – | 0.000 | not measured | 250 x 16, n=128 |
| ground_tokens_long | – | – | – | – | – | 0.029 | not measured | 1,500 x 16, n=128 |
| ground_tokens_spread_long | – | – | – | – | – | 0.057 | not measured | 1,500 x 16, n=128 |
| ground_text_long | – | – | – | – | – | 0.043 | not measured | 1,500 x 16, n=128 |
| Run | caption (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 after | Steps x batch, test samples per task |
|---|---|---|---|---|---|---|---|---|
| stage1_align | 0.797 | – | – | – | – | – | not measured | 600 x 8, n=64 |
| stage2_main | 0.812 | 0.729 | 0.442 | 0.138 | 0.146 | 0.000 | 38.37 to 28.78 | 500 x 4, n=48 |
| stage2_noreplay | 0.729 | 0.729 | 0.450 | 0.250 | 0.125 | 0.000 | 38.37 to 45.10 | 500 x 4, n=48 |
| stage2_replay_tokenmean | 0.708 | 0.562 | 0.830 | 0.135 | 0.104 | 0.000 | 38.37 to 31.61 | 100 x 4, n=48 |
| mix_temperature | 0.729 | 0.646 | 0.787 | 0.152 | 0.104 | 0.000 | not measured | 200 x 4, n=48 |
| mix_proportional | 0.708 | 0.562 | 0.822 | 0.021 | 0.104 | 0.000 | not measured | 200 x 4, n=48 |
| mix_uniform | 0.625 | 0.583 | 0.753 | 0.244 | 0.125 | 0.000 | not measured | 200 x 4, n=48 |
| mix_manual | 0.708 | 0.562 | 0.803 | 0.231 | 0.125 | 0.000 | not measured | 200 x 4, n=48 |
| freeze_partial (top 2 vision blocks) | 0.708 | 0.625 | 0.773 | 0.182 | 0.083 | 0.000 | not measured | 200 x 4, n=48 |
| freeze_full | 0.708 | 0.604 | 0.789 | 0.151 | 0.104 | 0.000 | not measured | 200 x 4, n=48 |
| ground_tokens | – | – | – | – | – | 0.000 | not measured | 200 x 4, n=48 |
| ground_tokens_spread | – | – | – | – | – | 0.000 | not measured | 200 x 4, n=48 |
| ground_text | – | – | – | – | – | 0.000 | not measured | 200 x 4, n=48 |
| res_tile | – | – | 0.347 | 0.268 | – | – | not measured | 200 x 4, n=48 |
| res_resize | – | – | 0.282 | 0.226 | – | – | not measured | 200 x 4, n=48 |
| lora_lm | 0.750 | 0.542 | 0.808 | 0.021 | 0.104 | 0.000 | not measured | 150 x 4, n=48 |
| lora_vision | 0.562 | 0.125 | 4.162 | 0.021 | 0.104 | 0.000 | not measured | 150 x 4, n=48 |
| lora_projector | 0.583 | 0.479 | 2.290 | 0.000 | 0.083 | 0.000 | not measured | 150 x 4, n=48 |
| lora_all | 0.750 | 0.542 | 0.811 | 0.021 | 0.104 | 0.000 | not measured | 150 x 4, n=48 |
| train_padded | 0.625 | 0.500 | 0.845 | 0.125 | 0.125 | 0.000 | not measured | 60 x 8, n=8 |
| train_packed | 0.625 | 0.500 | 0.845 | 0.125 | 0.125 | 0.000 | not measured | 60 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.
- A full-scale Stage 2. The plan was 8,000 steps. The numbers here are for 1,000 steps, and the OCR error was still falling at the end.
- bf16 or fp16. Every run is float32, and the trainer has no mixed precision.
- More than one seed. Every difference between two runs is a single-run difference, so it can be noise.
- Real data. Everything is rendered shapes, words, invoices and bar charts. The scores do not predict how a model would do on photographs or scans.
- A speed comparison. Both machines were shared with other jobs. Only the quality numbers compare across rows.
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
- One text passage can outweigh six visual samples. In our batch of 7, it holds 34 of the 62 target tokens, so how you average the loss is a choice about tasks. Step 2
- A soft metric can hide a wrong answer. One wrong digit in a date scores 0.9 on ANLS and 0 on exact match. On our integer charts, the 5% tolerance of relaxed accuracy never applies. Step 3
- The embedding matrix is also the output layer. Its 28.3M weights are shared, so the softmax sends a gradient to every row, including words our tasks never use. Step 4
- Frozen does not mean out of the graph. Stage 1 trains 0.9% of the weights, and it still pays for a backward pass through the whole language model. Step 5
- A mixture is a choice about updates and about repeats. The Stage 2 main run stays below one epoch of every corpus (at most 0.8), but Stage 1 makes 2.4 epochs over its captions and the long grounding runs make 6.0 over 4,000 samples, so memorisation was possible there and we did not measure it. In the 250-step runs, the VQA score followed the share of VQA draws, from 0.906 at 26.7% to 0.680 at 8.3%. Step 6
- A score above zero is not a learned task. On the H100 run, documents score 0.191 with real images and 0.197 with grey images, and charts score 0.148 against 0.125 for a fixed answer. The grey-image and no-model controls found both failures. Step 7
- Replay flatters the forgetting number. With replay, perplexity falls from 35.32 to 23.19, partly because the replay text and the test text are the same kind of writing. The run without replay (35.32 to 49.85) is the real forgetting measure. Step 8
- Tiling also distorts. A 336 by 224 image is stretched 33% to fit a 1 by 2 grid. Step 9
- Packing removes positions, not attention pairs. Our batch drops from 1,918 positions to 1,024, while pairs stay near 525,000. Step 10
- LoRA only on the vision tower, or only on the projector, did not learn the tasks in 250 steps. With the language model blocks frozen, VQA was 0.445 and 0.461 against 0.812 for LoRA on the language model. Step 11
- A perfect grounding answer does not score 1. With 32 bins, a perfect answer on a 28-pixel square can score an IoU of 0.64. Step 12
- Grounding is not shown to work. After 1,500 steps, 2 to 4 of 70 boxes are correct, and a fixed box with no model gets 1 to 5 of 70. The data cannot separate undertrained from no skill yet. The 32 new location rows start 3.2e-6 apart, a plausible cause that we did not isolate. Step 12
Exercises
- 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_SIZESand a metric toscore. 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. - 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
MixtureSamplerbetween log intervals. Comparemixture_observedwithsupervised_token_shareso you can see what really changed. - Find the best budgetMedium Run
bench_packing.pyat budgets from 274 to 1024. Plot real tokens per second against budget, and explain the shape using the attention pair count from figure 9. - 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. - Measure the noiseEasy Run
freeze_lmthree more times withseed=1,seed=2andseed=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
seedandname. Compare the spread with the binomial standard error of about 0.04 at 128 samples. - Measure the grounding ceilingEasy Using only
encode_box,decode_boxandbox_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
- Post-Train a VLM: the next tutorial, with preferences, hallucination negatives and visual RL on a real pretrained model.
- Build a Vision-Language Model From Scratch: the model this tutorial trains.
- Mixing data without losing capabilities: the theory behind step 6 and step 8.
- The cost of a picture: why visual tokens set the budget in step 9 and step 10.
References
Grouped by topic. Every entry links to its primary source.
Staged VLM training
- Visual Instruction Tuning (LLaVA) · Liu et al., 2023
- Improved Baselines with Visual Instruction Tuning (LLaVA-1.5) · Liu et al., 2023
- Building and better understanding vision-language models: insights and future directions · Laurençon et al., 2024
Models used here
- Sigmoid Loss for Language Image Pre-Training (SigLIP) · Zhai et al., 2023
- SmolLM2-135M-Instruct · Hugging Face, model card
- SmolVLM: Redefining small and efficient multimodal models · Marafioti et al., 2025
Tiling and grounding formats
- InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks · Chen et al., 2023
- PaliGemma: A versatile 3B VLM for transfer · Beyer et al., 2024
- Qwen2-VL: Enhancing Vision-Language Model’s Perception of the World at Any Resolution · Wang et al., 2024
- Molmo and PixMo: Open Weights and Open Data for State-of-the-Art Vision-Language Models · Deitke et al., 2024
Evaluation
- VQA: Visual Question Answering · Antol et al., 2015
- DocVQA: A Dataset for VQA on Document Images · Mathew et al., 2020
- ChartQA: A Benchmark for Question Answering about Charts with Visual and Logical Reasoning · Masry et al., 2022
- Microsoft COCO: Common Objects in Context · Lin et al., 2014
LoRA and mixtures
- LoRA: Low-Rank Adaptation of Large Language Models · Hu et al., 2021
- Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (T5) · Raffel et al., 2020
- blog-coding-tutorials: c08-vlm-training · the code for this tutorial